From 137231c95e30bc179ee581aa0320f2ba1b12f655 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 25 Nov 2020 21:30:00 +1100 Subject: [PATCH 01/12] cs-fixer --- app/Console/Commands/CheckData.php | 12 +- app/Console/Commands/CreateSingleAccount.php | 29 ++-- app/Console/Commands/CreateTestData.php | 3 - app/Console/Commands/DemoMode.php | 8 +- app/Console/Commands/PostUpdate.php | 2 - app/Console/Commands/SendRemindersCron.php | 5 +- app/Console/Commands/SendTestEmails.php | 1 - app/DataMapper/CompanySettings.php | 14 +- app/DataMapper/EmailTemplateDefaults.php | 4 - app/Factory/TaskFactory.php | 6 +- app/Filters/SystemLogFilters.php | 2 - app/Helpers/Invoice/InvoiceItemSum.php | 4 +- app/Helpers/Invoice/InvoiceSum.php | 20 +-- app/Helpers/Invoice/InvoiceSumInclusive.php | 18 ++- .../Auth/ContactLoginController.php | 1 - app/Http/Controllers/Auth/LoginController.php | 3 +- app/Http/Controllers/BaseController.php | 29 ++-- .../ContactHashLoginController.php | 5 - .../ClientPortal/InvitationController.php | 12 +- .../ClientPortal/PaymentController.php | 56 ++++--- app/Http/Controllers/CompanyController.php | 5 +- app/Http/Controllers/CreditController.php | 2 +- app/Http/Controllers/EmailController.php | 4 - app/Http/Controllers/InvoiceController.php | 3 +- app/Http/Controllers/MigrationController.php | 2 - app/Http/Controllers/OpenAPI/TaskSchema.php | 2 +- app/Http/Controllers/PingController.php | 4 +- app/Http/Controllers/ProjectController.php | 2 +- app/Http/Controllers/QuoteController.php | 10 +- .../RecurringInvoiceController.php | 1 - app/Http/Controllers/SelfUpdateController.php | 1 - app/Http/Controllers/SystemLogController.php | 3 +- .../Livewire/Profile/Settings/General.php | 6 +- app/Http/Middleware/ApiSecretCheck.php | 4 +- app/Http/Middleware/ContactKeyLogin.php | 29 +--- app/Http/Middleware/ContactTokenAuth.php | 2 +- app/Http/Middleware/QueryLogging.php | 2 - app/Http/Middleware/SetEmailDb.php | 2 +- app/Http/Middleware/StartupCheck.php | 3 +- app/Http/Middleware/TrustProxies.php | 12 +- .../Requests/Expense/UpdateExpenseRequest.php | 3 +- .../UpdateExpenseCategoryRequest.php | 6 +- .../GroupSetting/StoreGroupSettingRequest.php | 1 - .../Requests/Payment/StorePaymentRequest.php | 4 +- .../Requests/Payment/UpdatePaymentRequest.php | 3 +- .../Requests/Project/StoreProjectRequest.php | 8 +- .../Requests/Project/UpdateProjectRequest.php | 8 +- .../StoreRecurringInvoiceRequest.php | 25 ++-- .../UpdateRecurringInvoiceRequest.php | 16 +- app/Http/Requests/Request.php | 33 ++--- app/Http/Requests/Task/StoreTaskRequest.php | 8 +- app/Http/Requests/Task/UpdateTaskRequest.php | 5 +- .../TaskStatus/UpdateTaskStatusRequest.php | 8 +- .../ValidationRules/Credit/CreditsSumRule.php | 5 +- .../Expense/UniqueExpenseNumberRule.php | 3 +- .../Invoice/UniqueInvoiceNumberRule.php | 3 +- .../PaymentAmountsBalanceRule.php | 4 +- .../Project/ValidProjectForClient.php | 8 +- .../UniqueRecurringInvoiceNumberRule.php | 3 +- .../ValidationRules/User/RelatedUserRule.php | 4 +- .../ValidCreditsPresentRule.php | 1 - app/Http/ViewComposers/PortalComposer.php | 5 +- app/Jobs/Cron/RecurringInvoicesCron.php | 21 +-- app/Jobs/Entity/CreateEntityPdf.php | 35 ++--- app/Jobs/Entity/EmailEntity.php | 14 +- app/Jobs/Invoice/ZipInvoices.php | 4 +- app/Jobs/Mail/BaseMailerJob.php | 1 - app/Jobs/Mail/EntityPaidMailer.php | 6 +- app/Jobs/Mail/EntitySentMailer.php | 8 +- app/Jobs/Mail/EntityViewedMailer.php | 10 +- app/Jobs/Mail/MailRouter.php | 9 +- app/Jobs/Mail/PaymentFailureMailer.php | 9 +- app/Jobs/Ninja/RefundCancelledAccount.php | 9 +- app/Jobs/Ninja/SendReminders.php | 137 ++++++++---------- app/Jobs/Payment/EmailPayment.php | 18 +-- app/Jobs/Product/UpdateOrCreateProduct.php | 4 +- app/Jobs/RecurringInvoice/SendRecurring.php | 14 +- app/Jobs/User/UserEmailChanged.php | 13 +- app/Jobs/Util/Import.php | 75 +++++----- app/Jobs/Util/ReminderJob.php | 16 +- app/Jobs/Util/SendFailedEmails.php | 2 - app/Jobs/Util/StartMigration.php | 5 +- app/Jobs/Util/WebhookHandler.php | 7 +- .../Invoice/InvoiceEmailedNotification.php | 1 - app/Listeners/Invoice/InvoicePaidActivity.php | 5 +- .../Payment/PaymentEmailFailureActivity.php | 4 +- .../Payment/PaymentEmailedActivity.php | 1 - app/Listeners/Payment/PaymentNotification.php | 2 - .../SendVerificationNotification.php | 3 - app/Mail/DownloadInvoices.php | 1 - app/Mail/Engine/BaseEmailEngine.php | 81 ++++++----- app/Mail/Engine/CreditEmailEngine.php | 28 ++-- app/Mail/Engine/EngineInterface.php | 4 +- app/Mail/Engine/InvoiceEmailEngine.php | 34 ++--- app/Mail/Engine/PaymentEmailEngine.php | 31 ++-- app/Mail/Engine/QuoteEmailEngine.php | 30 ++-- app/Mail/TemplateEmail.php | 9 +- app/Models/Activity.php | 2 +- app/Models/BaseModel.php | 2 +- app/Models/Client.php | 52 +++---- app/Models/ClientContact.php | 5 +- app/Models/ClientGatewayToken.php | 2 +- app/Models/Company.php | 4 +- app/Models/CompanyGateway.php | 14 +- app/Models/CompanyToken.php | 1 - app/Models/CompanyUser.php | 1 - app/Models/Gateway.php | 8 +- app/Models/GroupSetting.php | 2 +- app/Models/Payment.php | 3 +- app/Models/Project.php | 1 - app/Models/RecurringInvoice.php | 49 +++---- app/Models/RecurringInvoiceInvitation.php | 1 - app/Models/SystemLog.php | 4 +- app/Models/Task.php | 6 - app/Models/TaskStatus.php | 1 - app/Models/User.php | 11 +- app/Models/VendorContact.php | 2 +- app/Observers/ClientObserver.php | 9 +- app/Observers/ExpenseObserver.php | 9 +- app/Observers/InvoiceObserver.php | 10 +- app/Observers/PaymentObserver.php | 7 +- app/Observers/QuoteObserver.php | 11 +- app/Observers/TaskObserver.php | 13 +- .../Authorize/AuthorizeCreditCard.php | 3 +- app/PaymentDrivers/BaseDriver.php | 2 - app/PaymentDrivers/StripePaymentDriver.php | 21 ++- app/Repositories/ActivityRepository.php | 19 +-- app/Repositories/BaseRepository.php | 8 +- app/Repositories/ClientContactRepository.php | 2 - app/Repositories/ClientRepository.php | 6 +- app/Repositories/DesignRepository.php | 1 - app/Repositories/DocumentRepository.php | 1 - app/Repositories/GroupSettingRepository.php | 1 - .../Migration/InvoiceMigrationRepository.php | 2 +- .../Migration/PaymentMigrationRepository.php | 6 +- app/Repositories/PaymentRepository.php | 14 +- app/Repositories/ProjectRepository.php | 1 - app/Repositories/QuoteRepository.php | 2 - .../RecurringInvoiceRepository.php | 1 - app/Repositories/RecurringQuoteRepository.php | 2 - app/Repositories/TaskRepository.php | 3 +- app/Repositories/UserRepository.php | 5 +- app/Repositories/VendorContactRepository.php | 1 - app/Repositories/VendorRepository.php | 1 - app/Services/Client/ClientService.php | 3 - app/Services/Credit/ApplyPayment.php | 39 ++--- app/Services/Credit/CreditService.php | 19 ++- app/Services/Credit/SendEmail.php | 1 - app/Services/Invoice/AddGatewayFee.php | 3 +- app/Services/Invoice/ApplyRecurringNumber.php | 2 +- app/Services/Invoice/AutoBillInvoice.php | 69 +++++---- app/Services/Invoice/HandleReversal.php | 5 +- app/Services/Invoice/InvoiceService.php | 48 +++--- app/Services/Invoice/MarkInvoiceDeleted.php | 27 ++-- app/Services/Invoice/MarkPaid.php | 3 +- app/Services/Invoice/SendEmail.php | 1 - app/Services/Invoice/TriggeredActions.php | 1 - app/Services/Payment/DeletePayment.php | 3 +- app/Services/Payment/RefundPayment.php | 1 - app/Services/Payment/UpdateInvoicePayment.php | 2 - app/Services/PdfMaker/Design.php | 28 ++-- .../Designs/Utilities/DesignHelpers.php | 2 +- app/Services/PdfMaker/PdfMaker.php | 2 +- app/Services/PdfMaker/PdfMakerUtilities.php | 36 ++--- app/Services/Quote/QuoteService.php | 14 +- app/Services/Quote/SendEmail.php | 1 - .../Recurring/CreateRecurringInvitations.php | 7 +- app/Services/Recurring/RecurringService.php | 22 +-- .../ClientGatewayTokenTransformer.php | 15 +- app/Transformers/UserTransformer.php | 5 +- app/Utils/Helpers.php | 14 +- app/Utils/HtmlEngine.php | 17 ++- app/Utils/Ninja.php | 9 +- app/Utils/PhantomJS/Phantom.php | 11 +- app/Utils/Statics.php | 1 - app/Utils/SystemHealth.php | 2 - app/Utils/TemplateEngine.php | 22 +-- app/Utils/Traits/AppSetup.php | 3 +- app/Utils/Traits/CleanLineItems.php | 13 +- app/Utils/Traits/GeneratesCounter.php | 21 ++- app/Utils/Traits/Inviteable.php | 1 - app/Utils/Traits/MakesDates.php | 3 +- app/Utils/Traits/MakesReminders.php | 63 ++++---- .../Traits/Notifications/UserNotifies.php | 1 - app/Utils/Traits/Recurring/HasRecurrence.php | 22 +-- app/Utils/Traits/SavesDocuments.php | 1 - app/Utils/Traits/Uploadable.php | 3 - 187 files changed, 898 insertions(+), 1148 deletions(-) diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php index 7130c1a9a1ab..15b9c693d67b 100644 --- a/app/Console/Commands/CheckData.php +++ b/app/Console/Commands/CheckData.php @@ -332,16 +332,16 @@ class CheckData extends Command $total_amount = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.amount'); $total_refund = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.refunded'); - $total_invoice_payments += ($total_amount - $total_refund); + $total_invoice_payments += ($total_amount - $total_refund); } - foreach($client->payments as $payment) - { - $credit_total_applied += $payment->paymentables->where('paymentable_type', App\Models\Credit::class)->sum(DB::raw('amount')); + foreach ($client->payments as $payment) { + $credit_total_applied += $payment->paymentables->where('paymentable_type', App\Models\Credit::class)->sum(DB::raw('amount')); } - if($credit_total_applied < 0) - $total_invoice_payments += $credit_total_applied; //todo this is contentious + if ($credit_total_applied < 0) { + $total_invoice_payments += $credit_total_applied; + } //todo this is contentious info("total invoice payments = {$total_invoice_payments} with client paid to date of of {$client->paid_to_date}"); diff --git a/app/Console/Commands/CreateSingleAccount.php b/app/Console/Commands/CreateSingleAccount.php index f500accc6db4..98e7d311faca 100644 --- a/app/Console/Commands/CreateSingleAccount.php +++ b/app/Console/Commands/CreateSingleAccount.php @@ -100,7 +100,6 @@ class CreateSingleAccount extends Command $this->warmCache(); $this->createSmallAccount(); - } private function createSmallAccount() @@ -205,7 +204,6 @@ class CreateSingleAccount extends Command $this->info('creating credit for client #'.$client->id); $this->createCredit($client); - } $this->createGateways($company, $user); @@ -299,7 +297,6 @@ class CreateSingleAccount extends Command private function createInvoice($client) { - $faker = Factory::create(); $invoice = InvoiceFactory::create($client->company->id, $client->user->id); //stub the company and user_id @@ -369,7 +366,6 @@ class CreateSingleAccount extends Command private function createQuote($client) { - $faker = Factory::create(); $quote = Quote::factory()->create(['user_id' => $client->user->id, 'company_id' => $client->company->id, 'client_id' => $client->id]); @@ -414,21 +410,21 @@ class CreateSingleAccount extends Command { $line_items = []; - $item = InvoiceItemFactory::create(); - $item->quantity = 1; - $item->cost = 1000; + $item = InvoiceItemFactory::create(); + $item->quantity = 1; + $item->cost = 1000; - $product = Product::all()->random(); + $product = Product::all()->random(); - $item->cost = (float) $product->cost; - $item->product_key = $product->product_key; - $item->notes = $product->notes; - $item->custom_value1 = $product->custom_value1; - $item->custom_value2 = $product->custom_value2; - $item->custom_value3 = $product->custom_value3; - $item->custom_value4 = $product->custom_value4; + $item->cost = (float) $product->cost; + $item->product_key = $product->product_key; + $item->notes = $product->notes; + $item->custom_value1 = $product->custom_value1; + $item->custom_value2 = $product->custom_value2; + $item->custom_value3 = $product->custom_value3; + $item->custom_value4 = $product->custom_value4; - $line_items[] = $item; + $line_items[] = $item; return $line_items; @@ -505,7 +501,6 @@ class CreateSingleAccount extends Command private function createGateways($company, $user) { - if (config('ninja.testvars.stripe') && ($this->gateway == 'all' || $this->gateway == 'stripe')) { $cg = new CompanyGateway; $cg->company_id = $company->id; diff --git a/app/Console/Commands/CreateTestData.php b/app/Console/Commands/CreateTestData.php index 6b1172ebf1df..5d0e07dd4240 100644 --- a/app/Console/Commands/CreateTestData.php +++ b/app/Console/Commands/CreateTestData.php @@ -471,7 +471,6 @@ class CreateTestData extends Command private function createInvoice($client) { - $faker = Factory::create(); $invoice = InvoiceFactory::create($client->company->id, $client->user->id); //stub the company and user_id @@ -522,7 +521,6 @@ class CreateTestData extends Command private function createCredit($client) { - $faker = Factory::create(); $credit = Credit::factory()->create(['user_id' => $client->user->id, 'company_id' => $client->company->id, 'client_id' => $client->id]); @@ -562,7 +560,6 @@ class CreateTestData extends Command private function createQuote($client) { - $faker = Factory::create(); //$quote = QuoteFactory::create($client->company->id, $client->user->id);//stub the company and user_id diff --git a/app/Console/Commands/DemoMode.php b/app/Console/Commands/DemoMode.php index 10b89a551b7c..ae18b2081533 100644 --- a/app/Console/Commands/DemoMode.php +++ b/app/Console/Commands/DemoMode.php @@ -303,7 +303,7 @@ class DemoMode extends Command 'is_primary' => 1, ]); - ClientContact::factory()->count(rand(1,5))->create([ + ClientContact::factory()->count(rand(1, 5))->create([ 'user_id' => $user->id, 'client_id' => $client->id, 'company_id' => $company->id, @@ -325,7 +325,7 @@ class DemoMode extends Command private function createExpense($client) { - Expense::factory()->count(rand(1,5))->create([ + Expense::factory()->count(rand(1, 5))->create([ 'user_id' => $client->user_id, 'client_id' => $client->id, 'company_id' => $client->company_id, @@ -346,7 +346,7 @@ class DemoMode extends Command 'is_primary' => 1, ]); - VendorContact::factory()->count(rand(1,5))->create([ + VendorContact::factory()->count(rand(1, 5))->create([ 'user_id' => $client->user->id, 'vendor_id' => $vendor->id, 'company_id' => $client->company_id, @@ -376,7 +376,6 @@ class DemoMode extends Command private function createInvoice($client, $assigned_user_id = null) { - $faker = \Faker\Factory::create(); $invoice = InvoiceFactory::create($client->company->id, $client->user->id); //stub the company and user_id @@ -441,7 +440,6 @@ class DemoMode extends Command private function createCredit($client, $assigned_user_id = null) { - $faker = \Faker\Factory::create(); $credit = Credit::factory()->create(['user_id' => $client->user->id, 'company_id' => $client->company->id, 'client_id' => $client->id]); diff --git a/app/Console/Commands/PostUpdate.php b/app/Console/Commands/PostUpdate.php index a10654a3fc88..2f3f32e3f123 100644 --- a/app/Console/Commands/PostUpdate.php +++ b/app/Console/Commands/PostUpdate.php @@ -46,7 +46,6 @@ class PostUpdate extends Command */ public function handle() { - set_time_limit(0); info('running post update'); @@ -73,6 +72,5 @@ class PostUpdate extends Command $application->run($input); echo "Done."; - } } diff --git a/app/Console/Commands/SendRemindersCron.php b/app/Console/Commands/SendRemindersCron.php index 9ad36e5434c6..e3f4ccb89970 100644 --- a/app/Console/Commands/SendRemindersCron.php +++ b/app/Console/Commands/SendRemindersCron.php @@ -65,10 +65,9 @@ class SendRemindersCron extends Command ->whereDate('due_date', now()->subDays(1)->startOfDay()) ->cursor(); - $invoices->each(function ($invoice){ + $invoices->each(function ($invoice) { WebHookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company); }); - } private function webHookExpiredQuotes() @@ -78,7 +77,7 @@ class SendRemindersCron extends Command ->whereDate('due_date', now()->subDays(1)->startOfDay()) ->cursor(); - $quotes->each(function ($quote){ + $quotes->each(function ($quote) { WebHookHandler::dispatch(Webhook::EVENT_EXPIRED_QUOTE, $quote, $quote->company); }); } diff --git a/app/Console/Commands/SendTestEmails.php b/app/Console/Commands/SendTestEmails.php index c775dce2f27d..e1fd223e6b21 100644 --- a/app/Console/Commands/SendTestEmails.php +++ b/app/Console/Commands/SendTestEmails.php @@ -82,7 +82,6 @@ class SendTestEmails extends Command $user = User::whereEmail('user@example.com')->first(); if (! $user) { - $account = Account::factory()->create(); $user = User::factory()->create([ diff --git a/app/DataMapper/CompanySettings.php b/app/DataMapper/CompanySettings.php index 4efc296a13e5..3d9a8639069d 100644 --- a/app/DataMapper/CompanySettings.php +++ b/app/DataMapper/CompanySettings.php @@ -175,13 +175,13 @@ class CompanySettings extends BaseSettings public $email_template_reminder3 = ''; //@implemented public $email_template_reminder_endless = ''; //@implemented public $email_signature = ''; //@implemented - public $enable_email_markup = true; //@TODO - + public $enable_email_markup = true; //@TODO - public $email_subject_custom1 = ''; //@TODO public $email_subject_custom2 = ''; //@TODO public $email_subject_custom3 = ''; //@TODO - public $email_template_custom1 = ''; //@TODO + public $email_template_custom1 = ''; //@TODO public $email_template_custom2 = ''; //@TODO public $email_template_custom3 = ''; //@TODO @@ -195,7 +195,7 @@ class CompanySettings extends BaseSettings public $num_days_reminder3 = 0;//@implmemented public $schedule_reminder1 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented - public $schedule_reminder2 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented + public $schedule_reminder2 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented public $schedule_reminder3 = ''; // (enum: after_invoice_date, before_due_date, after_due_date) implmemented public $reminder_send_time = 32400; //number of seconds from UTC +0 to send reminders @TODO @@ -511,7 +511,7 @@ class CompanySettings extends BaseSettings /** * Provides class defaults on init. - * + * * @return stdClass */ public static function defaults(): stdClass @@ -544,7 +544,7 @@ class CompanySettings extends BaseSettings * set new properties to the object prior to being returned. * * @param $settings - * + * * @return stdClass */ public static function setProperties($settings): stdClass @@ -562,7 +562,7 @@ class CompanySettings extends BaseSettings /** * Stubs the notification defaults - * + * * @return stdClass */ public static function notificationDefaults() :stdClass @@ -575,7 +575,7 @@ class CompanySettings extends BaseSettings /** * Defines entity variables for PDF generation - * + * * @return stdClass The stdClass of PDF variables */ private static function getEntityVariableDefaults() :stdClass diff --git a/app/DataMapper/EmailTemplateDefaults.php b/app/DataMapper/EmailTemplateDefaults.php index 0ab17319ade8..2c64b80eb6bf 100644 --- a/app/DataMapper/EmailTemplateDefaults.php +++ b/app/DataMapper/EmailTemplateDefaults.php @@ -148,11 +148,9 @@ class EmailTemplateDefaults public static function emailPaymentTemplate() { - $payment_message = '

'.self::transformText('payment_message').'



$view_link

'; return $payment_message; - } public static function emailCreditTemplate() @@ -164,11 +162,9 @@ class EmailTemplateDefaults public static function emailPaymentPartialTemplate() { - $payment_message = '

'.self::transformText('payment_message').'



$view_link

'; return $payment_message; - } public static function emailPaymentPartialSubject() diff --git a/app/Factory/TaskFactory.php b/app/Factory/TaskFactory.php index e0d43b02e94c..64e47ddefee1 100644 --- a/app/Factory/TaskFactory.php +++ b/app/Factory/TaskFactory.php @@ -24,9 +24,9 @@ class TaskFactory $task->company_id = $company_id; $task->user_id = $user_id; $task->time_log = '[]'; - $task->is_running = false; - $task->is_deleted = false; - $task->duration = 0; + $task->is_running = false; + $task->is_deleted = false; + $task->duration = 0; return $task; } diff --git a/app/Filters/SystemLogFilters.php b/app/Filters/SystemLogFilters.php index 388d941e8446..3e6ef9a1893a 100644 --- a/app/Filters/SystemLogFilters.php +++ b/app/Filters/SystemLogFilters.php @@ -51,13 +51,11 @@ class SystemLogFilters extends QueryFilters */ public function filter(string $filter = '') : Builder { - if (strlen($filter) == 0) { return $this->builder; } return $this->builder; - } /** diff --git a/app/Helpers/Invoice/InvoiceItemSum.php b/app/Helpers/Invoice/InvoiceItemSum.php index ee66fddc67cc..b031909aafb2 100644 --- a/app/Helpers/Invoice/InvoiceItemSum.php +++ b/app/Helpers/Invoice/InvoiceItemSum.php @@ -231,7 +231,7 @@ class InvoiceItemSum } //$amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount / $this->sub_total)); - $amount = ( $this->sub_total > 0 ) ? $this->item->line_total - ($this->item->line_total * ($this->invoice->discount / $this->sub_total)) : 0; + $amount = ($this->sub_total > 0) ? $this->item->line_total - ($this->item->line_total * ($this->invoice->discount / $this->sub_total)) : 0; $item_tax_rate1_total = $this->calcAmountLineTax($this->item->tax_rate1, $amount); @@ -264,7 +264,7 @@ class InvoiceItemSum /** * Sets default casts for the values in the line_items. - * + * * @return $this */ private function cleanLineItem() diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php index 3a9d4bab6685..a3c496dcde87 100644 --- a/app/Helpers/Invoice/InvoiceSum.php +++ b/app/Helpers/Invoice/InvoiceSum.php @@ -160,17 +160,21 @@ class InvoiceSum { $this->total += $this->total_taxes; - if(is_numeric($this->invoice->custom_value1) && $this->invoice->custom_value1 > 0) + if (is_numeric($this->invoice->custom_value1) && $this->invoice->custom_value1 > 0) { $this->total += $this->invoice->custom_value1; + } - if(is_numeric($this->invoice->custom_value2) && $this->invoice->custom_value2 > 0) + if (is_numeric($this->invoice->custom_value2) && $this->invoice->custom_value2 > 0) { $this->total += $this->invoice->custom_value2; + } - if(is_numeric($this->invoice->custom_value3) && $this->invoice->custom_value3 > 0) + if (is_numeric($this->invoice->custom_value3) && $this->invoice->custom_value3 > 0) { $this->total += $this->invoice->custom_value3; + } - if(is_numeric($this->invoice->custom_value4) && $this->invoice->custom_value4 > 0) + if (is_numeric($this->invoice->custom_value4) && $this->invoice->custom_value4 > 0) { $this->total += $this->invoice->custom_value4; + } return $this; } @@ -202,7 +206,6 @@ class InvoiceSum public function getRecurringInvoice() { - $this->invoice->amount = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); $this->invoice->total_taxes = $this->getTotalTaxes(); $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); @@ -220,8 +223,7 @@ class InvoiceSum { /* 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->status_id != Invoice::STATUS_DRAFT) - { + if ($this->invoice->status_id != Invoice::STATUS_DRAFT) { if ($this->invoice->amount != $this->invoice->balance) { $paid_to_date = $this->invoice->amount - $this->invoice->balance; @@ -318,7 +320,6 @@ class InvoiceSum public function purgeTaxes() { - $this->tax_rate1 = 0; $this->tax_name1 = ''; @@ -332,7 +333,7 @@ class InvoiceSum $line_items = collect($this->invoice->line_items); - $items = $line_items->map(function ($item){ + $items = $line_items->map(function ($item) { $item->tax_rate1 = 0; $item->tax_rate2 = 0; $item->tax_rate3 = 0; @@ -350,5 +351,4 @@ class InvoiceSum return $this; } - } diff --git a/app/Helpers/Invoice/InvoiceSumInclusive.php b/app/Helpers/Invoice/InvoiceSumInclusive.php index 95d2492b7354..f04818f62f52 100644 --- a/app/Helpers/Invoice/InvoiceSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceSumInclusive.php @@ -66,7 +66,7 @@ class InvoiceSumInclusive ->calculateCustomValues() ->calculateInvoiceTaxes() ->setTaxMap() - ->calculateTotals() //just don't add the taxes!! + ->calculateTotals() //just don't add the taxes!! ->calculateBalance() ->calculatePartial(); @@ -172,24 +172,27 @@ class InvoiceSumInclusive { //$this->total += $this->total_taxes; - if(is_numeric($this->invoice->custom_value1) && $this->invoice->custom_value1 > 0) + if (is_numeric($this->invoice->custom_value1) && $this->invoice->custom_value1 > 0) { $this->total += $this->invoice->custom_value1; + } - if(is_numeric($this->invoice->custom_value2) && $this->invoice->custom_value2 > 0) + if (is_numeric($this->invoice->custom_value2) && $this->invoice->custom_value2 > 0) { $this->total += $this->invoice->custom_value2; + } - if(is_numeric($this->invoice->custom_value3) && $this->invoice->custom_value3 > 0) + if (is_numeric($this->invoice->custom_value3) && $this->invoice->custom_value3 > 0) { $this->total += $this->invoice->custom_value3; + } - if(is_numeric($this->invoice->custom_value4) && $this->invoice->custom_value4 > 0) - $this->total += $this->invoice->custom_value4; + if (is_numeric($this->invoice->custom_value4) && $this->invoice->custom_value4 > 0) { + $this->total += $this->invoice->custom_value4; + } return $this; } public function getRecurringInvoice() { - $this->invoice->amount = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); $this->invoice->total_taxes = $this->getTotalTaxes(); $this->invoice->balance = $this->formatValue($this->getTotal(), $this->invoice->client->currency()->precision); @@ -329,7 +332,6 @@ class InvoiceSumInclusive public function purgeTaxes() { - return $this; } } diff --git a/app/Http/Controllers/Auth/ContactLoginController.php b/app/Http/Controllers/Auth/ContactLoginController.php index 2bcf310dfa04..8168052aab85 100644 --- a/app/Http/Controllers/Auth/ContactLoginController.php +++ b/app/Http/Controllers/Auth/ContactLoginController.php @@ -80,5 +80,4 @@ class ContactLoginController extends Controller return redirect('/client/login'); } - } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 63aa19aec955..dcaa7460b3df 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -173,8 +173,7 @@ class LoginController extends BaseController $cu = CompanyUser::query() ->where('user_id', auth()->user()->id); - return $this->listResponse($cu); - + return $this->listResponse($cu); } else { LightLogs::create(new LoginFailure()) ->increment() diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index 095e96f24503..a6b2c962db75 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -207,12 +207,12 @@ class BaseController extends Controller $updated_at = date('Y-m-d H:i:s', $updated_at); $query->with( - [ + [ 'company' => function ($query) use ($updated_at) { $query->whereNotNull('updated_at')->with('documents'); }, 'company.clients' => function ($query) use ($updated_at) { - $query->where('clients.updated_at', '>=', $updated_at)->with('contacts.company', 'gateway_tokens','documents'); + $query->where('clients.updated_at', '>=', $updated_at)->with('contacts.company', 'gateway_tokens', 'documents'); }, 'company.company_gateways' => function ($query) { $query->whereNotNull('updated_at'); @@ -236,7 +236,7 @@ class BaseController extends Controller $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents'); }, 'company.payments'=> function ($query) use ($updated_at) { - $query->where('updated_at', '>=', $updated_at)->with('paymentables','documents'); + $query->where('updated_at', '>=', $updated_at)->with('paymentables', 'documents'); }, 'company.payment_terms'=> function ($query) use ($updated_at) { $query->where('updated_at', '>=', $updated_at); @@ -245,7 +245,7 @@ class BaseController extends Controller $query->where('updated_at', '>=', $updated_at)->with('documents'); }, 'company.projects'=> function ($query) use ($updated_at) { - $query->where('updated_at', '>=', $updated_at)->with('documents' ); + $query->where('updated_at', '>=', $updated_at)->with('documents'); }, 'company.quotes'=> function ($query) use ($updated_at) { $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents'); @@ -254,13 +254,13 @@ class BaseController extends Controller $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents'); }, 'company.tasks'=> function ($query) use ($updated_at) { - $query->where('updated_at', '>=', $updated_at)->with('documents' ); + $query->where('updated_at', '>=', $updated_at)->with('documents'); }, 'company.tax_rates' => function ($query) use ($updated_at) { $query->where('updated_at', '>=', $updated_at); }, 'company.vendors'=> function ($query) use ($updated_at) { - $query->where('updated_at', '>=', $updated_at)->with('contacts','documents'); + $query->where('updated_at', '>=', $updated_at)->with('contacts', 'documents'); }, 'company.expense_categories'=> function ($query) use ($updated_at) { $query->where('updated_at', '>=', $updated_at); @@ -297,14 +297,17 @@ class BaseController extends Controller $query->with($includes); - if (auth()->user() && ! auth()->user()->hasPermission('view_'.lcfirst(class_basename($this->entity_type)))) + if (auth()->user() && ! auth()->user()->hasPermission('view_'.lcfirst(class_basename($this->entity_type)))) { $query->where('user_id', '=', auth()->user()->id); + } - if (request()->has('updated_at') && request()->input('updated_at') > 0) + if (request()->has('updated_at') && request()->input('updated_at') > 0) { $query->where('updated_at', '>=', date('Y-m-d H:i:s', intval(request()->input('updated_at')))); + } - if ($this->serializer && $this->serializer != EntityTransformer::API_SERIALIZER_JSON) + if ($this->serializer && $this->serializer != EntityTransformer::API_SERIALIZER_JSON) { $this->entity_type = null; + } if ($query instanceof Builder) { $limit = request()->input('per_page', 20); @@ -317,7 +320,6 @@ class BaseController extends Controller } return $this->response($this->manager->createData($resource)->toArray()); - } protected function response($response) @@ -357,13 +359,15 @@ class BaseController extends Controller $transformer = new $this->entity_transformer(request()->input('serializer')); - if ($this->serializer && $this->serializer != EntityTransformer::API_SERIALIZER_JSON) + if ($this->serializer && $this->serializer != EntityTransformer::API_SERIALIZER_JSON) { $this->entity_type = null; + } $resource = new Item($item, $transformer, $this->entity_type); - if (auth()->user() && request()->include_static) + if (auth()->user() && request()->include_static) { $data['static'] = Statics::company(auth()->user()->getCompany()->getLocale()); + } return $this->response($this->manager->createData($resource)->toArray()); } @@ -407,7 +411,6 @@ class BaseController extends Controller public function flutterRoute() { - if ((bool) $this->checkAppSetup() !== false && $account = Account::first()) { if (config('ninja.require_https') && ! request()->isSecure()) { return redirect()->secure(request()->getRequestUri()); diff --git a/app/Http/Controllers/ClientPortal/ContactHashLoginController.php b/app/Http/Controllers/ClientPortal/ContactHashLoginController.php index 3a64b9f1d36d..7ba208a4557b 100644 --- a/app/Http/Controllers/ClientPortal/ContactHashLoginController.php +++ b/app/Http/Controllers/ClientPortal/ContactHashLoginController.php @@ -25,11 +25,6 @@ class ContactHashLoginController extends Controller */ public function login(string $contact_key) { - return redirect('/client/login'); - } - } - - diff --git a/app/Http/Controllers/ClientPortal/InvitationController.php b/app/Http/Controllers/ClientPortal/InvitationController.php index 1e4e4efc22d4..344889f8ce98 100644 --- a/app/Http/Controllers/ClientPortal/InvitationController.php +++ b/app/Http/Controllers/ClientPortal/InvitationController.php @@ -37,7 +37,6 @@ class InvitationController extends Controller public function router(string $entity, string $invitation_key) { - $key = $entity.'_id'; $entity_obj = 'App\Models\\'.ucfirst(Str::camel($entity)).'Invitation'; @@ -48,18 +47,15 @@ class InvitationController extends Controller /* Return early if we have the correct client_hash embedded */ - if(request()->has('client_hash') && request()->input('client_hash') == $invitation->contact->client->client_hash) { + if (request()->has('client_hash') && request()->input('client_hash') == $invitation->contact->client->client_hash) { auth()->guard('contact')->login($invitation->contact, true); - } - else if ((bool) $invitation->contact->client->getSetting('enable_client_portal_password') !== false) { + } elseif ((bool) $invitation->contact->client->getSetting('enable_client_portal_password') !== false) { $this->middleware('auth:contact'); - } - else { + } else { auth()->guard('contact')->login($invitation->contact, true); } if (auth()->guard('contact') && ! request()->has('silent') && ! $invitation->viewed_date) { - $invitation->markViewed(); event(new InvitationWasViewed($invitation->{$entity}, $invitation, $invitation->{$entity}->company, Ninja::eventVars())); @@ -68,8 +64,6 @@ class InvitationController extends Controller } return redirect()->route('client.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->{$key})]); - - } private function fireEntityViewedEvent($invitation, $entity_string) diff --git a/app/Http/Controllers/ClientPortal/PaymentController.php b/app/Http/Controllers/ClientPortal/PaymentController.php index 1cac29ad5560..c58186a8c674 100644 --- a/app/Http/Controllers/ClientPortal/PaymentController.php +++ b/app/Http/Controllers/ClientPortal/PaymentController.php @@ -77,8 +77,9 @@ class PaymentController extends Controller $is_credit_payment = false; $token = false; - if($request->input('company_gateway_id') == CompanyGateway::GATEWAY_CREDIT) + if ($request->input('company_gateway_id') == CompanyGateway::GATEWAY_CREDIT) { $is_credit_payment = true; + } $gateway = CompanyGateway::find($request->input('company_gateway_id')); @@ -94,10 +95,8 @@ class PaymentController extends Controller $invoices = Invoice::whereIn('id', $this->transformKeys($payable_invoices->pluck('invoice_id')->toArray()))->get(); /* pop non payable invoice from the $payable_invoices array */ - $payable_invoices = $payable_invoices->filter(function ($payable_invoice) use ($invoices){ - + $payable_invoices = $payable_invoices->filter(function ($payable_invoice) use ($invoices) { return $invoices->where('hashed_id', $payable_invoice['invoice_id'])->first()->isPayable(); - }); /*return early if no invoices*/ @@ -110,8 +109,7 @@ class PaymentController extends Controller $settings = auth()->user()->client->getMergedSettings(); /*iterate through invoices and add gateway fees and other payment metadata*/ - $payable_invoices = $payable_invoices->map(function($payable_invoice) use($invoices, $settings){ - + $payable_invoices = $payable_invoices->map(function ($payable_invoice) use ($invoices, $settings) { $payable_invoice['amount'] = Number::parseFloat($payable_invoice['amount']); $invoice = $invoices->first(function ($inv) use ($payable_invoice) { @@ -167,7 +165,6 @@ class PaymentController extends Controller $payable_invoice['additional_info'] = $additional_info; return $payable_invoice; - }); if (request()->has('signature') && !is_null(request()->signature) && !empty(request()->signature)) { @@ -182,8 +179,9 @@ class PaymentController extends Controller $credit_totals = $first_invoice->client->getSetting('use_credits_payment') == 'off' ? 0 : $first_invoice->client->service()->getCreditBalance(); $starting_invoice_amount = $first_invoice->amount; - if($gateway) + if ($gateway) { $first_invoice->service()->addGatewayFee($gateway, $payment_method_id, $invoice_totals)->save(); + } /** * Gateway fee is calculated @@ -192,8 +190,9 @@ class PaymentController extends Controller */ $fee_totals = $first_invoice->amount - $starting_invoice_amount; - if($gateway) + if ($gateway) { $token = auth()->user()->client->gateway_token($gateway->id, $payment_method_id); + } $payment_hash = new PaymentHash; $payment_hash->hash = Str::random(128); @@ -218,7 +217,7 @@ class PaymentController extends Controller 'amount_with_fee' => $invoice_totals + $fee_totals, ]; - if($is_credit_payment) { + if ($is_credit_payment) { return $this->processCreditPayment($request, $data); } @@ -252,9 +251,9 @@ class PaymentController extends Controller $payment_hash = PaymentHash::whereRaw('BINARY `hash`= ?', [$request->input('payment_hash')])->first(); /* Hydrate the $payment */ - if($payment_hash->payment()->exists()) + if ($payment_hash->payment()->exists()) { $payment = $payment_hash->payment; - else { + } else { $payment = PaymentFactory::create($payment_hash->fee_invoice->company_id, $payment_hash->fee_invoice->user_id); $payment->client_id = $payment_hash->fee_invoice->client_id; $payment->save(); @@ -264,8 +263,7 @@ class PaymentController extends Controller } /* Iterate through the invoices and apply credits to them */ - collect($payment_hash->invoices())->each(function ($payable_invoice) use ($payment, $payment_hash){ - + collect($payment_hash->invoices())->each(function ($payable_invoice) use ($payment, $payment_hash) { $invoice = Invoice::find($this->decodePrimaryKey($payable_invoice->invoice_id)); $amount = $payable_invoice->amount; @@ -274,35 +272,31 @@ class PaymentController extends Controller ->service() ->getCredits(); - foreach($credits as $credit) - { - //starting invoice balance - $invoice_balance = $invoice->balance; + foreach ($credits as $credit) { + //starting invoice balance + $invoice_balance = $invoice->balance; - //credit payment applied - $credit->service()->applyPayment($invoice, $amount, $payment); + //credit payment applied + $credit->service()->applyPayment($invoice, $amount, $payment); - //amount paid from invoice calculated - $remaining_balance = ($invoice_balance - $invoice->fresh()->balance); + //amount paid from invoice calculated + $remaining_balance = ($invoice_balance - $invoice->fresh()->balance); - //reduce the amount to be paid on the invoice from the NEXT credit - $amount -= $remaining_balance; + //reduce the amount to be paid on the invoice from the NEXT credit + $amount -= $remaining_balance; - //break if the invoice is no longer PAYABLE OR there is no more amount to be applied - if(!$invoice->isPayable() || (int)$amount == 0) - break; + //break if the invoice is no longer PAYABLE OR there is no more amount to be applied + if (!$invoice->isPayable() || (int)$amount == 0) { + break; } - + } }); return redirect()->route('client.payments.show', ['payment' => $this->encodePrimaryKey($payment->id)]); - } public function processCreditPayment(Request $request, array $data) { - return render('gateways.credit.index', $data); - } } diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index 2ccf9a6012b7..42e5c1451975 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -408,9 +408,9 @@ class CompanyController extends BaseController */ public function update(UpdateCompanyRequest $request, Company $company) { - - if($request->hasFile('company_logo') || (is_array($request->input('settings')) && !array_key_exists('company_logo', $request->input('settings')))) + if ($request->hasFile('company_logo') || (is_array($request->input('settings')) && !array_key_exists('company_logo', $request->input('settings')))) { $this->removeLogo($company); + } $company = $this->company_repo->save($request->all(), $company); @@ -490,7 +490,6 @@ class CompanyController extends BaseController LightLogs::create(new AccountDeleted()) ->increment() ->batch(); - } else { $company_id = $company->id; $company->delete(); diff --git a/app/Http/Controllers/CreditController.php b/app/Http/Controllers/CreditController.php index acf081363458..f35efd2c5d40 100644 --- a/app/Http/Controllers/CreditController.php +++ b/app/Http/Controllers/CreditController.php @@ -187,7 +187,7 @@ class CreditController extends BaseController $credit = $this->credit_repository->save($request->all(), CreditFactory::create(auth()->user()->company()->id, auth()->user()->id)); - $credit = $credit->service() + $credit = $credit->service() ->fillDefaults() ->save(); diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index 04f10b0cccc9..e7abdeaae4c5 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -120,18 +120,14 @@ class EmailController extends BaseController $template = str_replace("email_template_", "", $template); $entity_obj->invitations->each(function ($invitation) use ($subject, $body, $entity_string, $entity_obj, $template) { - if ($invitation->contact->send_email && $invitation->contact->email) { - $data = [ 'subject' => $subject, 'body' => $body ]; EmailEntity::dispatchNow($invitation, $invitation->company, $template, $data); - } - }); $entity_obj->last_sent_date = now(); diff --git a/app/Http/Controllers/InvoiceController.php b/app/Http/Controllers/InvoiceController.php index 62092a73bd63..a6903e983035 100644 --- a/app/Http/Controllers/InvoiceController.php +++ b/app/Http/Controllers/InvoiceController.php @@ -396,7 +396,7 @@ class InvoiceController extends BaseController $invoice = $this->invoice_repo->save($request->all(), $invoice); - UnlinkFile::dispatchNow(config('filesystems.default'),$invoice->client->invoice_filepath().$invoice->number.'.pdf'); + UnlinkFile::dispatchNow(config('filesystems.default'), $invoice->client->invoice_filepath().$invoice->number.'.pdf'); event(new InvoiceWasUpdated($invoice, $invoice->company, Ninja::eventVars())); @@ -731,7 +731,6 @@ class InvoiceController extends BaseController $invoice->invitations->load('contact.client.country', 'invoice.client.country', 'invoice.company')->each(function ($invitation) use ($invoice) { info("firing email"); EmailEntity::dispatch($invitation, $invoice->company, $this->reminder_template); - }); if (! $bulk) { diff --git a/app/Http/Controllers/MigrationController.php b/app/Http/Controllers/MigrationController.php index de7e14fa9514..6ca47a94ceab 100644 --- a/app/Http/Controllers/MigrationController.php +++ b/app/Http/Controllers/MigrationController.php @@ -219,7 +219,6 @@ class MigrationController extends BaseController */ public function startMigration(Request $request) { - $companies = json_decode($request->companies); if (app()->environment() === 'local') { @@ -227,7 +226,6 @@ class MigrationController extends BaseController } foreach ($companies as $company) { - $is_valid = $request->file($company->company_index)->isValid(); if (!$is_valid) { diff --git a/app/Http/Controllers/OpenAPI/TaskSchema.php b/app/Http/Controllers/OpenAPI/TaskSchema.php index 72c6d473ca9b..23acb2649e06 100644 --- a/app/Http/Controllers/OpenAPI/TaskSchema.php +++ b/app/Http/Controllers/OpenAPI/TaskSchema.php @@ -27,4 +27,4 @@ * @OA\Property(property="updated_at", type="number", format="integer", example="1434342123", description="Timestamp"), * @OA\Property(property="archived_at", type="number", format="integer", example="1434342123", description="Timestamp"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/PingController.php b/app/Http/Controllers/PingController.php index 41f8886880ef..a265815e53e6 100644 --- a/app/Http/Controllers/PingController.php +++ b/app/Http/Controllers/PingController.php @@ -45,7 +45,9 @@ class PingController extends BaseController return response()->json( ['company_name' => auth()->user()->getCompany()->present()->name(), 'user_name' => auth()->user()->present()->name(), - ], 200); + ], + 200 + ); } /** diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 371b2004791b..67276ddf3e87 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -363,7 +363,7 @@ class ProjectController extends BaseController $project->fill($request->all()); $project->save(); - if(empty($project->number)){ + if (empty($project->number)) { $project->number = $this->getNextProjectNumber($project); $project->save(); } diff --git a/app/Http/Controllers/QuoteController.php b/app/Http/Controllers/QuoteController.php index 9aba18ada4a6..9d6a49cd55bb 100644 --- a/app/Http/Controllers/QuoteController.php +++ b/app/Http/Controllers/QuoteController.php @@ -670,22 +670,25 @@ class QuoteController extends BaseController case 'restore': $this->quote_repo->restore($quote); - if (!$bulk) + if (!$bulk) { return $this->listResponse($quote); + } break; case 'archive': $this->quote_repo->archive($quote); - if (!$bulk) + if (!$bulk) { return $this->listResponse($quote); + } break; case 'delete': $this->quote_repo->delete($quote); - if (!$bulk) + if (!$bulk) { return $this->listResponse($quote); + } break; case 'email': @@ -700,7 +703,6 @@ class QuoteController extends BaseController return $this->itemResponse($quote); } break; - // no break default: return response()->json(['message' => "The requested action `{$action}` is not available."], 400); break; diff --git a/app/Http/Controllers/RecurringInvoiceController.php b/app/Http/Controllers/RecurringInvoiceController.php index 7fe473520f03..2074062e7b38 100644 --- a/app/Http/Controllers/RecurringInvoiceController.php +++ b/app/Http/Controllers/RecurringInvoiceController.php @@ -628,6 +628,5 @@ class RecurringInvoiceController extends BaseController // code... break; } - } } diff --git a/app/Http/Controllers/SelfUpdateController.php b/app/Http/Controllers/SelfUpdateController.php index 338c79b2097f..5f4de1a7c0f2 100644 --- a/app/Http/Controllers/SelfUpdateController.php +++ b/app/Http/Controllers/SelfUpdateController.php @@ -74,7 +74,6 @@ class SelfUpdateController extends BaseController try { $res = $repo->pull(); } catch (GitException $e) { - info($e->getMessage()); return response()->json(['message'=>$e->getMessage()], 500); } diff --git a/app/Http/Controllers/SystemLogController.php b/app/Http/Controllers/SystemLogController.php index c96637e58714..524ca6303362 100644 --- a/app/Http/Controllers/SystemLogController.php +++ b/app/Http/Controllers/SystemLogController.php @@ -63,8 +63,9 @@ class SystemLogController extends BaseController { $system_logs = SystemLog::filter($filters); - if(auth()->user()->isAdmin()) + if (auth()->user()->isAdmin()) { return $this->listResponse($system_logs); + } return $this->errorResponse('Insufficient permissions', 403); } diff --git a/app/Http/Livewire/Profile/Settings/General.php b/app/Http/Livewire/Profile/Settings/General.php index 249c832458aa..48e7bd08764c 100644 --- a/app/Http/Livewire/Profile/Settings/General.php +++ b/app/Http/Livewire/Profile/Settings/General.php @@ -65,9 +65,9 @@ class General extends Component $data = $this->validate($this->rules); - if (!empty($this->password)) { - $this->profile->password = Hash::make($this->password); - } + if (!empty($this->password)) { + $this->profile->password = Hash::make($this->password); + } $this->profile ->fill($data) diff --git a/app/Http/Middleware/ApiSecretCheck.php b/app/Http/Middleware/ApiSecretCheck.php index dfe057768a4d..de0b80c8c707 100644 --- a/app/Http/Middleware/ApiSecretCheck.php +++ b/app/Http/Middleware/ApiSecretCheck.php @@ -27,9 +27,9 @@ class ApiSecretCheck */ public function handle($request, Closure $next) { - - if(! config('ninja.api_secret')) + if (! config('ninja.api_secret')) { return $next($request); + } if ($request->header('X-API-SECRET') && ($request->header('X-API-SECRET') == config('ninja.api_secret'))) { return $next($request); diff --git a/app/Http/Middleware/ContactKeyLogin.php b/app/Http/Middleware/ContactKeyLogin.php index 50444c5178bd..1be35211c59b 100644 --- a/app/Http/Middleware/ContactKeyLogin.php +++ b/app/Http/Middleware/ContactKeyLogin.php @@ -34,47 +34,32 @@ class ContactKeyLogin */ public function handle($request, Closure $next) { - - if(Auth::guard('contact')->check()) + if (Auth::guard('contact')->check()) { Auth::guard('contact')->logout(); + } if ($request->segment(3) && config('ninja.db.multi_db_enabled')) { - if (MultiDB::findAndSetDbByContactKey($request->segment(3))) { - $client_contact = ClientContact::where('contact_key', $request->segment(3))->first(); Auth::guard('contact')->login($client_contact, true); return redirect()->to('client/dashboard'); - } - - } - else if ($request->has('contact_key')) { - - if($client_contact = ClientContact::where('contact_key', $request->segment(3))->first()){ + } elseif ($request->has('contact_key')) { + if ($client_contact = ClientContact::where('contact_key', $request->segment(3))->first()) { Auth::guard('contact')->login($client_contact, true); return redirect()->to('client/dashboard'); } - - } - else if($request->has('client_hash') && config('ninja.db.multi_db_enabled')){ - + } elseif ($request->has('client_hash') && config('ninja.db.multi_db_enabled')) { if (MultiDB::findAndSetDbByClientHash($request->input('client_hash'))) { - $client = Client::where('client_hash', $request->input('client_hash'))->first(); Auth::guard('contact')->login($client->primary_contact()->first(), true); return redirect()->to('client/dashboard'); - } - - } - else if($request->has('client_hash')){ - - if($client = Client::where('client_hash', $request->input('client_hash'))->first()){ + } elseif ($request->has('client_hash')) { + if ($client = Client::where('client_hash', $request->input('client_hash'))->first()) { Auth::guard('contact')->login($client->primary_contact()->first(), true); return redirect()->to('client/dashboard'); } - } return $next($request); diff --git a/app/Http/Middleware/ContactTokenAuth.php b/app/Http/Middleware/ContactTokenAuth.php index 86e6175fd299..33759d2be039 100644 --- a/app/Http/Middleware/ContactTokenAuth.php +++ b/app/Http/Middleware/ContactTokenAuth.php @@ -55,7 +55,7 @@ class ContactTokenAuth //stateless, don't remember the contact. auth()->guard('contact')->login($client_contact, false); - event(new ContactLoggedIn($client_contact, $client_contact->company, Ninja::eventVars())); + event(new ContactLoggedIn($client_contact, $client_contact->company, Ninja::eventVars())); } else { $error = [ 'message' => 'Invalid token', diff --git a/app/Http/Middleware/QueryLogging.php b/app/Http/Middleware/QueryLogging.php index bf71e2969221..4843070dc947 100644 --- a/app/Http/Middleware/QueryLogging.php +++ b/app/Http/Middleware/QueryLogging.php @@ -31,7 +31,6 @@ class QueryLogging */ public function handle(Request $request, Closure $next) { - $timeStart = microtime(true); // Enable query logging for development @@ -54,7 +53,6 @@ class QueryLogging // if($count > 50) // Log::info($queries); - } } diff --git a/app/Http/Middleware/SetEmailDb.php b/app/Http/Middleware/SetEmailDb.php index ec22cacae3d3..024a221e7e7c 100644 --- a/app/Http/Middleware/SetEmailDb.php +++ b/app/Http/Middleware/SetEmailDb.php @@ -38,7 +38,7 @@ class SetEmailDb if (! MultiDB::userFindAndSetDb($request->input('email'))) { return response()->json($error, 400); } - } + } // else { // return response()->json($error, 403); // } diff --git a/app/Http/Middleware/StartupCheck.php b/app/Http/Middleware/StartupCheck.php index 48f2517fdeb7..fe0c79a7533c 100644 --- a/app/Http/Middleware/StartupCheck.php +++ b/app/Http/Middleware/StartupCheck.php @@ -69,8 +69,9 @@ class StartupCheck /*Build template cache*/ - if ($request->has('clear_cache') || ! Cache::has('templates')) + if ($request->has('clear_cache') || ! Cache::has('templates')) { $this->buildTemplates(); + } $response = $next($request); diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 82fd6890763e..1d8b76576121 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -36,12 +36,12 @@ class TrustProxies extends Middleware * * @param \Illuminate\Contracts\Config\Repository $config */ - public function __construct(Repository $config) { - - parent::__construct($config); - - if (config('ninja.trusted_proxies')) - $this->proxies = config('ninja.trusted_proxies'); + public function __construct(Repository $config) + { + parent::__construct($config); + if (config('ninja.trusted_proxies')) { + $this->proxies = config('ninja.trusted_proxies'); + } } } diff --git a/app/Http/Requests/Expense/UpdateExpenseRequest.php b/app/Http/Requests/Expense/UpdateExpenseRequest.php index bbaddc7ad89a..05f3cb5af5b1 100644 --- a/app/Http/Requests/Expense/UpdateExpenseRequest.php +++ b/app/Http/Requests/Expense/UpdateExpenseRequest.php @@ -42,8 +42,9 @@ class UpdateExpenseRequest extends Request //$rules['id_number'] = 'unique:clients,id_number,,id,company_id,' . auth()->user()->company()->id; $rules['contacts.*.email'] = 'nullable|distinct'; - if(isset($this->number)) + if (isset($this->number)) { $rules['number'] = Rule::unique('expenses')->where('company_id', auth()->user()->company()->id)->ignore($this->expense->id); + } return $this->globalRules($rules); } diff --git a/app/Http/Requests/ExpenseCategory/UpdateExpenseCategoryRequest.php b/app/Http/Requests/ExpenseCategory/UpdateExpenseCategoryRequest.php index 27d1f2c83c2c..aaf661f7558c 100644 --- a/app/Http/Requests/ExpenseCategory/UpdateExpenseCategoryRequest.php +++ b/app/Http/Requests/ExpenseCategory/UpdateExpenseCategoryRequest.php @@ -13,6 +13,7 @@ namespace App\Http\Requests\ExpenseCategory; use App\Http\Requests\Request; use App\Utils\Traits\ChecksEntityStatus; + class UpdateExpenseCategoryRequest extends Request { use ChecksEntityStatus; @@ -29,13 +30,12 @@ class UpdateExpenseCategoryRequest extends Request public function rules() { - $rules = []; - if ($this->input('name')) + if ($this->input('name')) { $rules['name'] = 'unique:expense_categories,name,'.$this->id.',id,company_id,'.$this->expense_category->company_id; + } return $rules; } - } diff --git a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php index 844e309eb525..0beb6ed7988e 100644 --- a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php @@ -31,7 +31,6 @@ class StoreGroupSettingRequest extends Request public function rules() { - $rules['name'] = 'required|unique:group_settings,name,null,null,company_id,'.auth()->user()->companyId(); $rules['settings'] = new ValidClientGroupSettingsRule(); diff --git a/app/Http/Requests/Payment/StorePaymentRequest.php b/app/Http/Requests/Payment/StorePaymentRequest.php index 93afbd206cdf..b2ea76a15db9 100644 --- a/app/Http/Requests/Payment/StorePaymentRequest.php +++ b/app/Http/Requests/Payment/StorePaymentRequest.php @@ -39,7 +39,7 @@ class StorePaymentRequest extends Request { $input = $this->all(); - // info(print_r($input,1)); + // info(print_r($input,1)); $invoices_total = 0; $credits_total = 0; @@ -77,7 +77,7 @@ class StorePaymentRequest extends Request } if (! isset($input['amount']) || $input['amount'] == 0) { - $input['amount'] = $invoices_total - $credits_total; + $input['amount'] = $invoices_total - $credits_total; } $input['is_manual'] = true; diff --git a/app/Http/Requests/Payment/UpdatePaymentRequest.php b/app/Http/Requests/Payment/UpdatePaymentRequest.php index 961fd3e93274..182fccd83a81 100644 --- a/app/Http/Requests/Payment/UpdatePaymentRequest.php +++ b/app/Http/Requests/Payment/UpdatePaymentRequest.php @@ -35,8 +35,7 @@ class UpdatePaymentRequest extends Request public function rules() { - - $rules = [ + $rules = [ 'number' => 'nullable|unique:payments,number,'.$this->id.',id,company_id,'.$this->payment->company_id, 'invoices' => ['array', new PaymentAppliedValidAmount, new ValidCreditsPresentRule], 'invoices.*.invoice_id' => 'distinct', diff --git a/app/Http/Requests/Project/StoreProjectRequest.php b/app/Http/Requests/Project/StoreProjectRequest.php index a59dbbadb10f..a7f77e9d2c67 100644 --- a/app/Http/Requests/Project/StoreProjectRequest.php +++ b/app/Http/Requests/Project/StoreProjectRequest.php @@ -34,16 +34,16 @@ class StoreProjectRequest extends Request { $rules = []; - $rules['name'] = 'required'; - $rules['client_id'] = 'required|exists:clients,id,company_id,'.auth()->user()->company()->id; - $rules['number'] = 'unique:projects,number,'.$this->id.',id,company_id,'.auth()->user()->company()->id; + $rules['name'] = 'required'; + $rules['client_id'] = 'required|exists:clients,id,company_id,'.auth()->user()->company()->id; + $rules['number'] = 'unique:projects,number,'.$this->id.',id,company_id,'.auth()->user()->company()->id; return $this->globalRules($rules); } protected function prepareForValidation() { - $input = $this->decodePrimaryKeys($this->all()); + $input = $this->decodePrimaryKeys($this->all()); $this->replace($input); } diff --git a/app/Http/Requests/Project/UpdateProjectRequest.php b/app/Http/Requests/Project/UpdateProjectRequest.php index 48c4e947a140..89bc1d468176 100644 --- a/app/Http/Requests/Project/UpdateProjectRequest.php +++ b/app/Http/Requests/Project/UpdateProjectRequest.php @@ -33,18 +33,20 @@ class UpdateProjectRequest extends Request { $rules = []; - if(isset($this->number)) + if (isset($this->number)) { $rules['number'] = Rule::unique('projects')->where('company_id', auth()->user()->company()->id)->ignore($this->project->id); + } return $this->globalRules($rules); } protected function prepareForValidation() { - $input = $this->decodePrimaryKeys($this->all()); + $input = $this->decodePrimaryKeys($this->all()); - if(isset($input['client_id'])) + if (isset($input['client_id'])) { unset($input['client_id']); + } $this->replace($input); } diff --git a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php index 6c5fca03ccda..cba0442356a7 100644 --- a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php @@ -100,29 +100,30 @@ class StoreRecurringInvoiceRequest extends Request $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; - if(isset($input['auto_bill'])) + if (isset($input['auto_bill'])) { $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); - else{ - - if($client = Client::find($input['client_id'])) + } else { + if ($client = Client::find($input['client_id'])) { $input['auto_bill'] = $client->getSetting('auto_bill'); + } } - $this->replace($input); + $this->replace($input); } private function setAutoBillFlag($auto_bill) { - if($auto_bill == 'always') + if ($auto_bill == 'always') { return true; + } - if($auto_bill == 'off') + if ($auto_bill == 'off') { return false; - + } } - public function messages() - { - return []; - } + public function messages() + { + return []; + } } diff --git a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php index cd512f03f09b..a02fa5a989b0 100644 --- a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php @@ -36,7 +36,6 @@ class UpdateRecurringInvoiceRequest extends Request public function rules() { - $rules = []; if ($this->input('documents') && is_array($this->input('documents'))) { @@ -90,33 +89,32 @@ class UpdateRecurringInvoiceRequest extends Request $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; - if(isset($input['auto_bill'])) + if (isset($input['auto_bill'])) { $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); + } $this->replace($input); } /** * if($auto_bill == '') - * off / optin / optout will reset the status of this field to off to allow + * off / optin / optout will reset the status of this field to off to allow * the client to choose whether to auto_bill or not. - * + * * @param enum $auto_bill off/always/optin/optout * * @return bool */ private function setAutoBillFlag($auto_bill) :bool { - - if($auto_bill == 'always') + if ($auto_bill == 'always') { return true; + } // if($auto_bill == '') - // off / optin / optout will reset the status of this field to off to allow + // off / optin / optout will reset the status of this field to off to allow // the client to choose whether to auto_bill or not. return false; - } - } diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index 5e31c967e522..5b30670aa357 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -17,7 +17,7 @@ use Illuminate\Foundation\Http\FormRequest; class Request extends FormRequest { - use MakesHash; + use MakesHash; /** * Get the validation rules that apply to the request. @@ -31,22 +31,22 @@ class Request extends FormRequest public function globalRules($rules) { - $merge_rules = []; + $merge_rules = []; - foreach($this->all() as $key => $value) - { - if(method_exists($this, $key)) - $merge_rules = $this->{$key}($rules); - } + foreach ($this->all() as $key => $value) { + if (method_exists($this, $key)) { + $merge_rules = $this->{$key}($rules); + } + } - return array_merge($merge_rules, $rules); + return array_merge($merge_rules, $rules); } private function assigned_user_id($rules) - { - $rules['assigned_user_id'] = [ - 'bail' , - 'sometimes', + { + $rules['assigned_user_id'] = [ + 'bail' , + 'sometimes', 'nullable', new RelatedUserRule($this->all()) ]; @@ -70,7 +70,6 @@ class Request extends FormRequest public function decodePrimaryKeys($input) { - if (array_key_exists('assigned_user_id', $input) && is_string($input['assigned_user_id'])) { $input['assigned_user_id'] = $this->decodePrimaryKey($input['assigned_user_id']); } @@ -81,15 +80,15 @@ class Request extends FormRequest if (array_key_exists('vendor_id', $input) && is_string($input['vendor_id'])) { $input['vendor_id'] = $this->decodePrimaryKey($input['vendor_id']); - } + } if (array_key_exists('client_id', $input) && is_string($input['client_id'])) { $input['client_id'] = $this->decodePrimaryKey($input['client_id']); - } + } if (array_key_exists('invoice_id', $input) && is_string($input['invoice_id'])) { $input['invoice_id'] = $this->decodePrimaryKey($input['invoice_id']); - } + } if (array_key_exists('design_id', $input) && is_string($input['design_id'])) { $input['design_id'] = $this->decodePrimaryKey($input['design_id']); @@ -146,6 +145,6 @@ class Request extends FormRequest } } - return $input; + return $input; } } diff --git a/app/Http/Requests/Task/StoreTaskRequest.php b/app/Http/Requests/Task/StoreTaskRequest.php index 6bd1bce41387..a7813c7a9c23 100644 --- a/app/Http/Requests/Task/StoreTaskRequest.php +++ b/app/Http/Requests/Task/StoreTaskRequest.php @@ -38,17 +38,18 @@ class StoreTaskRequest extends Request { $rules = []; - if(isset($this->number)) + if (isset($this->number)) { $rules['number'] = Rule::unique('tasks')->where('company_id', auth()->user()->company()->id); + } - return $this->globalRules($rules); + return $this->globalRules($rules); } protected function prepareForValidation() { $input = $this->all(); - $input = $this->decodePrimaryKeys($this->all()); + $input = $this->decodePrimaryKeys($this->all()); if (array_key_exists('status_id', $input) && is_string($input['status_id'])) { $input['status_id'] = $this->decodePrimaryKey($input['status_id']); @@ -56,5 +57,4 @@ class StoreTaskRequest extends Request $this->replace($input); } - } diff --git a/app/Http/Requests/Task/UpdateTaskRequest.php b/app/Http/Requests/Task/UpdateTaskRequest.php index 16a1e3882e1f..1610800efb49 100644 --- a/app/Http/Requests/Task/UpdateTaskRequest.php +++ b/app/Http/Requests/Task/UpdateTaskRequest.php @@ -38,15 +38,16 @@ class UpdateTaskRequest extends Request { $rules = []; - if(isset($this->number)) + if (isset($this->number)) { $rules['number'] = Rule::unique('tasks')->where('company_id', auth()->user()->company()->id)->ignore($this->task->id); + } return $this->globalRules($rules); } protected function prepareForValidation() { - $input = $this->decodePrimaryKeys($this->all()); + $input = $this->decodePrimaryKeys($this->all()); if (array_key_exists('status_id', $input) && is_string($input['status_id'])) { $input['status_id'] = $this->decodePrimaryKey($input['status_id']); diff --git a/app/Http/Requests/TaskStatus/UpdateTaskStatusRequest.php b/app/Http/Requests/TaskStatus/UpdateTaskStatusRequest.php index d6e550427f98..b0d822ca3af1 100644 --- a/app/Http/Requests/TaskStatus/UpdateTaskStatusRequest.php +++ b/app/Http/Requests/TaskStatus/UpdateTaskStatusRequest.php @@ -33,10 +33,10 @@ class UpdateTaskStatusRequest extends Request { $rules = []; - if ($this->input('name')) - $rules['name'] = 'unique:task_statuses,name,'.$this->id.',id,company_id,'.$this->task_status->company_id; + if ($this->input('name')) { + $rules['name'] = 'unique:task_statuses,name,'.$this->id.',id,company_id,'.$this->task_status->company_id; + } - return $rules; + return $rules; } - } diff --git a/app/Http/ValidationRules/Credit/CreditsSumRule.php b/app/Http/ValidationRules/Credit/CreditsSumRule.php index 134a8bbe76b9..5da527372f96 100644 --- a/app/Http/ValidationRules/Credit/CreditsSumRule.php +++ b/app/Http/ValidationRules/Credit/CreditsSumRule.php @@ -41,12 +41,11 @@ class CreditsSumRule implements Rule private function checkCreditTotals() { - - if( array_sum(array_column($this->input['credits'],'amount')) > array_sum(array_column($this->input['invoices'], 'amount'))) + if (array_sum(array_column($this->input['credits'], 'amount')) > array_sum(array_column($this->input['invoices'], 'amount'))) { return false; + } return true; - } /** diff --git a/app/Http/ValidationRules/Expense/UniqueExpenseNumberRule.php b/app/Http/ValidationRules/Expense/UniqueExpenseNumberRule.php index dc1c0c5195f4..1e7ea875dd24 100644 --- a/app/Http/ValidationRules/Expense/UniqueExpenseNumberRule.php +++ b/app/Http/ValidationRules/Expense/UniqueExpenseNumberRule.php @@ -51,8 +51,9 @@ class UniqueExpenseNumberRule implements Rule */ private function checkIfExpenseNumberUnique() : bool { - if(empty($this->input['number'])) + if (empty($this->input['number'])) { return true; + } $expense = Expense::query() ->where('number', $this->input['number']) diff --git a/app/Http/ValidationRules/Invoice/UniqueInvoiceNumberRule.php b/app/Http/ValidationRules/Invoice/UniqueInvoiceNumberRule.php index 1cecd095cf2b..cc45ff9d1206 100644 --- a/app/Http/ValidationRules/Invoice/UniqueInvoiceNumberRule.php +++ b/app/Http/ValidationRules/Invoice/UniqueInvoiceNumberRule.php @@ -51,8 +51,9 @@ class UniqueInvoiceNumberRule implements Rule */ private function checkIfInvoiceNumberUnique() : bool { - if(empty($this->input['number'])) + if (empty($this->input['number'])) { return true; + } $invoice = Invoice::where('client_id', $this->input['client_id']) ->where('number', $this->input['number']) diff --git a/app/Http/ValidationRules/PaymentAmountsBalanceRule.php b/app/Http/ValidationRules/PaymentAmountsBalanceRule.php index cc9ff5251b21..35146355c7e1 100644 --- a/app/Http/ValidationRules/PaymentAmountsBalanceRule.php +++ b/app/Http/ValidationRules/PaymentAmountsBalanceRule.php @@ -73,8 +73,8 @@ class PaymentAmountsBalanceRule implements Rule return true; } // if no invoices are present, then this is an unapplied payment, let this pass validation! -// info("payment amounts = {$payment_amounts}"); -// info("invoice amounts = {$invoice_amounts}"); + // info("payment amounts = {$payment_amounts}"); + // info("invoice amounts = {$invoice_amounts}"); return $payment_amounts >= $invoice_amounts; } diff --git a/app/Http/ValidationRules/Project/ValidProjectForClient.php b/app/Http/ValidationRules/Project/ValidProjectForClient.php index e33d5366a2bd..2118686a1155 100644 --- a/app/Http/ValidationRules/Project/ValidProjectForClient.php +++ b/app/Http/ValidationRules/Project/ValidProjectForClient.php @@ -35,11 +35,13 @@ class ValidProjectForClient implements Rule */ public function passes($attribute, $value) { - if(empty($this->input['project_id'])) + if (empty($this->input['project_id'])) { return true; + } - if(is_string($this->input['project_id'])) + if (is_string($this->input['project_id'])) { $this->input['project_id'] = $this->decodePrimaryKey($this->input['project_id']); + } $project = Project::findOrFail($this->input['project_id']); @@ -53,6 +55,4 @@ class ValidProjectForClient implements Rule { return "Project client does not match entity client"; } - - } diff --git a/app/Http/ValidationRules/Recurring/UniqueRecurringInvoiceNumberRule.php b/app/Http/ValidationRules/Recurring/UniqueRecurringInvoiceNumberRule.php index d37cbcfa05ea..124118bbc90a 100644 --- a/app/Http/ValidationRules/Recurring/UniqueRecurringInvoiceNumberRule.php +++ b/app/Http/ValidationRules/Recurring/UniqueRecurringInvoiceNumberRule.php @@ -52,8 +52,9 @@ class UniqueRecurringInvoiceNumberRule implements Rule */ private function checkIfInvoiceNumberUnique() : bool { - if(empty($this->input['number'])) + if (empty($this->input['number'])) { return true; + } $invoice = RecurringInvoice::where('client_id', $this->input['client_id']) ->where('number', $this->input['number']) diff --git a/app/Http/ValidationRules/User/RelatedUserRule.php b/app/Http/ValidationRules/User/RelatedUserRule.php index 43958e7a49b9..f554684b3edc 100644 --- a/app/Http/ValidationRules/User/RelatedUserRule.php +++ b/app/Http/ValidationRules/User/RelatedUserRule.php @@ -50,9 +50,9 @@ class RelatedUserRule implements Rule */ private function checkUserIsRelated($user_id) : bool { - - if(empty($user_id)) + if (empty($user_id)) { return true; + } return User::query() ->where('id', $user_id) diff --git a/app/Http/ValidationRules/ValidCreditsPresentRule.php b/app/Http/ValidationRules/ValidCreditsPresentRule.php index 46d1de283e51..6f24b1b0f181 100644 --- a/app/Http/ValidationRules/ValidCreditsPresentRule.php +++ b/app/Http/ValidationRules/ValidCreditsPresentRule.php @@ -60,7 +60,6 @@ class ValidCreditsPresentRule implements Rule if (request()->input('credits') && is_array(request()->input('credits'))) { - $credit_collection = Credit::whereIn('id', $this->transformKeys(array_column(request()->input('credits'), 'credit_id'))) ->where('balance', '>', 0) ->get(); diff --git a/app/Http/ViewComposers/PortalComposer.php b/app/Http/ViewComposers/PortalComposer.php index 5f1a172ef57b..5d36d37c4e89 100644 --- a/app/Http/ViewComposers/PortalComposer.php +++ b/app/Http/ViewComposers/PortalComposer.php @@ -32,8 +32,9 @@ class PortalComposer { $view->with($this->portalData()); - if(auth()->user()) + if (auth()->user()) { Lang::replace(Ninja::transformTranslations(auth()->user()->client->getMergedSettings())); + } } /** @@ -73,7 +74,7 @@ class PortalComposer $data[] = ['title' => ctrans('texts.documents'), 'url' => 'client.documents.index', 'icon' => 'download']; if (auth()->user('contact')->client->getSetting('enable_client_portal_tasks')) { - $data[] = ['title' => ctrans('texts.tasks'), 'url' => 'client.dashboard', 'icon' => 'clock']; + $data[] = ['title' => ctrans('texts.tasks'), 'url' => 'client.dashboard', 'icon' => 'clock']; // TODO: Update when 'tasks' module is available in client portal. } diff --git a/app/Jobs/Cron/RecurringInvoicesCron.php b/app/Jobs/Cron/RecurringInvoicesCron.php index 6927648d0b0c..efc441756cde 100644 --- a/app/Jobs/Cron/RecurringInvoicesCron.php +++ b/app/Jobs/Cron/RecurringInvoicesCron.php @@ -22,7 +22,7 @@ use Illuminate\Support\Facades\Log; class RecurringInvoicesCron { - use Dispatchable; + use Dispatchable; /** * Create a new job instance. @@ -44,27 +44,23 @@ class RecurringInvoicesCron info("Sending recurring invoices ".Carbon::now()->format('Y-m-d h:i:s')); if (! config('ninja.db.multi_db_enabled')) { - - $recurring_invoices = RecurringInvoice::whereDate('next_send_date', '=', now()) + $recurring_invoices = RecurringInvoice::whereDate('next_send_date', '=', now()) ->where('status_id', RecurringInvoice::STATUS_ACTIVE) ->with('company') ->cursor(); - Log::info(now()->format('Y-m-d') . ' Sending Recurring Invoices. Count = '.$recurring_invoices->count()); - - $recurring_invoices->each(function ($recurring_invoice, $key) { + Log::info(now()->format('Y-m-d') . ' Sending Recurring Invoices. Count = '.$recurring_invoices->count()); + $recurring_invoices->each(function ($recurring_invoice, $key) { info("Current date = " . now()->format("Y-m-d") . " Recurring date = " .$recurring_invoice->next_send_date); - if(!$recurring_invoice->company->is_disabled) + if (!$recurring_invoice->company->is_disabled) { SendRecurring::dispatchNow($recurring_invoice, $recurring_invoice->company->db); - + } }); - } else { //multiDB environment, need to foreach (MultiDB::$dbs as $db) { - MultiDB::setDB($db); $recurring_invoices = RecurringInvoice::whereDate('next_send_date', '=', now()) @@ -75,12 +71,11 @@ class RecurringInvoicesCron Log::info(now()->format('Y-m-d') . ' Sending Recurring Invoices. Count = '.$recurring_invoices->count().' On Database # '.$db); $recurring_invoices->each(function ($recurring_invoice, $key) { - info("Current date = " . now()->format("Y-m-d") . " Recurring date = " .$recurring_invoice->next_send_date); - if(!$recurring_invoice->company->is_disabled) + if (!$recurring_invoice->company->is_disabled) { SendRecurring::dispatchNow($recurring_invoice, $recurring_invoice->company->db); - + } }); } } diff --git a/app/Jobs/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php index a3847da9fe4c..982eadc06c38 100644 --- a/app/Jobs/Entity/CreateEntityPdf.php +++ b/app/Jobs/Entity/CreateEntityPdf.php @@ -72,19 +72,16 @@ class CreateEntityPdf implements ShouldQueue { $this->invitation = $invitation; - if($invitation instanceof InvoiceInvitation){ + if ($invitation instanceof InvoiceInvitation) { $this->entity = $invitation->invoice; $this->entity_string = 'invoice'; - } - elseif($invitation instanceof QuoteInvitation){ + } elseif ($invitation instanceof QuoteInvitation) { $this->entity = $invitation->quote; $this->entity_string = 'quote'; - } - elseif($invitation instanceof CreditInvitation){ + } elseif ($invitation instanceof CreditInvitation) { $this->entity = $invitation->credit; $this->entity_string = 'credit'; - } - elseif($invitation instanceof RecurringInvoiceInvitation){ + } elseif ($invitation instanceof RecurringInvoiceInvitation) { $this->entity = $invitation->recurring_invoice; $this->entity_string = 'recurring_invoice'; } @@ -98,7 +95,6 @@ class CreateEntityPdf implements ShouldQueue public function handle() { - if (config('ninja.phantomjs_key')) { return (new Phantom)->generate($this->invitation); } @@ -108,15 +104,13 @@ class CreateEntityPdf implements ShouldQueue $entity_design_id = ''; - if($this->entity instanceof Invoice){ + if ($this->entity instanceof Invoice) { $path = $this->entity->client->invoice_filepath(); $entity_design_id = 'invoice_design_id'; - } - elseif($this->entity instanceof Quote){ + } elseif ($this->entity instanceof Quote) { $path = $this->entity->client->quote_filepath(); $entity_design_id = 'quote_design_id'; - } - elseif($this->entity instanceof Credit){ + } elseif ($this->entity instanceof Credit) { $path = $this->entity->client->credit_filepath(); $entity_design_id = 'credit_design_id'; } @@ -131,12 +125,12 @@ class CreateEntityPdf implements ShouldQueue $html = new HtmlEngine($this->invitation); if ($design->is_custom) { - $options = [ + $options = [ 'custom_partials' => json_decode(json_encode($design->design), true) ]; - $template = new PdfMakerDesign(PdfDesignModel::CUSTOM, $options); + $template = new PdfMakerDesign(PdfDesignModel::CUSTOM, $options); } else { - $template = new PdfMakerDesign(strtolower($design->name)); + $template = new PdfMakerDesign(strtolower($design->name)); } $state = [ @@ -165,15 +159,14 @@ class CreateEntityPdf implements ShouldQueue $pdf = null; try { - $pdf = $this->makePdf(null, null, $maker->getCompiledHTML(true)); - } - catch(\Exception $e) { - info(print_r($e->getMessage(),1)); + } catch (\Exception $e) { + info(print_r($e->getMessage(), 1)); } - if($pdf) + if ($pdf) { $instance = Storage::disk($this->disk)->put($file_path, $pdf); + } return $file_path; } diff --git a/app/Jobs/Entity/EmailEntity.php b/app/Jobs/Entity/EmailEntity.php index c6ab3c30f197..1daf8e0bf61a 100644 --- a/app/Jobs/Entity/EmailEntity.php +++ b/app/Jobs/Entity/EmailEntity.php @@ -88,7 +88,6 @@ class EmailEntity extends BaseMailerJob implements ShouldQueue $this->template_data = $template_data; $this->email_entity_builder = $this->resolveEmailBuilder(); - } /** @@ -99,8 +98,9 @@ class EmailEntity extends BaseMailerJob implements ShouldQueue */ public function handle() { - if($this->company->is_disabled) + if ($this->company->is_disabled) { return true; + } MultiDB::setDB($this->company->db); @@ -132,14 +132,15 @@ class EmailEntity extends BaseMailerJob implements ShouldQueue private function resolveEntityString() :string { - if($this->invitation instanceof InvoiceInvitation) + if ($this->invitation instanceof InvoiceInvitation) { return 'invoice'; - elseif($this->invitation instanceof QuoteInvitation) + } elseif ($this->invitation instanceof QuoteInvitation) { return 'quote'; - elseif($this->invitation instanceof CreditInvitation) + } elseif ($this->invitation instanceof CreditInvitation) { return 'credit'; - elseif($this->invitation instanceof RecurringInvoiceInvitation) + } elseif ($this->invitation instanceof RecurringInvoiceInvitation) { return 'recurring_invoice'; + } } private function entityEmailFailed($message) @@ -153,7 +154,6 @@ class EmailEntity extends BaseMailerJob implements ShouldQueue # code... break; } - } private function entityEmailSucceeded() diff --git a/app/Jobs/Invoice/ZipInvoices.php b/app/Jobs/Invoice/ZipInvoices.php index ad3619923105..e614352c5701 100644 --- a/app/Jobs/Invoice/ZipInvoices.php +++ b/app/Jobs/Invoice/ZipInvoices.php @@ -97,10 +97,8 @@ class ZipInvoices extends BaseMailerJob implements ShouldQueue try { Mail::to($this->email) ->send(new DownloadInvoices(Storage::disk(config('filesystems.default'))->url($path.$file_name), $this->company)); - } - catch (\Exception $e) { + } catch (\Exception $e) { $this->failed($e); - } UnlinkFile::dispatch(config('filesystems.default'), $path.$file_name)->delay(now()->addHours(1)); diff --git a/app/Jobs/Mail/BaseMailerJob.php b/app/Jobs/Mail/BaseMailerJob.php index a938086e133b..303591d0c435 100644 --- a/app/Jobs/Mail/BaseMailerJob.php +++ b/app/Jobs/Mail/BaseMailerJob.php @@ -104,6 +104,5 @@ class BaseMailerJob implements ShouldQueue LightLogs::create($job_failure) ->batch(); - } } diff --git a/app/Jobs/Mail/EntityPaidMailer.php b/app/Jobs/Mail/EntityPaidMailer.php index 2ca18b4a8916..f5ba0d8b7aa4 100644 --- a/app/Jobs/Mail/EntityPaidMailer.php +++ b/app/Jobs/Mail/EntityPaidMailer.php @@ -72,8 +72,9 @@ class EntityPaidMailer extends BaseMailerJob implements ShouldQueue public function handle() { /*If we are migrating data we don't want to fire these notification*/ - if ($this->company->is_disabled) + if ($this->company->is_disabled) { return true; + } //Set DB MultiDB::setDb($this->company->db); @@ -82,18 +83,15 @@ class EntityPaidMailer extends BaseMailerJob implements ShouldQueue $this->setMailDriver(); try { - $mail_obj = (new EntityPaidObject($this->payment))->build(); $mail_obj->from = [$this->user->email, $this->user->present()->name()]; //send email Mail::to($this->user->email) ->send(new EntityNotificationMailer($mail_obj)); - } catch (\Exception $e) { $this->failed($e); $this->logMailError($e->getMessage(), $this->payment->client); } - } } diff --git a/app/Jobs/Mail/EntitySentMailer.php b/app/Jobs/Mail/EntitySentMailer.php index 88b120913ee4..a21b052f243f 100644 --- a/app/Jobs/Mail/EntitySentMailer.php +++ b/app/Jobs/Mail/EntitySentMailer.php @@ -76,8 +76,9 @@ class EntitySentMailer extends BaseMailerJob implements ShouldQueue public function handle() { /*If we are migrating data we don't want to fire these notification*/ - if ($this->company->is_disabled) + if ($this->company->is_disabled) { return true; + } //Set DB MultiDB::setDb($this->company->db); @@ -91,12 +92,9 @@ class EntitySentMailer extends BaseMailerJob implements ShouldQueue try { Mail::to($this->user->email) ->send(new EntityNotificationMailer($mail_obj)); - }catch(\Exception $e) { - + } catch (\Exception $e) { $this->failed($e); $this->logMailError($e->getMessage(), $this->entity->client); - } - } } diff --git a/app/Jobs/Mail/EntityViewedMailer.php b/app/Jobs/Mail/EntityViewedMailer.php index ba01dd8b88f1..278531ee8f4c 100644 --- a/app/Jobs/Mail/EntityViewedMailer.php +++ b/app/Jobs/Mail/EntityViewedMailer.php @@ -76,8 +76,9 @@ class EntityViewedMailer extends BaseMailerJob implements ShouldQueue public function handle() { /*If we are migrating data we don't want to fire these notification*/ - if ($this->company->is_disabled) + if ($this->company->is_disabled) { return true; + } //Set DB MultiDB::setDb($this->company->db); @@ -89,15 +90,12 @@ class EntityViewedMailer extends BaseMailerJob implements ShouldQueue $mail_obj->from = [$this->entity->user->email, $this->entity->user->present()->name()]; //send email - try{ + try { Mail::to($this->user->email) ->send(new EntityNotificationMailer($mail_obj)); - } - catch (\Exception $e) { - + } catch (\Exception $e) { $this->failed($e); $this->logMailError($e->getMessage(), $this->entity->client); - } } } diff --git a/app/Jobs/Mail/MailRouter.php b/app/Jobs/Mail/MailRouter.php index e0dcd4b31020..a532de21b477 100644 --- a/app/Jobs/Mail/MailRouter.php +++ b/app/Jobs/Mail/MailRouter.php @@ -67,8 +67,9 @@ class MailRouter extends BaseMailerJob implements ShouldQueue public function handle() { /*If we are migrating data we don't want to fire these notification*/ - if ($this->company->is_disabled) + if ($this->company->is_disabled) { return true; + } MultiDB::setDb($this->company->db); @@ -79,13 +80,9 @@ class MailRouter extends BaseMailerJob implements ShouldQueue try { Mail::to($this->to_user->email) ->send($this->mailable); - } - catch (\Exception $e) { - + } catch (\Exception $e) { $this->failed($e); $this->logMailError($e->getMessage(), $this->to_user); - } - } } diff --git a/app/Jobs/Mail/PaymentFailureMailer.php b/app/Jobs/Mail/PaymentFailureMailer.php index 1c405d477ce8..3828bfc5c666 100644 --- a/app/Jobs/Mail/PaymentFailureMailer.php +++ b/app/Jobs/Mail/PaymentFailureMailer.php @@ -77,8 +77,9 @@ class PaymentFailureMailer extends BaseMailerJob implements ShouldQueue public function handle() { /*If we are migrating data we don't want to fire these notification*/ - if ($this->company->is_disabled) + if ($this->company->is_disabled) { return true; + } //Set DB MultiDB::setDb($this->company->db); @@ -103,14 +104,10 @@ class PaymentFailureMailer extends BaseMailerJob implements ShouldQueue try { Mail::to($company_user->user->email) ->send(new EntityNotificationMailer($mail_obj)); - } - catch(\Exception $e) { - + } catch (\Exception $e) { $this->failed($e); $this->logMailError($e->getMessage(), $this->client); - } - } }); } diff --git a/app/Jobs/Ninja/RefundCancelledAccount.php b/app/Jobs/Ninja/RefundCancelledAccount.php index 9bc2e40ea74c..0a1154d153c6 100644 --- a/app/Jobs/Ninja/RefundCancelledAccount.php +++ b/app/Jobs/Ninja/RefundCancelledAccount.php @@ -41,16 +41,19 @@ class RefundCancelledAccount implements ShouldQueue $plan_details = $this->account->getPlanDetails(); - if(!$plan_details) + if (!$plan_details) { return; + } /* Trial user cancelling early.... */ - if ($plan_details['trial_plan']) + if ($plan_details['trial_plan']) { return; + } /* Is the plan Active? */ - if (! $plan_details['active']) + if (! $plan_details['active']) { return; + } /* Refundable client! */ diff --git a/app/Jobs/Ninja/SendReminders.php b/app/Jobs/Ninja/SendReminders.php index 6120332cd4c9..299dd1e0f607 100644 --- a/app/Jobs/Ninja/SendReminders.php +++ b/app/Jobs/Ninja/SendReminders.php @@ -47,26 +47,18 @@ class SendReminders implements ShouldQueue */ public function handle() { - info("Sending reminders ".Carbon::now()->format('Y-m-d h:i:s')); if (! config('ninja.db.multi_db_enabled')) { - $this->sendReminderEmails(); - - } else { //multiDB environment, need to - foreach (MultiDB::$dbs as $db) - { - + foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); $this->sendReminderEmails(); } - } - } @@ -80,21 +72,17 @@ class SendReminders implements ShouldQueue ->cursor(); //we only need invoices that are payable - $invoices->filter(function ($invoice){ - + $invoices->filter(function ($invoice) { return $invoice->isPayable(); + })->each(function ($invoice) { + $reminder_template = $invoice->calculateTemplate('invoice'); - })->each(function ($invoice){ - - $reminder_template = $invoice->calculateTemplate('invoice'); - - info("hitting a reminder for {$invoice->number} with template {$reminder_template}"); + info("hitting a reminder for {$invoice->number} with template {$reminder_template}"); - if(in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'endless_reminder'])) - $this->sendReminder($invoice, $reminder_template); - + if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'endless_reminder'])) { + $this->sendReminder($invoice, $reminder_template); + } }); - } private function checkSendSetting($invoice, $template) @@ -111,7 +99,7 @@ class SendReminders implements ShouldQueue break; case 'endless_reminder': return $invoice->client->getSetting('enable_reminder_endless'); - break; + break; default: return false; break; @@ -121,9 +109,9 @@ class SendReminders implements ShouldQueue /** * Create a collection of all possible reminder dates * and pass back the first one in chronology - * + * * @param Invoice $invoice - * @return Carbon $date + * @return Carbon $date */ private function calculateNextSendDate($invoice) { @@ -135,41 +123,41 @@ class SendReminders implements ShouldQueue $set_reminder2 = false; $set_reminder3 = false; - if((int)$settings->schedule_reminder1 > 0){ - + if ((int)$settings->schedule_reminder1 > 0) { $next_reminder_date = $this->calculateScheduledDate($invoice, (int)$settings->schedule_reminder1, (int)$settings->num_days_reminder1); - if($next_reminder_date->gt(Carbon::parse($invoice->last_sent_date))); - $dates->push($next_reminder_date); + if ($next_reminder_date->gt(Carbon::parse($invoice->last_sent_date))); + $dates->push($next_reminder_date); - if(!$invoice->reminder1_sent) + if (!$invoice->reminder1_sent) { $set_reminder1 = true; + } } - if((int)$settings->num_days_reminder2 > 0){ - + if ((int)$settings->num_days_reminder2 > 0) { $next_reminder_date = $this->calculateScheduledDate($invoice, (int)$settings->schedule_reminder2, (int)$settings->num_days_reminder2); - if($next_reminder_date->gt(Carbon::parse($invoice->last_sent_date))); - $dates->push($next_reminder_date); + if ($next_reminder_date->gt(Carbon::parse($invoice->last_sent_date))); + $dates->push($next_reminder_date); - if(!$invoice->reminder2_sent) + if (!$invoice->reminder2_sent) { $set_reminder3 = true; + } } - if((int)$settings->num_days_reminder3 > 0){ - + if ((int)$settings->num_days_reminder3 > 0) { $next_reminder_date = $this->calculateScheduledDate($invoice, (int)$settings->schedule_reminder3, (int)$settings->num_days_reminder3); - if($next_reminder_date->gt(Carbon::parse($invoice->last_sent_date))); - $dates->push($next_reminder_date); + if ($next_reminder_date->gt(Carbon::parse($invoice->last_sent_date))); + $dates->push($next_reminder_date); - if(!$invoice->reminder3_sent) + if (!$invoice->reminder3_sent) { $set_reminder3 = true; + } } //If all the available reminders have fired, we then start to fire the endless reminders - if((int)$settings->endless_reminder_frequency_id > 0 && !$set_reminder1 && !$set_reminder2 && !$set_reminder3) { + if ((int)$settings->endless_reminder_frequency_id > 0 && !$set_reminder1 && !$set_reminder2 && !$set_reminder3) { $dates->push($this->addTimeInterval($invoice->last_sent_date, (int)$settings->endless_reminder_frequency_id)); } @@ -179,10 +167,10 @@ class SendReminders implements ShouldQueue /** * Helper method which switches values based on the $schedule_reminder - * @param Invoice $invoice - * @param string $schedule_reminder - * @param int $num_days_reminder - * @return Carbon $date + * @param Invoice $invoice + * @param string $schedule_reminder + * @param int $num_days_reminder + * @return Carbon $date */ private function calculateScheduledDate($invoice, $schedule_reminder, $num_days_reminder) :?Carbon { @@ -204,48 +192,46 @@ class SendReminders implements ShouldQueue /** * Sends the reminder and/or late fee for the invoice. - * - * @param Invoice $invoice - * @param string $template - * @return void + * + * @param Invoice $invoice + * @param string $template + * @return void */ private function sendReminder($invoice, $template) :void { $invoice = $this->calcLateFee($invoice, $template); - $invoice->invitations->each(function ($invitation) use($template, $invoice){ + $invoice->invitations->each(function ($invitation) use ($template, $invoice) { //only send if enable_reminder setting is toggled to yes - if($this->checkSendSetting($invoice, $template)) { - + if ($this->checkSendSetting($invoice, $template)) { info("firing email"); EmailEntity::dispatchNow($invitation, $invitation->company, $template); - } - - }); - if($this->checkSendSetting($invoice, $template)) - event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars())); + if ($this->checkSendSetting($invoice, $template)) { + event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars())); + } - $invoice->last_sent_date = now(); - $invoice->next_send_date = $this->calculateNextSendDate($invoice); + $invoice->last_sent_date = now(); + $invoice->next_send_date = $this->calculateNextSendDate($invoice); - if(in_array($template, ['reminder1', 'reminder2', 'reminder3'])) - $invoice->{$template."_sent"} = now(); + if (in_array($template, ['reminder1', 'reminder2', 'reminder3'])) { + $invoice->{$template."_sent"} = now(); + } - $invoice->save(); + $invoice->save(); } /** * Calculates the late if - if any - and rebuilds the invoice - * - * @param Invoice $invoice - * @param string $template - * @return Invoice + * + * @param Invoice $invoice + * @param string $template + * @return Invoice */ private function calcLateFee($invoice, $template) :Invoice { @@ -268,7 +254,7 @@ class SendReminders implements ShouldQueue case 'endless_reminder': $late_fee_amount = $invoice->client->getSetting('late_fee_endless_amount'); $late_fee_percent = $invoice->client->getSetting('late_fee_endless_percent'); - break; + break; default: $late_fee_amount = 0; $late_fee_percent = 0; @@ -276,31 +262,32 @@ class SendReminders implements ShouldQueue } return $this->setLateFee($invoice, $late_fee_amount, $late_fee_percent); - } /** * Applies the late fee to the invoice line items - * - * @param Invoice $invoice + * + * @param Invoice $invoice * @param float $amount The fee amount * @param float $percent The fee percentage amount - * - * @return Invoice + * + * @return Invoice */ private function setLateFee($invoice, $amount, $percent) :Invoice { $temp_invoice_balance = $invoice->balance; - if ($amount <= 0 && $percent <= 0) + if ($amount <= 0 && $percent <= 0) { return $invoice; + } $fee = $amount; - if ($invoice->partial > 0) + if ($invoice->partial > 0) { $fee += round($invoice->partial * $percent / 100, 2); - else + } else { $fee += round($invoice->balance * $percent / 100, 2); + } $invoice_item = new InvoiceItem; $invoice_item->type_id = '5'; @@ -321,7 +308,5 @@ class SendReminders implements ShouldQueue $this->invoice->ledger()->updateInvoiceBalance($this->invoice->balance - $temp_invoice_balance); return $invoice; - } - -} \ No newline at end of file +} diff --git a/app/Jobs/Payment/EmailPayment.php b/app/Jobs/Payment/EmailPayment.php index 5e751b333f79..4bbaafc9f3c5 100644 --- a/app/Jobs/Payment/EmailPayment.php +++ b/app/Jobs/Payment/EmailPayment.php @@ -73,37 +73,29 @@ class EmailPayment extends BaseMailerJob implements ShouldQueue */ public function handle() { - - if($this->company->is_disabled) + if ($this->company->is_disabled) { return true; + } if ($this->contact->email) { - - MultiDB::setDb($this->company->db); + MultiDB::setDb($this->company->db); //if we need to set an email driver do it now $this->setMailDriver(); $email_builder = (new PaymentEmailEngine($this->payment, $this->contact))->build(); - try{ - + try { $mail = Mail::to($this->contact->email, $this->contact->present()->name()); $mail->send(new TemplateEmail($email_builder, $this->contact->user, $this->contact->client)); - - }catch(\Exception $e) { - + } catch (\Exception $e) { info("mailing failed with message " . $e->getMessage()); event(new PaymentWasEmailedAndFailed($this->payment, $this->company, Mail::failures(), Ninja::eventVars())); $this->failed($e); return $this->logMailError($e->getMessage(), $this->payment->client); - } event(new PaymentWasEmailed($this->payment, $this->payment->company, Ninja::eventVars())); - } } - - } diff --git a/app/Jobs/Product/UpdateOrCreateProduct.php b/app/Jobs/Product/UpdateOrCreateProduct.php index 4f7098b34ae8..bb655aa245f2 100644 --- a/app/Jobs/Product/UpdateOrCreateProduct.php +++ b/app/Jobs/Product/UpdateOrCreateProduct.php @@ -60,9 +60,7 @@ class UpdateOrCreateProduct implements ShouldQueue //only update / create products - not tasks or gateway fees $updateable_products = collect($this->products)->filter(function ($item) { - return $item->type_id == 1; - }); foreach ($updateable_products as $item) { @@ -98,6 +96,6 @@ class UpdateOrCreateProduct implements ShouldQueue public function failed($exception = null) { info("update create failed with = "); - info(print_r($exception->getMessage(),1)); + info(print_r($exception->getMessage(), 1)); } } diff --git a/app/Jobs/RecurringInvoice/SendRecurring.php b/app/Jobs/RecurringInvoice/SendRecurring.php index 3df78415c903..30c28d0783be 100644 --- a/app/Jobs/RecurringInvoice/SendRecurring.php +++ b/app/Jobs/RecurringInvoice/SendRecurring.php @@ -67,19 +67,18 @@ class SendRecurring implements ShouldQueue ->createInvitations() ->save(); - info("Invoice {$invoice->number} created"); + info("Invoice {$invoice->number} created"); $invoice->invitations->each(function ($invitation) use ($invoice) { - - if($invitation->contact && strlen($invitation->contact->email) >=1){ + if ($invitation->contact && strlen($invitation->contact->email) >=1) { EmailEntity::dispatch($invitation, $invoice->company); info("Firing email for invoice {$invoice->number}"); } - }); - if($invoice->client->getSetting('auto_bill_date') == 'on_send_date' && $this->recurring_invoice->auto_bill_enabled) + if ($invoice->client->getSetting('auto_bill_date') == 'on_send_date' && $this->recurring_invoice->auto_bill_enabled) { $invoice->service()->autoBill()->save(); + } info("updating recurring invoice dates"); /* Set next date here to prevent a recurring loop forming */ @@ -88,8 +87,9 @@ class SendRecurring implements ShouldQueue $this->recurring_invoice->last_sent_date = date('Y-m-d'); /* Set completed if we don't have any more cycles remaining*/ - if ($this->recurring_invoice->remaining_cycles == 0) + if ($this->recurring_invoice->remaining_cycles == 0) { $this->recurring_invoice->setCompleted(); + } info("next send date = " . $this->recurring_invoice->next_send_date); info("remaining cycles = " . $this->recurring_invoice->remaining_cycles); @@ -100,7 +100,6 @@ class SendRecurring implements ShouldQueue //this is duplicated!! // if ($invoice->invitations->count() > 0) // event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars())); - } public function failed($exception = null) @@ -116,5 +115,4 @@ class SendRecurring implements ShouldQueue info(print_r($exception->getMessage(), 1)); } - } diff --git a/app/Jobs/User/UserEmailChanged.php b/app/Jobs/User/UserEmailChanged.php index fb3a963d84a6..05cbda539ee6 100644 --- a/app/Jobs/User/UserEmailChanged.php +++ b/app/Jobs/User/UserEmailChanged.php @@ -54,8 +54,9 @@ class UserEmailChanged extends BaseMailerJob implements ShouldQueue public function handle() { - if($this->company->is_disabled) + if ($this->company->is_disabled) { return true; + } //Set DB MultiDB::setDb($this->company->db); @@ -74,19 +75,15 @@ class UserEmailChanged extends BaseMailerJob implements ShouldQueue //Send email via a Mailable class // try { - Mail::to($this->old_email) + Mail::to($this->old_email) ->send(new UserNotificationMailer($mail_obj)); - Mail::to($this->new_email) + Mail::to($this->new_email) ->send(new UserNotificationMailer($mail_obj)); - } - catch (\Exception $e) { - + } catch (\Exception $e) { $this->failed($e); $this->logMailError($e->getMessage(), $this->company->owner()); - } - } private function getData() diff --git a/app/Jobs/Util/Import.php b/app/Jobs/Util/Import.php index 5e26f3ceb784..197370068703 100644 --- a/app/Jobs/Util/Import.php +++ b/app/Jobs/Util/Import.php @@ -156,7 +156,7 @@ class Import implements ShouldQueue // public $backoff = 86430; - // public $maxExceptions = 2; + // public $maxExceptions = 2; /** * Create a new job instance. * @@ -178,16 +178,15 @@ class Import implements ShouldQueue * * @return bool */ - public function handle() + public function handle() { set_time_limit(0); - // $jsonStream = \JsonMachine\JsonMachine::fromFile($this->file_path, "/data"); + // $jsonStream = \JsonMachine\JsonMachine::fromFile($this->file_path, "/data"); $array = json_decode(file_get_contents($this->file_path), 1); $data = $array['data']; foreach ($this->available_imports as $import) { - if (! array_key_exists($import, $data)) { //throw new ResourceNotAvailableForMigration("Resource {$key} is not available for migration."); info("Resource {$import} is not available for migration."); @@ -210,7 +209,6 @@ class Import implements ShouldQueue CompanySizeCheck::dispatch(); info('Completed🚀🚀🚀🚀🚀 at '.now()); - } private function setInitialCompanyLedgerBalances() @@ -268,15 +266,12 @@ class Import implements ShouldQueue $company_repository = new CompanyRepository(); $company_repository->save($data, $this->company); - if(isset($data['settings']->company_logo) && strlen($data['settings']->company_logo) > 0) { - + if (isset($data['settings']->company_logo) && strlen($data['settings']->company_logo) > 0) { try { $tempImage = tempnam(sys_get_temp_dir(), basename($data['settings']->company_logo)); copy($data['settings']->company_logo, $tempImage); $this->uploadLogo($tempImage, $this->company, $this->company); - } - catch(\Exception $e){ - + } catch (\Exception $e) { } } @@ -596,7 +591,6 @@ class Import implements ShouldQueue $invoice_repository = new InvoiceMigrationRepository(); foreach ($data as $key => $resource) { - $modified = $resource; if (array_key_exists('client_id', $resource) && ! array_key_exists('clients', $this->ids)) { @@ -621,7 +615,6 @@ class Import implements ShouldQueue 'old' => $resource['id'], 'new' => $invoice->id, ]; - } RecurringInvoice::reguard(); @@ -629,7 +622,6 @@ class Import implements ShouldQueue /*Improve memory handling by setting everything to null when we have finished*/ $data = null; $invoice_repository = null; - } private function processInvoices(array $data): void @@ -785,7 +777,6 @@ class Import implements ShouldQueue private function processPayments(array $data): void { - Payment::reguard(); $rules = [ @@ -818,14 +809,12 @@ class Import implements ShouldQueue if (isset($modified['invoices'])) { foreach ($modified['invoices'] as $key => $invoice) { - - if($this->tryTransformingId('invoices', $invoice['invoice_id'])) + if ($this->tryTransformingId('invoices', $invoice['invoice_id'])) { $modified['invoices'][$key]['invoice_id'] = $this->transformId('invoices', $invoice['invoice_id']); - else{ + } else { $modified['credits'][$key]['credit_id'] = $this->transformId('credits', $invoice['invoice_id']); $modified['credits'][$key]['amount'] = $modified['invoices'][$key]['amount']; } - } } @@ -886,12 +875,12 @@ class Import implements ShouldQueue $payment->status_id = Payment::STATUS_PARTIALLY_REFUNDED; $payment->save(); return $payment; - break; + break; case 6: $payment->status_id = Payment::STATUS_REFUNDED; $payment->save(); return $payment; - break; + break; default: return $payment; @@ -901,11 +890,10 @@ class Import implements ShouldQueue private function processDocuments(array $data): void { - // Document::unguard(); + // Document::unguard(); /* No validators since data provided by database is already valid. */ - foreach($data as $resource) - { + foreach ($data as $resource) { $modified = $resource; if (array_key_exists('invoice_id', $resource) && $resource['invoice_id'] && ! array_key_exists('invoices', $this->ids)) { @@ -927,7 +915,6 @@ class Import implements ShouldQueue } $this->saveDocument(file_get_contents($resource['url']), $entity, $is_public = true); - } // foreach ($data as $resource) { @@ -1079,7 +1066,8 @@ class Import implements ShouldQueue } private function processTaskStatuses(array $data) :void - {info('in task statuses'); + { + info('in task statuses'); TaskStatus::unguard(); foreach ($data as $resource) { @@ -1149,17 +1137,21 @@ class Import implements ShouldQueue $modified['company_id'] = $this->company->id; $modified['user_id'] = $this->processUserId($resource); - if(isset($modified['client_id'])) + if (isset($modified['client_id'])) { $modified['client_id'] = $this->transformId('clients', $resource['client_id']); + } - if(isset($modified['invoice_id'])) + if (isset($modified['invoice_id'])) { $modified['invoice_id'] = $this->transformId('invoices', $resource['invoice_id']); + } - if(isset($modified['project_id'])) + if (isset($modified['project_id'])) { $modified['project_id'] = $this->transformId('projects', $resource['project_id']); + } - if(isset($modified['status_id'])) + if (isset($modified['status_id'])) { $modified['status_id'] = $this->transformId('task_statuses', $resource['status_id']); + } $task = Task::Create($modified); @@ -1190,8 +1182,9 @@ class Import implements ShouldQueue $modified['company_id'] = $this->company->id; $modified['user_id'] = $this->processUserId($resource); - if(isset($modified['client_id'])) + if (isset($modified['client_id'])) { $modified['client_id'] = $this->transformId('clients', $resource['client_id']); + } $project = Project::Create($modified); @@ -1201,7 +1194,6 @@ class Import implements ShouldQueue 'old' => $resource['id'], 'new' => $project->id, ]; - } Project::reguard(); @@ -1211,7 +1203,6 @@ class Import implements ShouldQueue private function processExpenses(array $data) :void { - Expense::unguard(); foreach ($data as $resource) { @@ -1222,20 +1213,25 @@ class Import implements ShouldQueue $modified['company_id'] = $this->company->id; $modified['user_id'] = $this->processUserId($resource); - if(isset($resource['client_id'])) + if (isset($resource['client_id'])) { $modified['client_id'] = $this->transformId('clients', $resource['client_id']); + } - if(isset($resource['category_id'])) + if (isset($resource['category_id'])) { $modified['category_id'] = $this->transformId('expense_categories', $resource['category_id']); + } - if(isset($resource['invoice_id'])) + if (isset($resource['invoice_id'])) { $modified['invoice_id'] = $this->transformId('invoices', $resource['invoice_id']); + } - if(isset($resource['project_id'])) + if (isset($resource['project_id'])) { $modified['project_id'] = $this->transformId('projects', $resource['project_id']); + } - if(isset($resource['vendor_id'])) + if (isset($resource['vendor_id'])) { $modified['vendor_id'] = $this->transformId('vendors', $resource['vendor_id']); + } $expense = Expense::Create($modified); @@ -1252,7 +1248,6 @@ class Import implements ShouldQueue Expense::reguard(); $data = null; - } /** * |-------------------------------------------------------------------------- @@ -1289,7 +1284,7 @@ class Import implements ShouldQueue public function transformId($resource, string $old): int { if (! array_key_exists($resource, $this->ids)) { - info(print_r($resource,1)); + info(print_r($resource, 1)); throw new Exception("Resource {$resource} not available."); } @@ -1345,7 +1340,5 @@ class Import implements ShouldQueue ->batch(); info(print_r($exception->getMessage(), 1)); - } - } diff --git a/app/Jobs/Util/ReminderJob.php b/app/Jobs/Util/ReminderJob.php index 4ad02907e345..2cbc6251e050 100644 --- a/app/Jobs/Util/ReminderJob.php +++ b/app/Jobs/Util/ReminderJob.php @@ -55,37 +55,27 @@ class ReminderJob implements ShouldQueue $this->processReminders($db); } } - } private function processReminders($db = null) { - Invoice::where('next_send_date', Carbon::today()->format('Y-m-d'))->with('invitations')->cursor()->each(function ($invoice) { - if ($invoice->isPayable()) { - - $reminder_template = $invoice->calculateTemplate('invoice'); + $reminder_template = $invoice->calculateTemplate('invoice'); $invoice->service()->touchReminder($this->reminder_template)->save(); $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) { - EmailEntity::dispatch($invitation, $invitation->company, $reminder_template); info("Firing email for invoice {$invoice->number}"); }); - if ($invoice->invitations->count() > 0) + if ($invoice->invitations->count() > 0) { event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars())); - - + } } else { - $invoice->next_send_date = null; $invoice->save(); - } - }); - } } diff --git a/app/Jobs/Util/SendFailedEmails.php b/app/Jobs/Util/SendFailedEmails.php index 19281c19a1e7..2882c11c0a19 100644 --- a/app/Jobs/Util/SendFailedEmails.php +++ b/app/Jobs/Util/SendFailedEmails.php @@ -55,7 +55,6 @@ class SendFailedEmails implements ShouldQueue private function processEmails() { - $email_jobs = SystemLog::where('event_id', SystemLog::EVENT_MAIL_RETRY_QUEUE)->get(); $email_jobs->each(function ($job) { @@ -64,7 +63,6 @@ class SendFailedEmails implements ShouldQueue $invitation = $job_meta_array['entity_name']::where('key', $job_meta_array['invitation_key'])->with('contact')->first(); if ($invitation->invoice) { - if ($invitation->contact->send_email && $invitation->contact->email) { EmailEntity::dispatch($invitation, $invitation->company, $job_meta_array['reminder_template']); } diff --git a/app/Jobs/Util/StartMigration.php b/app/Jobs/Util/StartMigration.php index e782549ae958..78eabfe608da 100644 --- a/app/Jobs/Util/StartMigration.php +++ b/app/Jobs/Util/StartMigration.php @@ -55,7 +55,7 @@ class StartMigration implements ShouldQueue public $timeout = 0; - // public $maxExceptions = 2; + // public $maxExceptions = 2; //public $backoff = 86430; @@ -111,7 +111,6 @@ class StartMigration implements ShouldQueue //Import::dispatchNow($data['data'], $this->company, $this->user); Import::dispatchNow($file, $this->company, $this->user); } catch (NonExistingMigrationFile | ProcessingMigrationArchiveFailed | ResourceNotAvailableForMigration | MigrationValidatorFailed | ResourceDependencyMissing $e) { - Mail::to($this->user)->send(new MigrationFailed($e, $e->getMessage())); if (app()->environment() !== 'production') { @@ -126,6 +125,6 @@ class StartMigration implements ShouldQueue public function failed($exception = null) { - info(print_r($exception->getMessage(),1)); + info(print_r($exception->getMessage(), 1)); } } diff --git a/app/Jobs/Util/WebhookHandler.php b/app/Jobs/Util/WebhookHandler.php index 11ec72cff38e..44abb02574b2 100644 --- a/app/Jobs/Util/WebhookHandler.php +++ b/app/Jobs/Util/WebhookHandler.php @@ -63,21 +63,22 @@ class WebhookHandler implements ShouldQueue MultiDB::setDb($this->company->db); - if (! $this->company || $this->company->is_disabled) + if (! $this->company || $this->company->is_disabled) { return true; + } $subscriptions = Webhook::where('company_id', $this->company->id) ->where('event_id', $this->event_id) ->get(); - if (! $subscriptions || $subscriptions->count() == 0) + if (! $subscriptions || $subscriptions->count() == 0) { return; + } $subscriptions->each(function ($subscription) { $this->process($subscription); }); - } private function process($subscription) diff --git a/app/Listeners/Invoice/InvoiceEmailedNotification.php b/app/Listeners/Invoice/InvoiceEmailedNotification.php index 95dec6fe1c2d..f1197397d2da 100644 --- a/app/Listeners/Invoice/InvoiceEmailedNotification.php +++ b/app/Listeners/Invoice/InvoiceEmailedNotification.php @@ -62,7 +62,6 @@ class InvoiceEmailedNotification implements ShouldQueue EntitySentMailer::dispatch($event->invitation, 'invoice', $user, $event->invitation->company); $first_notification_sent = false; - } $notification->method = $methods; diff --git a/app/Listeners/Invoice/InvoicePaidActivity.php b/app/Listeners/Invoice/InvoicePaidActivity.php index c90bf32afbb5..415dc13978bc 100644 --- a/app/Listeners/Invoice/InvoicePaidActivity.php +++ b/app/Listeners/Invoice/InvoicePaidActivity.php @@ -57,9 +57,8 @@ class InvoicePaidActivity implements ShouldQueue try { $event->invoice->service()->touchPdf(); - } - catch(\Exception $e){ - info(print_r($e->getMessage(),1)); + } catch (\Exception $e) { + info(print_r($e->getMessage(), 1)); } } } diff --git a/app/Listeners/Payment/PaymentEmailFailureActivity.php b/app/Listeners/Payment/PaymentEmailFailureActivity.php index 78920d20da35..c4a7c628de74 100644 --- a/app/Listeners/Payment/PaymentEmailFailureActivity.php +++ b/app/Listeners/Payment/PaymentEmailFailureActivity.php @@ -50,8 +50,6 @@ class PaymentEmailFailureActivity implements ShouldQueue $payment = $event->payment; info("i failed emailing {$payment->number}"); - // info(print_r($event->errors,1)); - + // info(print_r($event->errors,1)); } } - diff --git a/app/Listeners/Payment/PaymentEmailedActivity.php b/app/Listeners/Payment/PaymentEmailedActivity.php index 60bc6e8785e1..938296fb04d4 100644 --- a/app/Listeners/Payment/PaymentEmailedActivity.php +++ b/app/Listeners/Payment/PaymentEmailedActivity.php @@ -52,4 +52,3 @@ class PaymentEmailedActivity implements ShouldQueue info("i succeeded in emailing payment {$payment->number}"); } } - diff --git a/app/Listeners/Payment/PaymentNotification.php b/app/Listeners/Payment/PaymentNotification.php index 07f194170169..854357ec9650 100644 --- a/app/Listeners/Payment/PaymentNotification.php +++ b/app/Listeners/Payment/PaymentNotification.php @@ -55,7 +55,6 @@ class PaymentNotification implements ShouldQueue /*User notifications*/ foreach ($payment->company->company_users as $company_user) { - $user = $company_user->user; $methods = $this->findUserEntityNotificationType($payment, $company_user, ['all_notifications']); @@ -64,7 +63,6 @@ class PaymentNotification implements ShouldQueue unset($methods[$key]); EntityPaidMailer::dispatch($payment, $payment->company, $user); - } $notification = new NewPaymentNotification($payment, $payment->company); diff --git a/app/Listeners/SendVerificationNotification.php b/app/Listeners/SendVerificationNotification.php index 2c1eb8a4f983..9e6457079d23 100644 --- a/app/Listeners/SendVerificationNotification.php +++ b/app/Listeners/SendVerificationNotification.php @@ -51,11 +51,8 @@ class SendVerificationNotification implements ShouldQueue $event->user->notify(new VerifyUser($event->user, $event->company)); Ninja::registerNinjaUser($event->user); - } catch (Exception $e) { - info("I couldn't send the email " . $e->getMessage()); - } } } diff --git a/app/Mail/DownloadInvoices.php b/app/Mail/DownloadInvoices.php index 21c8a4990085..6d07768ae419 100644 --- a/app/Mail/DownloadInvoices.php +++ b/app/Mail/DownloadInvoices.php @@ -40,6 +40,5 @@ class DownloadInvoices extends Mailable 'logo' => $this->company->present()->logo, ] ); - } } diff --git a/app/Mail/Engine/BaseEmailEngine.php b/app/Mail/Engine/BaseEmailEngine.php index 4b41dd965266..37c13c1f263b 100644 --- a/app/Mail/Engine/BaseEmailEngine.php +++ b/app/Mail/Engine/BaseEmailEngine.php @@ -13,129 +13,132 @@ namespace App\Mail\Engine; class BaseEmailEngine implements EngineInterface { - public $footer; + public $footer; - public $variables; + public $variables; - public $contact; + public $contact; - public $subject; + public $subject; - public $body; + public $body; - public $template_style; + public $template_style; - public $attachments; + public $attachments; - public $link; + public $link; - public $text; + public $text; public function setFooter($footer) { - $this->footer = $footer; + $this->footer = $footer; - return $this; + return $this; } public function setVariables($variables) { - $this->variables = $variables; + $this->variables = $variables; - return $this; + return $this; } public function setContact($contact) { - $this->contact = $contact; + $this->contact = $contact; - return $this; + return $this; } public function setSubject($subject) { - if (! empty($this->variables)) + if (! empty($this->variables)) { $subject = str_replace(array_keys($this->variables), array_values($this->variables), $subject); + } - $this->subject = $subject; + $this->subject = $subject; - return $this; + return $this; } public function setBody($body) { - if (! empty($this->variables)) + if (! empty($this->variables)) { $body = str_replace(array_keys($this->variables), array_values($this->variables), $body); + } - $this->body = $body; + $this->body = $body; - return $this; + return $this; } public function setTemplate($template_style) { - $this->template_style = $template_style; + $this->template_style = $template_style; - return $this; + return $this; } public function setAttachments($attachments) { - $this->attachments = $attachments; + $this->attachments = $attachments; - return $this; + return $this; } public function setViewLink($link) { - $this->link = $link; + $this->link = $link; - return $this; + return $this; } public function setViewText($text) { - $this->text = $text; + $this->text = $text; - return $this; + return $this; } public function getSubject() { - return $this->subject; + return $this->subject; } public function getBody() { - return $this->body; + return $this->body; } public function getAttachments() { - return $this->attachments; + return $this->attachments; } public function getFooter() { - return $this->footer; + return $this->footer; } public function getTemplate() { - return $this->template_style; + return $this->template_style; } public function getViewLink() { - return $this->link; + return $this->link; } public function getViewText() { - return $this->text; + return $this->text; } - public function build(){} - -} \ No newline at end of file + public function build() + { + } +} diff --git a/app/Mail/Engine/CreditEmailEngine.php b/app/Mail/Engine/CreditEmailEngine.php index 7529767001eb..7cbcbc0ec44b 100644 --- a/app/Mail/Engine/CreditEmailEngine.php +++ b/app/Mail/Engine/CreditEmailEngine.php @@ -14,15 +14,15 @@ namespace App\Mail\Engine; use App\Utils\HtmlEngine; use App\Utils\Number; -class CreditEmailEngine extends BaseEmailEngine +class CreditEmailEngine extends BaseEmailEngine { - public $invitation; + public $invitation; - public $client; + public $client; - public $credit; + public $credit; - public $contact; + public $contact; public $reminder_template; @@ -30,7 +30,7 @@ class CreditEmailEngine extends BaseEmailEngine public function __construct($invitation, $reminder_template, $template_data) { - $this->invitation = $invitation; + $this->invitation = $invitation; $this->reminder_template = $reminder_template; $this->client = $invitation->contact->client; $this->credit = $invitation->credit; @@ -40,11 +40,11 @@ class CreditEmailEngine extends BaseEmailEngine public function build() { - - if(is_array($this->template_data) && array_key_exists('body', $this->template_data) && strlen($this->template_data['body']) > 0) + if (is_array($this->template_data) && array_key_exists('body', $this->template_data) && strlen($this->template_data['body']) > 0) { $body_template = $this->template_data['body']; - else + } else { $body_template = $this->client->getSetting('email_template_'.$this->reminder_template); + } /* Use default translations if a custom message has not been set*/ if (iconv_strlen($body_template) == 0) { @@ -60,13 +60,13 @@ class CreditEmailEngine extends BaseEmailEngine ); } - if(is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) + if (is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) { $subject_template = $this->template_data['subject']; - else + } else { $subject_template = $this->client->getSetting('email_subject_'.$this->reminder_template); + } if (iconv_strlen($subject_template) == 0) { - $subject_template = trans( 'texts.credit_subject', [ @@ -76,7 +76,6 @@ class CreditEmailEngine extends BaseEmailEngine null, $this->client->locale() ); - } $this->setTemplate($this->client->getSetting('email_style')) @@ -93,8 +92,5 @@ class CreditEmailEngine extends BaseEmailEngine } return $this; - } - } - diff --git a/app/Mail/Engine/EngineInterface.php b/app/Mail/Engine/EngineInterface.php index 9196b1a1619a..8518ffe8b535 100644 --- a/app/Mail/Engine/EngineInterface.php +++ b/app/Mail/Engine/EngineInterface.php @@ -13,7 +13,6 @@ namespace App\Mail\Engine; interface EngineInterface { - public function setFooter($footer); public function setVariables($variables); @@ -47,5 +46,4 @@ interface EngineInterface public function getViewText(); public function build(); - -} \ No newline at end of file +} diff --git a/app/Mail/Engine/InvoiceEmailEngine.php b/app/Mail/Engine/InvoiceEmailEngine.php index 3a455925f846..af72ac485fe9 100644 --- a/app/Mail/Engine/InvoiceEmailEngine.php +++ b/app/Mail/Engine/InvoiceEmailEngine.php @@ -15,15 +15,15 @@ use App\DataMapper\EmailTemplateDefaults; use App\Utils\HtmlEngine; use App\Utils\Number; -class InvoiceEmailEngine extends BaseEmailEngine +class InvoiceEmailEngine extends BaseEmailEngine { - public $invitation; + public $invitation; - public $client; + public $client; - public $invoice; + public $invoice; - public $contact; + public $contact; public $reminder_template; @@ -31,7 +31,7 @@ class InvoiceEmailEngine extends BaseEmailEngine public function __construct($invitation, $reminder_template, $template_data) { - $this->invitation = $invitation; + $this->invitation = $invitation; $this->reminder_template = $reminder_template; $this->client = $invitation->contact->client; $this->invoice = $invitation->invoice; @@ -41,12 +41,11 @@ class InvoiceEmailEngine extends BaseEmailEngine public function build() { - - if(is_array($this->template_data) && array_key_exists('body', $this->template_data) && strlen($this->template_data['body']) > 0) + if (is_array($this->template_data) && array_key_exists('body', $this->template_data) && strlen($this->template_data['body']) > 0) { $body_template = $this->template_data['body']; - elseif(strlen($this->client->getSetting('email_template_'.$this->reminder_template)) > 0) + } elseif (strlen($this->client->getSetting('email_template_'.$this->reminder_template)) > 0) { $body_template = $this->client->getSetting('email_template_'.$this->reminder_template); - else{ + } else { $body_template = EmailTemplateDefaults::getDefaultTemplate('email_template_'.$this->reminder_template, $this->client->locale()); } @@ -64,22 +63,19 @@ class InvoiceEmailEngine extends BaseEmailEngine ); } - if(is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0){ + if (is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) { $subject_template = $this->template_data['subject']; info("subject = template data"); - } - elseif(strlen($this->client->getSetting('email_subject_'.$this->reminder_template)) > 0){ + } elseif (strlen($this->client->getSetting('email_subject_'.$this->reminder_template)) > 0) { $subject_template = $this->client->getSetting('email_subject_'.$this->reminder_template); info("subject = settings var"); - } - else{ + } else { info("subject = default template " . 'email_subject_'.$this->reminder_template); $subject_template = EmailTemplateDefaults::getDefaultTemplate('email_subject_'.$this->reminder_template, $this->client->locale()); - // $subject_template = $this->client->getSetting('email_subject_'.$this->reminder_template); + // $subject_template = $this->client->getSetting('email_subject_'.$this->reminder_template); } if (iconv_strlen($subject_template) == 0) { - $subject_template = trans( 'texts.invoice_subject', [ @@ -89,7 +85,6 @@ class InvoiceEmailEngine extends BaseEmailEngine null, $this->client->locale() ); - } $this->setTemplate($this->client->getSetting('email_style')) @@ -106,8 +101,5 @@ class InvoiceEmailEngine extends BaseEmailEngine } return $this; - } - } - diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php index 48724998d6bd..c0662f9f7855 100644 --- a/app/Mail/Engine/PaymentEmailEngine.php +++ b/app/Mail/Engine/PaymentEmailEngine.php @@ -16,13 +16,13 @@ use App\Utils\HtmlEngine; use App\Utils\Number; use App\Utils\Traits\MakesDates; -class PaymentEmailEngine extends BaseEmailEngine +class PaymentEmailEngine extends BaseEmailEngine { use MakesDates; - public $client; + public $client; - public $payment; + public $payment; public $template_data; @@ -44,12 +44,11 @@ class PaymentEmailEngine extends BaseEmailEngine public function build() { - - if(is_array($this->template_data) && array_key_exists('body', $this->template_data) && strlen($this->template_data['body']) > 0) + if (is_array($this->template_data) && array_key_exists('body', $this->template_data) && strlen($this->template_data['body']) > 0) { $body_template = $this->template_data['body']; - elseif(strlen($this->client->getSetting('email_template_payment')) > 0) + } elseif (strlen($this->client->getSetting('email_template_payment')) > 0) { $body_template = $this->client->getSetting('email_template_payment'); - else{ + } else { $body_template = EmailTemplateDefaults::getDefaultTemplate('email_template_payment', $this->client->locale()); } @@ -63,13 +62,11 @@ class PaymentEmailEngine extends BaseEmailEngine ); } - if(is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0){ + if (is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) { $subject_template = $this->template_data['subject']; - } - elseif(strlen($this->client->getSetting('email_subject_payment')) > 0){ + } elseif (strlen($this->client->getSetting('email_subject_payment')) > 0) { $subject_template = $this->client->getSetting('email_subject_payment'); - } - else{ + } else { $subject_template = EmailTemplateDefaults::getDefaultTemplate('email_subject_payment', $this->client->locale()); } @@ -92,7 +89,6 @@ class PaymentEmailEngine extends BaseEmailEngine ->setViewText(''); return $this; - } @@ -115,7 +111,7 @@ class PaymentEmailEngine extends BaseEmailEngine $data['$payment2'] = ['value' => $this->formatCustomFieldValue('payment2', $this->payment->custom_value2) ?: ' ', 'label' => $this->makeCustomField('payment2')]; $data['$payment3'] = ['value' => $this->formatCustomFieldValue('payment3', $this->payment->custom_value3) ?: ' ', 'label' => $this->makeCustomField('payment3')]; $data['$payment4'] = ['value' => $this->formatCustomFieldValue('payment4', $this->payment->custom_value4) ?: ' ', 'label' => $this->makeCustomField('payment4')]; - // $data['$type'] = ['value' => $this->payment->type->name ?: '', 'label' => ctrans('texts.payment_type')]; + // $data['$type'] = ['value' => $this->payment->type->name ?: '', 'label' => ctrans('texts.payment_type')]; $data['$client1'] = ['value' => $this->formatCustomFieldValue('client1', $this->client->custom_value1) ?: ' ', 'label' => $this->makeCustomField('client1')]; $data['$client2'] = ['value' => $this->formatCustomFieldValue('client2', $this->client->custom_value2) ?: ' ', 'label' => $this->makeCustomField('client2')]; @@ -200,8 +196,7 @@ class PaymentEmailEngine extends BaseEmailEngine { $invoice_list = ''; - foreach($this->payment->invoices as $invoice) - { + foreach ($this->payment->invoices as $invoice) { $invoice_list .= ctrans('texts.invoice_number_short') . " {$invoice->number} - " . Number::formatMoney($invoice->pivot->amount, $this->client) . "
"; } @@ -232,8 +227,9 @@ class PaymentEmailEngine extends BaseEmailEngine $custom_field = $custom_fields->{$field}; $custom_field_parts = explode('|', $custom_field); - if(count($custom_field_parts) >= 2) + if (count($custom_field_parts) >= 2) { $custom_field = $custom_field_parts[1]; + } } switch ($custom_field) { @@ -260,4 +256,3 @@ class PaymentEmailEngine extends BaseEmailEngine return $data; } } - diff --git a/app/Mail/Engine/QuoteEmailEngine.php b/app/Mail/Engine/QuoteEmailEngine.php index af74cb93fc4f..eeea79ccc26a 100644 --- a/app/Mail/Engine/QuoteEmailEngine.php +++ b/app/Mail/Engine/QuoteEmailEngine.php @@ -14,23 +14,23 @@ namespace App\Mail\Engine; use App\Utils\HtmlEngine; use App\Utils\Number; -class QuoteEmailEngine extends BaseEmailEngine +class QuoteEmailEngine extends BaseEmailEngine { - public $invitation; + public $invitation; - public $client; + public $client; - public $quote; + public $quote; - public $contact; + public $contact; public $reminder_template; - public $template_data; + public $template_data; public function __construct($invitation, $reminder_template, $template_data) { - $this->invitation = $invitation; + $this->invitation = $invitation; $this->reminder_template = $reminder_template; $this->client = $invitation->contact->client; $this->quote = $invitation->quote; @@ -40,11 +40,11 @@ class QuoteEmailEngine extends BaseEmailEngine public function build() { - - if(is_array($this->template_data) && array_key_exists('body', $this->template_data) && strlen($this->template_data['body']) > 0) + if (is_array($this->template_data) && array_key_exists('body', $this->template_data) && strlen($this->template_data['body']) > 0) { $body_template = $this->template_data['body']; - else + } else { $body_template = $this->client->getSetting('email_template_'.$this->reminder_template); + } /* Use default translations if a custom message has not been set*/ if (iconv_strlen($body_template) == 0) { @@ -60,13 +60,13 @@ class QuoteEmailEngine extends BaseEmailEngine ); } - if(is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) + if (is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) { $subject_template = $this->template_data['subject']; - else + } else { $subject_template = $this->client->getSetting('email_subject_'.$this->reminder_template); + } if (iconv_strlen($subject_template) == 0) { - $subject_template = trans( 'texts.quote_subject', [ @@ -76,7 +76,6 @@ class QuoteEmailEngine extends BaseEmailEngine null, $this->client->locale() ); - } $this->setTemplate($this->client->getSetting('email_style')) @@ -93,8 +92,5 @@ class QuoteEmailEngine extends BaseEmailEngine } return $this; - } - } - diff --git a/app/Mail/TemplateEmail.php b/app/Mail/TemplateEmail.php index 2f180c365c48..c7d2fe20daa9 100644 --- a/app/Mail/TemplateEmail.php +++ b/app/Mail/TemplateEmail.php @@ -47,7 +47,6 @@ class TemplateEmail extends Mailable */ public function build() { - $template_name = 'email.template.'.$this->build_email->getTemplate(); $settings = $this->client->getMergedSettings(); @@ -56,13 +55,15 @@ class TemplateEmail extends Mailable $this->from($this->user->email, $this->user->present()->name()); - if(strlen($settings->reply_to_email) > 1) + if (strlen($settings->reply_to_email) > 1) { $this->replyTo($settings->reply_to_email, $settings->reply_to_email); + } - if(strlen($settings->bcc_email) > 1) + if (strlen($settings->bcc_email) > 1) { $this->bcc($settings->bcc_email, $settings->bcc_email); + } - $this->subject($this->build_email->getSubject()) + $this->subject($this->build_email->getSubject()) ->text('email.template.plain', [ 'body' => $this->build_email->getBody(), 'footer' => $this->build_email->getFooter(), diff --git a/app/Models/Activity.php b/app/Models/Activity.php index 607dc86890fa..258af69fc01c 100644 --- a/app/Models/Activity.php +++ b/app/Models/Activity.php @@ -157,7 +157,7 @@ class Activity extends StaticModel return $this->belongsTo(Company::class); } - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { if (is_numeric($value)) { throw new ModelNotFoundException("Record with value {$value} not found"); diff --git a/app/Models/BaseModel.php b/app/Models/BaseModel.php index 305fcd4ff451..89cd71f2d237 100644 --- a/app/Models/BaseModel.php +++ b/app/Models/BaseModel.php @@ -166,7 +166,7 @@ class BaseModel extends Model * @param null $field * @return Model|null */ - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { if (is_numeric($value)) { throw new ModelNotFoundException("Record with value {$value} not found"); diff --git a/app/Models/Client.php b/app/Models/Client.php index b9aee73742cc..87383c73ee97 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -243,7 +243,6 @@ class Client extends BaseModel implements HasLocalePreference return $date_formats->filter(function ($item) { return $item->id == $this->getSetting('date_format_id'); })->first()->format; - } public function currency() @@ -384,7 +383,7 @@ class Client extends BaseModel implements HasLocalePreference return array_search($model->id, $transformed_ids); }); } else { - $gateways = $this->company->company_gateways; + $gateways = $this->company->company_gateways; } foreach ($gateways as $gateway) { @@ -472,7 +471,6 @@ class Client extends BaseModel implements HasLocalePreference //we need to check for "0" here as we disable a payment gateway for a client with the number "0" if ($company_gateways || $company_gateways == '0') { - $transformed_ids = $this->transformKeys(explode(',', $company_gateways)); $gateways = $this->company ->company_gateways @@ -488,21 +486,13 @@ class Client extends BaseModel implements HasLocalePreference foreach ($gateways as $gateway) { foreach ($gateway->driver($this)->gatewayTypes() as $type) { - - if(isset($gateway->fees_and_limits) && property_exists($gateway->fees_and_limits, $type)) - { - - if($this->validGatewayForAmount($gateway->fees_and_limits->{$type}, $amount)) + if (isset($gateway->fees_and_limits) && property_exists($gateway->fees_and_limits, $type)) { + if ($this->validGatewayForAmount($gateway->fees_and_limits->{$type}, $amount)) { $payment_methods[] = [$gateway->id => $type]; - - } - else - { - + } + } else { $payment_methods[] = [$gateway->id => $type]; - } - } } @@ -527,8 +517,8 @@ class Client extends BaseModel implements HasLocalePreference } } - if(($this->getSetting('use_credits_payment') == 'option' || $this->getSetting('use_credits_payment') == 'always') && $this->service()->getCreditBalance() > 0) { - $payment_urls[] = [ + if (($this->getSetting('use_credits_payment') == 'option' || $this->getSetting('use_credits_payment') == 'always') && $this->service()->getCreditBalance() > 0) { + $payment_urls[] = [ 'label' => ctrans('texts.apply_credit'), 'company_gateway_id' => CompanyGateway::GATEWAY_CREDIT, 'gateway_type_id' => GatewayType::CREDIT, @@ -540,21 +530,21 @@ class Client extends BaseModel implements HasLocalePreference public function validGatewayForAmount($fees_and_limits_for_payment_type, $amount) :bool { - if (isset($fees_and_limits_for_payment_type)) { - $fees_and_limits = $fees_and_limits_for_payment_type; - } else { - return true; - } - - if ((property_exists($fees_and_limits, 'min_limit')) && $fees_and_limits->min_limit !== null && $fees_and_limits->min_limit != -1 && $amount < $fees_and_limits->min_limit) { - return false; - } - - if ((property_exists($fees_and_limits, 'max_limit')) && $fees_and_limits->max_limit !== null && $fees_and_limits->max_limit != -1 && $amount > $fees_and_limits->max_limit) { - return false; - } - + if (isset($fees_and_limits_for_payment_type)) { + $fees_and_limits = $fees_and_limits_for_payment_type; + } else { return true; + } + + if ((property_exists($fees_and_limits, 'min_limit')) && $fees_and_limits->min_limit !== null && $fees_and_limits->min_limit != -1 && $amount < $fees_and_limits->min_limit) { + return false; + } + + if ((property_exists($fees_and_limits, 'max_limit')) && $fees_and_limits->max_limit !== null && $fees_and_limits->max_limit != -1 && $amount > $fees_and_limits->max_limit) { + return false; + } + + return true; } public function preferredLocale() diff --git a/app/Models/ClientContact.php b/app/Models/ClientContact.php index c800db4c8ff6..f14fe6a72dae 100644 --- a/app/Models/ClientContact.php +++ b/app/Models/ClientContact.php @@ -185,7 +185,7 @@ class ClientContact extends Authenticatable implements HasLocalePreference * @param null $field * @return Model|null */ - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { return $this ->withTrashed() @@ -212,11 +212,8 @@ class ClientContact extends Authenticatable implements HasLocalePreference */ public function getLoginLink() { - $domain = isset($this->company->portal_domain) ?: $this->company->domain(); return $domain . 'client/key_login/' . $this->contact_key; - } - } diff --git a/app/Models/ClientGatewayToken.php b/app/Models/ClientGatewayToken.php index d8148e15c2d5..21e34db4fda5 100644 --- a/app/Models/ClientGatewayToken.php +++ b/app/Models/ClientGatewayToken.php @@ -71,7 +71,7 @@ class ClientGatewayToken extends BaseModel * @param null $field * @return Model|null */ - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { return $this ->where('id', $this->decodePrimaryKey($value))->firstOrFail(); diff --git a/app/Models/Company.php b/app/Models/Company.php index e7e333282d61..7c1bcf453bf8 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -416,7 +416,7 @@ class Company extends BaseModel return User::find($c->user_id); } - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { return $this->where('id', $this->decodePrimaryKey($value))->firstOrFail(); } @@ -439,6 +439,4 @@ class Company extends BaseModel { return $this->slack_webhook_url; } - - } diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php index c9a98ef12591..593256a50471 100644 --- a/app/Models/CompanyGateway.php +++ b/app/Models/CompanyGateway.php @@ -241,7 +241,6 @@ class CompanyGateway extends BaseModel } return $this->fees_and_limits->{$gateway_type_id}; - } /** @@ -272,7 +271,6 @@ class CompanyGateway extends BaseModel public function calcGatewayFee($amount, $include_taxes = false, $gateway_type_id = GatewayType::CREDIT_CARD) { - $fees_and_limits = $this->getFeesAndLimits($gateway_type_id); if (! $fees_and_limits) { @@ -288,9 +286,9 @@ class CompanyGateway extends BaseModel if ($fees_and_limits->fee_percent) { if ($fees_and_limits->adjust_fee_percent) { - $fee += round(($amount / (1 - $fees_and_limits->fee_percent / 100) - $amount),2); + $fee += round(($amount / (1 - $fees_and_limits->fee_percent / 100) - $amount), 2); } else { - $fee += round(($amount * $fees_and_limits->fee_percent / 100),2); + $fee += round(($amount * $fees_and_limits->fee_percent / 100), 2); } info("fee after adding fee percent = {$fee}"); } @@ -305,17 +303,17 @@ class CompanyGateway extends BaseModel /**/ if ($include_taxes) { if ($fees_and_limits->fee_tax_rate1) { - $fee += round(($pre_tax_fee * $fees_and_limits->fee_tax_rate1 / 100),2); + $fee += round(($pre_tax_fee * $fees_and_limits->fee_tax_rate1 / 100), 2); info("fee after adding fee tax 1 = {$fee}"); } if ($fees_and_limits->fee_tax_rate2) { - $fee += round(($pre_tax_fee * $fees_and_limits->fee_tax_rate2 / 100),2); + $fee += round(($pre_tax_fee * $fees_and_limits->fee_tax_rate2 / 100), 2); info("fee after adding fee tax 2 = {$fee}"); } if ($fees_and_limits->fee_tax_rate3) { - $fee += round(($pre_tax_fee * $fees_and_limits->fee_tax_rate3 / 100),2); + $fee += round(($pre_tax_fee * $fees_and_limits->fee_tax_rate3 / 100), 2); info("fee after adding fee tax 3 = {$fee}"); } } @@ -359,7 +357,7 @@ class CompanyGateway extends BaseModel // $fee_component_tax_rate3 = $fees_and_limits->fee_tax_rate3 ? ($combined_fee_component * $fees_and_limits->fee_tax_rate3 / 100) : 0; // } - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { return $this ->where('id', $this->decodePrimaryKey($value))->firstOrFail(); diff --git a/app/Models/CompanyToken.php b/app/Models/CompanyToken.php index d202645047bb..ed9cd2581c82 100644 --- a/app/Models/CompanyToken.php +++ b/app/Models/CompanyToken.php @@ -51,7 +51,6 @@ class CompanyToken extends BaseModel public function company_user() { - return $this->hasOne(CompanyUser::class, 'user_id', 'user_id') ->where('company_id', $this->company_id) ->where('user_id', $this->user_id); diff --git a/app/Models/CompanyUser.php b/app/Models/CompanyUser.php index 90386e136258..fd0c799adc70 100644 --- a/app/Models/CompanyUser.php +++ b/app/Models/CompanyUser.php @@ -16,7 +16,6 @@ use Illuminate\Database\Eloquent\SoftDeletes; class CompanyUser extends Pivot { - use SoftDeletes; // protected $guarded = ['id']; diff --git a/app/Models/Gateway.php b/app/Models/Gateway.php index 5a2ef08f1a30..f2257b3ac5bb 100644 --- a/app/Models/Gateway.php +++ b/app/Models/Gateway.php @@ -66,7 +66,7 @@ class Gateway extends StaticModel $link = 'https://applications.sagepay.com/apply/2C02C252-0F8A-1B84-E10D-CF933EFCAA99'; } elseif ($this->id == 20) { $link = 'https://dashboard.stripe.com/account/apikeys'; - } + } // $key = 'texts.gateway_help_'.$this->id; // $str = trans($key, [ @@ -82,8 +82,8 @@ class Gateway extends StaticModel /** * Returns an array of methods and the gatewaytypes possible - * - * @return array + * + * @return array *///todo remove methods replace with gatewaytype:: and then nest refund / token billing public function getMethods() { @@ -97,7 +97,7 @@ class Gateway extends StaticModel case 20: return [GatewayType::CREDIT_CARD => ['refund' => true, 'token_billing' => true], GatewayType::BANK_TRANSFER => ['refund' => true, 'token_billing' => true], - GatewayType::ALIPAY => ['refund' => false, 'token_billing' => false], + GatewayType::ALIPAY => ['refund' => false, 'token_billing' => false], GatewayType::APPLE_PAY => ['refund' => false, 'token_billing' => false]]; //Stripe break; case 39: diff --git a/app/Models/GroupSetting.php b/app/Models/GroupSetting.php index f87dbb5c2979..17aec3965105 100644 --- a/app/Models/GroupSetting.php +++ b/app/Models/GroupSetting.php @@ -64,7 +64,7 @@ class GroupSetting extends StaticModel * @param null $field * @return Model|null */ - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { return $this ->where('id', $this->decodePrimaryKey($value))->firstOrFail(); diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 33b5760b1a59..0b1f58b09920 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -207,7 +207,7 @@ class Payment extends BaseModel return new PaymentService($this); } - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { return $this ->withTrashed() @@ -293,5 +293,4 @@ class Payment extends BaseModel { return route('client.payments.show', $this->hashed_id); } - } diff --git a/app/Models/Project.php b/app/Models/Project.php index 4ca4eeade66c..55dc2c23a307 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -12,7 +12,6 @@ use Laracasts\Presenter\PresentableTrait; */ class Project extends BaseModel { - use SoftDeletes; use PresentableTrait; use Filterable; diff --git a/app/Models/RecurringInvoice.php b/app/Models/RecurringInvoice.php index 078202fbcfbb..8a89de7beb6e 100644 --- a/app/Models/RecurringInvoice.php +++ b/app/Models/RecurringInvoice.php @@ -181,15 +181,16 @@ class RecurringInvoice extends BaseModel public function getStatusAttribute() { - if ($this->status_id == self::STATUS_ACTIVE && Carbon::parse($this->next_send_date)->isFuture()) + if ($this->status_id == self::STATUS_ACTIVE && Carbon::parse($this->next_send_date)->isFuture()) { return self::STATUS_PENDING; - else + } else { return $this->status_id; + } } public function nextSendDate() :?Carbon { - if(!$this->next_send_date){ + if (!$this->next_send_date) { return null; // $this->next_send_date = now()->format('Y-m-d'); } @@ -224,7 +225,6 @@ class RecurringInvoice extends BaseModel public function nextDateByFrequency($date) { - switch ($this->frequency_id) { case self::FREQUENCY_WEEKLY: return Carbon::parse($date)->addWeek(); @@ -251,18 +251,15 @@ class RecurringInvoice extends BaseModel default: return null; } - } public function remainingCycles() : int { if ($this->remaining_cycles == 0) { return 0; - } - else if($this->remaining_cycles == -1) { + } elseif ($this->remaining_cycles == -1) { return -1; - } - else { + } else { return $this->remaining_cycles - 1; } } @@ -351,34 +348,33 @@ class RecurringInvoice extends BaseModel return $invoice_calc->build(); } - /* - * Important to note when playing with carbon dates - in order + /* + * Important to note when playing with carbon dates - in order * not to modify the original instance, always use a `->copy()` - * + * */ public function recurringDates() { - /* Return early if nothing to send back! */ - if( $this->status_id == self::STATUS_COMPLETED || + /* Return early if nothing to send back! */ + if ($this->status_id == self::STATUS_COMPLETED || $this->remaining_cycles == 0 || !$this->next_send_date) { - return []; } /* Endless - lets send 10 back*/ $iterations = $this->remaining_cycles; - if($this->remaining_cycles == -1) + if ($this->remaining_cycles == -1) { $iterations = 10; + } $next_send_date = Carbon::parse($this->next_send_date)->copy(); $data = []; - for($x=0; $x<$iterations; $x++) - { + for ($x=0; $x<$iterations; $x++) { // we don't add the days... we calc the day of the month!! $next_due_date = $this->calculateDueDate($next_send_date->copy()->format('Y-m-d')); $next_due_date_string = $next_due_date ? $next_due_date->format('Y-m-d') : ''; @@ -386,12 +382,11 @@ class RecurringInvoice extends BaseModel $next_send_date = Carbon::parse($next_send_date); $data[] = [ - 'send_date' => $next_send_date->format('Y-m-d'), + 'send_date' => $next_send_date->format('Y-m-d'), 'due_date' => $next_due_date_string ]; - $next_send_date = $this->nextDateByFrequency($next_send_date->format('Y-m-d')); - + $next_send_date = $this->nextDateByFrequency($next_send_date->format('Y-m-d')); } /*If no due date is set - unset the due_date value */ @@ -403,13 +398,11 @@ class RecurringInvoice extends BaseModel // } return $data; - } - public function calculateDueDate($date) + public function calculateDueDate($date) { - switch ($this->due_date_days) { case 'terms': return $this->calculateDateFromTerms($date); @@ -422,18 +415,19 @@ class RecurringInvoice extends BaseModel /** * Calculates a date based on the client payment terms. - * + * * @param Carbon $date A given date * @return NULL|Carbon The date */ - public function calculateDateFromTerms($date) + public function calculateDateFromTerms($date) { $new_date = Carbon::parse($date); $client_payment_terms = $this->client->getSetting('payment_terms'); - if($client_payment_terms == '')//no due date! return null; + if ($client_payment_terms == '') {//no due date! return null; return null; + } return $new_date->addDays($client_payment_terms); //add the number of days in the payment terms to the date } @@ -445,5 +439,4 @@ class RecurringInvoice extends BaseModel { return new RecurringService($this); } - } diff --git a/app/Models/RecurringInvoiceInvitation.php b/app/Models/RecurringInvoiceInvitation.php index bd24c7c535a7..0fb626e3e68b 100644 --- a/app/Models/RecurringInvoiceInvitation.php +++ b/app/Models/RecurringInvoiceInvitation.php @@ -86,5 +86,4 @@ class RecurringInvoiceInvitation extends BaseModel $this->opened_date = now(); $this->save(); } - } diff --git a/app/Models/SystemLog.php b/app/Models/SystemLog.php index 54da10e23ad1..7c138620a069 100644 --- a/app/Models/SystemLog.php +++ b/app/Models/SystemLog.php @@ -67,7 +67,7 @@ class SystemLog extends Model 'type_id', ]; - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { if (is_numeric($value)) { throw new ModelNotFoundException("Record with value {$value} not found"); @@ -86,4 +86,4 @@ class SystemLog extends Model return $query; } -} \ No newline at end of file +} diff --git a/app/Models/Task.php b/app/Models/Task.php index 47412d915618..1cf6bcbf242e 100644 --- a/app/Models/Task.php +++ b/app/Models/Task.php @@ -115,7 +115,6 @@ class Task extends BaseModel } else { return ''; } - } public function calcDuration($start_time_cutoff = 0, $end_time_cutoff = 0) @@ -143,9 +142,4 @@ class Task extends BaseModel return round($duration); } - - - - - } diff --git a/app/Models/TaskStatus.php b/app/Models/TaskStatus.php index c90ab601978a..e9a134a8b297 100644 --- a/app/Models/TaskStatus.php +++ b/app/Models/TaskStatus.php @@ -30,5 +30,4 @@ class TaskStatus extends BaseModel protected $dates = ['deleted_at']; protected $fillable = ['name']; - } diff --git a/app/Models/User.php b/app/Models/User.php index 00653a53b18f..2d2f7461feb9 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -164,12 +164,11 @@ class User extends Authenticatable implements MustVerifyEmail */ public function getCompany() { - if ($this->company) { return $this->company; } - if(request()->header('X-API-TOKEN')){ + if (request()->header('X-API-TOKEN')) { $company_token = CompanyToken::whereRaw('BINARY `token`= ?', [request()->header('X-API-TOKEN')])->first(); return $company_token->company; } @@ -205,13 +204,11 @@ class User extends Authenticatable implements MustVerifyEmail $this->id = auth()->user()->id; } - if(request()->header('X-API-TOKEN')){ + if (request()->header('X-API-TOKEN')) { return $this->hasOneThrough(CompanyUser::class, CompanyToken::class, 'user_id', 'company_id', 'id', 'company_id') ->where('company_tokens.token', request()->header('X-API-TOKEN')) ->withTrashed(); - } - else { - + } else { return $this->hasOneThrough(CompanyUser::class, CompanyToken::class, 'user_id', 'company_id', 'id', 'company_id') ->where('company_user.user_id', $this->id) ->withTrashed(); @@ -354,7 +351,7 @@ class User extends Authenticatable implements MustVerifyEmail * @param null $field * @return Model|null */ - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { return $this ->withTrashed() diff --git a/app/Models/VendorContact.php b/app/Models/VendorContact.php index acbff497cf43..31e2dd489fb1 100644 --- a/app/Models/VendorContact.php +++ b/app/Models/VendorContact.php @@ -137,7 +137,7 @@ class VendorContact extends Authenticatable implements HasLocalePreference * @param null $field * @return Model|null */ - public function resolveRouteBinding($value, $field = NULL) + public function resolveRouteBinding($value, $field = null) { return $this ->withTrashed() diff --git a/app/Observers/ClientObserver.php b/app/Observers/ClientObserver.php index e6336c5eb2c3..5d0604174e90 100644 --- a/app/Observers/ClientObserver.php +++ b/app/Observers/ClientObserver.php @@ -29,8 +29,9 @@ class ClientObserver ->where('event_id', Webhook::EVENT_CREATE_CLIENT) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_CLIENT, $client, $client->company); + } } /** @@ -45,8 +46,9 @@ class ClientObserver ->where('event_id', Webhook::EVENT_UPDATE_CLIENT) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_UPDATE_CLIENT, $client, $client->company); + } } /** @@ -61,8 +63,9 @@ class ClientObserver ->where('event_id', Webhook::EVENT_DELETE_CLIENT) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_DELETE_CLIENT, $client, $client->company); + } } /** diff --git a/app/Observers/ExpenseObserver.php b/app/Observers/ExpenseObserver.php index e67abbd9e620..9df1ea328731 100644 --- a/app/Observers/ExpenseObserver.php +++ b/app/Observers/ExpenseObserver.php @@ -29,8 +29,9 @@ class ExpenseObserver ->where('event_id', Webhook::EVENT_CREATE_EXPENSE) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_EXPENSE, $expense, $expense->company); + } } /** @@ -45,8 +46,9 @@ class ExpenseObserver ->where('event_id', Webhook::EVENT_UPDATE_EXPENSE) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_UPDATE_EXPENSE, $expense, $expense->company); + } } /** @@ -61,8 +63,9 @@ class ExpenseObserver ->where('event_id', Webhook::EVENT_DELETE_EXPENSE) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_DELETE_EXPENSE, $expense, $expense->company); + } } /** diff --git a/app/Observers/InvoiceObserver.php b/app/Observers/InvoiceObserver.php index 224456d68477..28c1b43b2cd5 100644 --- a/app/Observers/InvoiceObserver.php +++ b/app/Observers/InvoiceObserver.php @@ -26,13 +26,13 @@ class InvoiceObserver */ public function created(Invoice $invoice) { - $subscriptions = Webhook::where('company_id', $invoice->company->id) ->where('event_id', Webhook::EVENT_CREATE_INVOICE) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_INVOICE, $invoice, $invoice->company); + } } /** @@ -47,8 +47,9 @@ class InvoiceObserver ->where('event_id', Webhook::EVENT_UPDATE_INVOICE) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_UPDATE_INVOICE, $invoice, $invoice->company); + } } /** @@ -63,8 +64,9 @@ class InvoiceObserver ->where('event_id', Webhook::EVENT_DELETE_INVOICE) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_DELETE_INVOICE, $invoice, $invoice->company); + } } /** diff --git a/app/Observers/PaymentObserver.php b/app/Observers/PaymentObserver.php index 5eaa05de5a91..926da623a19c 100644 --- a/app/Observers/PaymentObserver.php +++ b/app/Observers/PaymentObserver.php @@ -26,13 +26,13 @@ class PaymentObserver */ public function created(Payment $payment) { - $subscriptions = Webhook::where('company_id', $payment->company->id) ->where('event_id', Webhook::EVENT_CREATE_PAYMENT) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_PAYMENT, $payment, $payment->company); + } } /** @@ -57,8 +57,9 @@ class PaymentObserver ->where('event_id', Webhook::EVENT_DELETE_PAYMENT) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_DELETE_PAYMENT, $payment, $payment->company); + } } /** diff --git a/app/Observers/QuoteObserver.php b/app/Observers/QuoteObserver.php index 600382a0d8d8..e9cdfffd1fae 100644 --- a/app/Observers/QuoteObserver.php +++ b/app/Observers/QuoteObserver.php @@ -29,8 +29,9 @@ class QuoteObserver ->where('event_id', Webhook::EVENT_CREATE_QUOTE) ->exists(); - if($subscriptions) - WebhookHandler::dispatch(Webhook::EVENT_CREATE_QUOTE, $quote, $quote->company); + if ($subscriptions) { + WebhookHandler::dispatch(Webhook::EVENT_CREATE_QUOTE, $quote, $quote->company); + } } /** @@ -45,8 +46,9 @@ class QuoteObserver ->where('event_id', Webhook::EVENT_UPDATE_QUOTE) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_UPDATE_QUOTE, $quote, $quote->company); + } } /** @@ -61,8 +63,9 @@ class QuoteObserver ->where('event_id', Webhook::EVENT_DELETE_QUOTE) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_DELETE_QUOTE, $quote, $quote->company); + } } /** diff --git a/app/Observers/TaskObserver.php b/app/Observers/TaskObserver.php index e31371276c7c..03abb7c3a9d2 100644 --- a/app/Observers/TaskObserver.php +++ b/app/Observers/TaskObserver.php @@ -25,13 +25,13 @@ class TaskObserver */ public function created(Task $task) { - $subscriptions = Webhook::where('company_id', $task->company->id) ->where('event_id', Webhook::EVENT_CREATE_TASK) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_TASK, $task, $task->company); + } } /** @@ -42,13 +42,13 @@ class TaskObserver */ public function updated(Task $task) { - $subscriptions = Webhook::where('company_id', $task->company->id) ->where('event_id', Webhook::EVENT_UPDATE_TASK) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_UPDATE_TASK, $task, $task->company); + } } /** @@ -59,14 +59,13 @@ class TaskObserver */ public function deleted(Task $task) { - - $subscriptions = Webhook::where('company_id', $task->company->id) ->where('event_id', Webhook::EVENT_DELETE_TASK) ->exists(); - if($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_DELETE_TASK, $task, $task->company); + } } /** diff --git a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php index 38ad15a89400..4324369b0a8e 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php +++ b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php @@ -136,8 +136,7 @@ class AuthorizeCreditCard $response = $data['response']; if ($response != null && $response->getMessages()->getResultCode() == 'Ok') { - - $this->authorize->confirmGatewayFee($request); + $this->authorize->confirmGatewayFee($request); return $this->processSuccessfulResponse($data, $request); } diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index f11aaf2bc3cf..964001db2edb 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -239,13 +239,11 @@ class BaseDriver extends AbstractPaymentDriver */ public function unWindGatewayFees(PaymentHash $payment_hash) { - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->get(); $invoices->each(function ($invoice) { $invoice->service()->removeUnpaidGatewayFees(); }); - } /** diff --git a/app/PaymentDrivers/StripePaymentDriver.php b/app/PaymentDrivers/StripePaymentDriver.php index 764fc91c2e7d..0eefea5b4c4f 100644 --- a/app/PaymentDrivers/StripePaymentDriver.php +++ b/app/PaymentDrivers/StripePaymentDriver.php @@ -383,20 +383,19 @@ class StripePaymentDriver extends BaseDriver } /** - * Attach Stripe payment method to Stripe client. - * - * @param string $payment_method - * @param mixed $customer - * - * @return void + * Attach Stripe payment method to Stripe client. + * + * @param string $payment_method + * @param mixed $customer + * + * @return void */ public function attach(string $payment_method, $customer): void { try { $stripe_payment_method = $this->getStripePaymentMethod($payment_method); $stripe_payment_method->attach(['customer' => $customer->id]); - } - catch(\Stripe\Exception\ApiErrorException | \Exception $e) { + } catch (\Stripe\Exception\ApiErrorException | \Exception $e) { $this->processInternallyFailedPayment($this, $e); } } @@ -430,10 +429,10 @@ class StripePaymentDriver extends BaseDriver /** * Retrieve payment method from Stripe. - * - * @param string $source * - * @return \Stripe\PaymentMethod|void + * @param string $source + * + * @return \Stripe\PaymentMethod|void */ public function getStripePaymentMethod(string $source) { diff --git a/app/Repositories/ActivityRepository.php b/app/Repositories/ActivityRepository.php index 0e52ea0cbb33..0277f89e2cfe 100644 --- a/app/Repositories/ActivityRepository.php +++ b/app/Repositories/ActivityRepository.php @@ -73,8 +73,9 @@ class ActivityRepository extends BaseRepository */ public function createBackup($entity, $activity) { - if($entity->company->is_disabled) + if ($entity->company->is_disabled) { return; + } $backup = new Backup(); @@ -107,13 +108,11 @@ class ActivityRepository extends BaseRepository { $entity_design_id = ''; - if($entity instanceof Invoice || $entity instanceof RecurringInvoice){ + if ($entity instanceof Invoice || $entity instanceof RecurringInvoice) { $entity_design_id = 'invoice_design_id'; - } - elseif($entity instanceof Quote){ + } elseif ($entity instanceof Quote) { $entity_design_id = 'quote_design_id'; - } - elseif($entity instanceof Credit){ + } elseif ($entity instanceof Credit) { $entity_design_id = 'credit_design_id'; } @@ -123,12 +122,12 @@ class ActivityRepository extends BaseRepository $html = new HtmlEngine($entity->invitations->first()); if ($design->is_custom) { - $options = [ + $options = [ 'custom_partials' => json_decode(json_encode($design->design), true) ]; - $template = new PdfMakerDesign(PdfDesignModel::CUSTOM, $options); + $template = new PdfMakerDesign(PdfDesignModel::CUSTOM, $options); } else { - $template = new PdfMakerDesign(strtolower($design->name)); + $template = new PdfMakerDesign(strtolower($design->name)); } $state = [ @@ -150,7 +149,5 @@ class ActivityRepository extends BaseRepository return $maker->design($template) ->build() ->getCompiledHTML(true); - } - } diff --git a/app/Repositories/BaseRepository.php b/app/Repositories/BaseRepository.php index 1f95fbfe4914..6c230a38bf2e 100644 --- a/app/Repositories/BaseRepository.php +++ b/app/Repositories/BaseRepository.php @@ -158,7 +158,6 @@ class BaseRepository */ protected function alternativeSave($data, $model) { - $class = new ReflectionClass($model); if (array_key_exists('client_id', $data)) { @@ -233,9 +232,7 @@ class BaseRepository //make sure we are creating an invite for a contact who belongs to the client only! $contact = ClientContact::find($invitation['client_contact_id']); - if ($contact && $model->client_id == $contact->client_id) - { - + if ($contact && $model->client_id == $contact->client_id) { $invitation_class = sprintf('App\\Models\\%sInvitation', $resource); $new_invitation = $invitation_class::withTrashed() @@ -251,7 +248,6 @@ class BaseRepository $new_invitation->client_contact_id = $contact->id; $new_invitation->save(); } - } } } @@ -286,11 +282,9 @@ class BaseRepository //links tasks and expenses back to the invoice. $model->service()->linkEntities()->save(); - } if ($class->name == Credit::class) { - $model = $model->calc()->getCredit(); $model->ledger()->updateCreditBalance(($state['finished_amount'] - $state['starting_amount'])); diff --git a/app/Repositories/ClientContactRepository.php b/app/Repositories/ClientContactRepository.php index fe14030a5b19..873be6d30e2c 100644 --- a/app/Repositories/ClientContactRepository.php +++ b/app/Repositories/ClientContactRepository.php @@ -61,9 +61,7 @@ class ClientContactRepository extends BaseRepository $update_contact->fill($contact); if (array_key_exists('password', $contact) && strlen($contact['password']) > 1) { - $update_contact->password = Hash::make($contact['password']); - } $update_contact->save(); diff --git a/app/Repositories/ClientRepository.php b/app/Repositories/ClientRepository.php index d133ff887d1f..a56c68e45d4f 100644 --- a/app/Repositories/ClientRepository.php +++ b/app/Repositories/ClientRepository.php @@ -62,11 +62,13 @@ class ClientRepository extends BaseRepository $client->fill($data); - if (!isset($client->id_number)) + if (!isset($client->id_number)) { $client->id_number = $this->getNextClientNumber($client); + } - if (empty($data['name'])) + if (empty($data['name'])) { $data['name'] = $client->present()->name(); + } $client->save(); diff --git a/app/Repositories/DesignRepository.php b/app/Repositories/DesignRepository.php index 97a53dd8734e..ec3e4f7986c6 100644 --- a/app/Repositories/DesignRepository.php +++ b/app/Repositories/DesignRepository.php @@ -16,5 +16,4 @@ namespace App\Repositories; */ class DesignRepository extends BaseRepository { - } diff --git a/app/Repositories/DocumentRepository.php b/app/Repositories/DocumentRepository.php index b9521dc954cd..49736b80fa8f 100644 --- a/app/Repositories/DocumentRepository.php +++ b/app/Repositories/DocumentRepository.php @@ -19,7 +19,6 @@ use App\Utils\Ninja; */ class DocumentRepository extends BaseRepository { - public function delete($document) { $document->deleteFile(); diff --git a/app/Repositories/GroupSettingRepository.php b/app/Repositories/GroupSettingRepository.php index d1aac1dda4d9..c71298360397 100644 --- a/app/Repositories/GroupSettingRepository.php +++ b/app/Repositories/GroupSettingRepository.php @@ -15,7 +15,6 @@ use App\Models\GroupSetting; class GroupSettingRepository extends BaseRepository { - public function save($data, GroupSetting $group_setting) :?GroupSetting { $group_setting->fill($data); diff --git a/app/Repositories/Migration/InvoiceMigrationRepository.php b/app/Repositories/Migration/InvoiceMigrationRepository.php index bb8254e24962..e75c39c8d50e 100644 --- a/app/Repositories/Migration/InvoiceMigrationRepository.php +++ b/app/Repositories/Migration/InvoiceMigrationRepository.php @@ -100,7 +100,7 @@ class InvoiceMigrationRepository extends BaseRepository $invitations = collect($data['invitations']); /* Get array of Keys which have been removed from the invitations array and soft delete each invitation */ - $model->invitations->pluck('key')->diff($invitations->pluck('key'))->each(function ($invitation) use($resource){ + $model->invitations->pluck('key')->diff($invitations->pluck('key'))->each(function ($invitation) use ($resource) { $this->getInvitation($invitation, $resource)->delete(); }); diff --git a/app/Repositories/Migration/PaymentMigrationRepository.php b/app/Repositories/Migration/PaymentMigrationRepository.php index d4144ac42168..732be99a0e95 100644 --- a/app/Repositories/Migration/PaymentMigrationRepository.php +++ b/app/Repositories/Migration/PaymentMigrationRepository.php @@ -89,13 +89,13 @@ class PaymentMigrationRepository extends BaseRepository $payment->fill($data); //$payment->status_id = Payment::STATUS_COMPLETED; - if(!array_key_exists('status_id', $data)){ + if (!array_key_exists('status_id', $data)) { info("payment with no status id?"); - info(print_r($data,1)); + info(print_r($data, 1)); } $payment->status_id = $data['status_id']; - $payment->deleted_at = $data['deleted_at'] ?: NULL; + $payment->deleted_at = $data['deleted_at'] ?: null; $payment->save(); /*Ensure payment number generated*/ diff --git a/app/Repositories/PaymentRepository.php b/app/Repositories/PaymentRepository.php index bdf05cfc6745..13967b8897d5 100644 --- a/app/Repositories/PaymentRepository.php +++ b/app/Repositories/PaymentRepository.php @@ -82,20 +82,17 @@ class PaymentRepository extends BaseRepository } $client->service()->updatePaidToDate($data['amount'])->save(); - } if (array_key_exists('credits', $data) && is_array($data['credits']) && count($data['credits']) > 0) { - $_credit_totals = array_sum(array_column($data['credits'], 'amount')); - if($data['amount'] == $_credit_totals) + if ($data['amount'] == $_credit_totals) { $data['amount'] = 0; - else + } else { $client->service()->updatePaidToDate($_credit_totals)->save(); - + } } - } /*Fill the payment*/ @@ -155,10 +152,11 @@ class PaymentRepository extends BaseRepository } } - if(!$is_existing_payment) + if (!$is_existing_payment) { event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); + } - $payment->applied += ($invoice_totals - $credit_totals); //wont work because - check tests + $payment->applied += ($invoice_totals - $credit_totals); //wont work because - check tests // $payment->applied += $invoice_totals; //wont work because - check tests $payment->save(); diff --git a/app/Repositories/ProjectRepository.php b/app/Repositories/ProjectRepository.php index 136ecadf9e55..1dd26a7792dd 100644 --- a/app/Repositories/ProjectRepository.php +++ b/app/Repositories/ProjectRepository.php @@ -18,5 +18,4 @@ use App\Models\Project; */ class ProjectRepository extends BaseRepository { - } diff --git a/app/Repositories/QuoteRepository.php b/app/Repositories/QuoteRepository.php index 33aa4e34e554..8708a10b5bef 100644 --- a/app/Repositories/QuoteRepository.php +++ b/app/Repositories/QuoteRepository.php @@ -27,8 +27,6 @@ use Illuminate\Http\Request; */ class QuoteRepository extends BaseRepository { - - public function save($data, Quote $quote) : ?Quote { return $this->alternativeSave($data, $quote); diff --git a/app/Repositories/RecurringInvoiceRepository.php b/app/Repositories/RecurringInvoiceRepository.php index 9658caaaa533..f962cd8e8712 100644 --- a/app/Repositories/RecurringInvoiceRepository.php +++ b/app/Repositories/RecurringInvoiceRepository.php @@ -20,7 +20,6 @@ use Illuminate\Http\Request; */ class RecurringInvoiceRepository extends BaseRepository { - public function save($data, RecurringInvoice $invoice) : ?RecurringInvoice { $invoice->fill($data); diff --git a/app/Repositories/RecurringQuoteRepository.php b/app/Repositories/RecurringQuoteRepository.php index a0894e8f3a9d..d4059b9a7710 100644 --- a/app/Repositories/RecurringQuoteRepository.php +++ b/app/Repositories/RecurringQuoteRepository.php @@ -20,8 +20,6 @@ use Illuminate\Http\Request; */ class RecurringQuoteRepository extends BaseRepository { - - public function save(Request $request, RecurringQuote $quote) : ?RecurringQuote { $quote->fill($request->input()); diff --git a/app/Repositories/TaskRepository.php b/app/Repositories/TaskRepository.php index 75f0e7817570..db0e6cc97a73 100644 --- a/app/Repositories/TaskRepository.php +++ b/app/Repositories/TaskRepository.php @@ -34,7 +34,6 @@ class TaskRepository extends BaseRepository */ public function save(array $data, Task $task) : ?Task { - $task->fill($data); $task->save(); @@ -68,7 +67,7 @@ class TaskRepository extends BaseRepository } elseif ($data['action'] == 'stop' && $task->is_running) { $time_log[count($time_log) - 1][1] = time(); $task->is_running = false; - } elseif ($data['action'] == 'offline'){ + } elseif ($data['action'] == 'offline') { $task->is_running = $data['is_running'] ? 1 : 0; } } elseif (isset($data['is_running'])) { diff --git a/app/Repositories/UserRepository.php b/app/Repositories/UserRepository.php index 6a55bd1aa5a6..4f25ab6b06a4 100644 --- a/app/Repositories/UserRepository.php +++ b/app/Repositories/UserRepository.php @@ -62,8 +62,9 @@ class UserRepository extends BaseRepository $user->fill($details); - if(!$user->confirmation_code) + if (!$user->confirmation_code) { $user->confirmation_code = $this->createDbHash(config('database.default')); + } $user->account_id = $account->id; $user->save(); @@ -95,7 +96,6 @@ class UserRepository extends BaseRepository public function destroy(array $data, User $user) { - if (array_key_exists('company_user', $data)) { $this->forced_includes = 'company_users'; @@ -121,7 +121,6 @@ class UserRepository extends BaseRepository */ public function delete($user) { - $company = auth()->user()->company(); $cu = CompanyUser::whereUserId($user->id) diff --git a/app/Repositories/VendorContactRepository.php b/app/Repositories/VendorContactRepository.php index 3700c59e6034..4432be9dfb0a 100644 --- a/app/Repositories/VendorContactRepository.php +++ b/app/Repositories/VendorContactRepository.php @@ -25,7 +25,6 @@ class VendorContactRepository extends BaseRepository public function save(array $data, Vendor $vendor) : void { - if (isset($data['contacts'])) { $contacts = collect($data['contacts']); } else { diff --git a/app/Repositories/VendorRepository.php b/app/Repositories/VendorRepository.php index 9b15eb5a3f5f..39a7576a2891 100644 --- a/app/Repositories/VendorRepository.php +++ b/app/Repositories/VendorRepository.php @@ -45,7 +45,6 @@ class VendorRepository extends BaseRepository */ public function save(array $data, Vendor $vendor) : ?Vendor { - $vendor->fill($data); $vendor->save(); diff --git a/app/Services/Client/ClientService.php b/app/Services/Client/ClientService.php index 9632db976cf1..0a3ddd03cab9 100644 --- a/app/Services/Client/ClientService.php +++ b/app/Services/Client/ClientService.php @@ -47,7 +47,6 @@ class ClientService public function getCreditBalance() :float { - $credits = $this->client->credits ->where('is_deleted', false) ->where('balance', '>', 0) @@ -58,12 +57,10 @@ class ClientService public function getCredits() :Collection { - return $this->client->credits ->where('is_deleted', false) ->where('balance', '>', 0) ->sortBy('created_at'); - } diff --git a/app/Services/Credit/ApplyPayment.php b/app/Services/Credit/ApplyPayment.php index 009aeb4d94b1..351c969f3134 100644 --- a/app/Services/Credit/ApplyPayment.php +++ b/app/Services/Credit/ApplyPayment.php @@ -21,7 +21,6 @@ use App\Utils\Ninja; class ApplyPayment { - private $credit; private $invoice; @@ -50,8 +49,7 @@ class ApplyPayment $credit_balance = $this->credit->balance; /* Check invoice partial for amount to be cleared first */ - if($this->invoice->partial > 0){ - + if ($this->invoice->partial > 0) { $partial_payment = min($this->invoice->partial, $applicable_amount); $this->invoice->partial -= $partial_payment; @@ -60,38 +58,34 @@ class ApplyPayment $credit_balance -= $partial_payment; $applicable_amount -= $partial_payment; $this->amount_applied += $partial_payment; - } /* If there is remaining amount use it on the balance */ - if($this->amount > 0 && $applicable_amount > 0 && $invoice_balance > 0){ - + if ($this->amount > 0 && $applicable_amount > 0 && $invoice_balance > 0) { $balance_payment = min($invoice_balance, min($this->amount, $credit_balance)); $invoice_balance -= $balance_payment; $this->amount -= $balance_payment; $this->amount_applied += $balance_payment; - } $this->credit->balance -= $this->amount_applied; - if((int)$this->credit->balance == 0) + if ((int)$this->credit->balance == 0) { $this->credit->status_id = Credit::STATUS_APPLIED; - else + } else { $this->credit->status_id = Credit::STATUS_PARTIAL; + } $this->credit->save(); $this->addPaymentToLedger(); return $this->credit; - } private function applyPaymentToCredit() { - $credit_item = new InvoiceItem; $credit_item->type_id = '1'; $credit_item->product_key = ctrans('texts.credit'); @@ -106,12 +100,10 @@ class ApplyPayment $this->credit = $this->credit->calc()->getCredit(); $this->credit->save(); - } private function addPaymentToLedger() { - $this->payment->amount += $this->amount_applied; $this->payment->applied += $this->amount_applied; $this->payment->status_id = Payment::STATUS_COMPLETED; @@ -126,11 +118,11 @@ class ApplyPayment ->credits() ->attach($this->credit->id, ['amount' => $this->amount_applied]); - $this->payment + $this->payment ->ledger() ->updatePaymentBalance($this->amount_applied * -1); - $this->payment + $this->payment ->client ->service() ->updateBalance($this->amount_applied * -1) @@ -138,22 +130,21 @@ class ApplyPayment ->updatePaidToDate($this->amount_applied) ->save(); - $this->invoice - ->service() + $this->invoice + ->service() ->updateBalance($this->amount_applied * -1) ->updateStatus() ->save(); - $this->credit + $this->credit ->ledger() ->updateCreditBalance(($this->amount_applied * -1), "Credit payment applied to Invoice {$this->invoice->number}"); - event(new InvoiceWasUpdated($this->invoice, $this->invoice->company, Ninja::eventVars())); - - if((int)$this->invoice->balance == 0){ - $this->invoice->service()->deletePdf(); - event(new InvoiceWasPaid($this->invoice, $this->payment->company, Ninja::eventVars())); - } + event(new InvoiceWasUpdated($this->invoice, $this->invoice->company, Ninja::eventVars())); + if ((int)$this->invoice->balance == 0) { + $this->invoice->service()->deletePdf(); + event(new InvoiceWasPaid($this->invoice, $this->payment->company, Ninja::eventVars())); + } } } diff --git a/app/Services/Credit/CreditService.php b/app/Services/Credit/CreditService.php index cb2077378569..ce17900b4314 100644 --- a/app/Services/Credit/CreditService.php +++ b/app/Services/Credit/CreditService.php @@ -69,13 +69,13 @@ class CreditService public function setCalculatedStatus() { - - if((int)$this->credit->balance == 0) + if ((int)$this->credit->balance == 0) { $this->credit->status_id = Credit::STATUS_APPLIED; - elseif((string)$this->credit->amount == (string)$this->credit->balance) + } elseif ((string)$this->credit->amount == (string)$this->credit->balance) { $this->credit->status_id = Credit::STATUS_SENT; - elseif($this->credit->balance > 0) + } elseif ($this->credit->balance > 0) { $this->credit->status_id = Credit::STATUS_PARTIAL; + } return $this; } @@ -106,17 +106,20 @@ class CreditService { $settings = $this->credit->client->getMergedSettings(); - if(! $this->credit->design_id) + if (! $this->credit->design_id) { $this->credit->design_id = $this->decodePrimaryKey($settings->credit_design_id); + } - if(!isset($this->credit->footer)) + if (!isset($this->credit->footer)) { $this->credit->footer = $settings->credit_footer; + } - if(!isset($this->credit->terms)) + if (!isset($this->credit->terms)) { $this->credit->terms = $settings->credit_terms; + } - return $this; + return $this; } /** diff --git a/app/Services/Credit/SendEmail.php b/app/Services/Credit/SendEmail.php index 39b3533f3bba..271214dec66d 100644 --- a/app/Services/Credit/SendEmail.php +++ b/app/Services/Credit/SendEmail.php @@ -50,7 +50,6 @@ class SendEmail // EmailCredit::dispatchNow($email_builder, $invitation, $invitation->company); EmailEntity::dispatchNow($invitation, $invitation->company, $this->reminder_template); - } }); diff --git a/app/Services/Invoice/AddGatewayFee.php b/app/Services/Invoice/AddGatewayFee.php index 84af200f026e..13ddc521e768 100644 --- a/app/Services/Invoice/AddGatewayFee.php +++ b/app/Services/Invoice/AddGatewayFee.php @@ -48,8 +48,9 @@ class AddGatewayFee extends AbstractService { $gateway_fee = round($this->company_gateway->calcGatewayFee($this->amount, $this->gateway_type_id), $this->invoice->client->currency()->precision); - if((int)$gateway_fee == 0) + if ((int)$gateway_fee == 0) { return $this->invoice; + } $this->cleanPendingGatewayFees(); diff --git a/app/Services/Invoice/ApplyRecurringNumber.php b/app/Services/Invoice/ApplyRecurringNumber.php index 43126dffcfbd..a29f47e9120f 100644 --- a/app/Services/Invoice/ApplyRecurringNumber.php +++ b/app/Services/Invoice/ApplyRecurringNumber.php @@ -48,7 +48,7 @@ class ApplyRecurringNumber extends AbstractService break; case 'when_sent': if ($this->invoice->status_id == Invoice::STATUS_SENT) { - $this->invoice->number = $this->getNextRecurringInvoiceNumber($this->client); + $this->invoice->number = $this->getNextRecurringInvoiceNumber($this->client); } break; diff --git a/app/Services/Invoice/AutoBillInvoice.php b/app/Services/Invoice/AutoBillInvoice.php index 102f1bee251b..510d1759b23c 100644 --- a/app/Services/Invoice/AutoBillInvoice.php +++ b/app/Services/Invoice/AutoBillInvoice.php @@ -45,39 +45,44 @@ class AutoBillInvoice extends AbstractService public function run() { /* Is the invoice payable? */ - if (! $this->invoice->isPayable()) + if (! $this->invoice->isPayable()) { return $this->invoice; + } /* Mark the invoice as sent */ $this->invoice = $this->invoice->service()->markSent()->save(); /* Mark the invoice as paid if there is no balance */ - if ((int)$this->invoice->balance == 0) + if ((int)$this->invoice->balance == 0) { return $this->invoice->service()->markPaid()->save(); + } //if the credits cover the payments, we stop here, build the payment with credits and exit early - if($this->client->getSetting('use_credits_payment') != 'off') + if ($this->client->getSetting('use_credits_payment') != 'off') { $this->applyCreditPayment(); + } // info("partial = {$this->invoice->partial}"); // info("balance = {$this->invoice->balance}"); /* Determine $amount */ - if ($this->invoice->partial > 0) + if ($this->invoice->partial > 0) { $amount = $this->invoice->partial; - elseif($this->invoice->balance > 0) + } elseif ($this->invoice->balance > 0) { $amount = $this->invoice->balance; - else + } else { return $this->invoice; + } info("balance remains to be paid!!"); $gateway_token = $this->getGateway($amount); /* Bail out if no payment methods available */ - if (! $gateway_token || ! $gateway_token->gateway->driver($this->client)->token_billing) + if (! $gateway_token || ! $gateway_token->gateway->driver($this->client)->token_billing) { return $this->invoice; + } /* $gateway fee */ $fee = $gateway_token->gateway->calcGatewayFee($amount, $this->invoice->uses_inclusive_taxes); @@ -107,7 +112,6 @@ class AutoBillInvoice extends AbstractService */ private function finalizePaymentUsingCredits() { - $amount = array_sum(array_column($this->used_credit, 'amount')); $payment = PaymentFactory::create($this->invoice->company_id, $this->invoice->user_id); @@ -124,35 +128,34 @@ class AutoBillInvoice extends AbstractService $this->invoice->service()->setStatus(Invoice::STATUS_PAID)->save(); - foreach($this->used_credit as $credit) - { - $current_credit = Credit::find($credit['credit_id']); - $payment->credits()->attach($current_credit->id, ['amount' => $credit['amount']]); + foreach ($this->used_credit as $credit) { + $current_credit = Credit::find($credit['credit_id']); + $payment->credits()->attach($current_credit->id, ['amount' => $credit['amount']]); - info("adjusting credit balance {$current_credit->balance} by this amount ". $credit['amount']); + info("adjusting credit balance {$current_credit->balance} by this amount ". $credit['amount']); - $current_credit->balance -= $credit['amount']; + $current_credit->balance -= $credit['amount']; - $current_credit->service()->setCalculatedStatus()->save(); - // $this->applyPaymentToCredit($current_credit, $credit['amount']); - } + $current_credit->service()->setCalculatedStatus()->save(); + // $this->applyPaymentToCredit($current_credit, $credit['amount']); + } - $payment->ledger() + $payment->ledger() ->updatePaymentBalance($amount * -1) ->save(); - $this->invoice->client->service() + $this->invoice->client->service() ->updateBalance($amount * -1) ->updatePaidToDate($amount) ->adjustCreditBalance($amount * -1) ->save(); - $this->invoice->ledger() + $this->invoice->ledger() ->updateInvoiceBalance($amount * -1, 'Invoice payment using Credit') ->updateCreditBalance($amount * -1, 'Credits used to pay down Invoice ' . $this->invoice->number) ->save(); - event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); + event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); return $this->invoice->service()->setCalculatedStatus()->save(); } @@ -165,7 +168,6 @@ class AutoBillInvoice extends AbstractService */ private function applyCreditPayment() { - $available_credits = $this->client ->credits ->where('is_deleted', false) @@ -176,8 +178,9 @@ class AutoBillInvoice extends AbstractService info("available credit balance = {$available_credit_balance}"); - if((int)$available_credit_balance == 0) + if ((int)$available_credit_balance == 0) { return; + } $is_partial_amount = false; @@ -187,40 +190,35 @@ class AutoBillInvoice extends AbstractService $this->used_credit = []; - foreach($available_credits as $key => $credit) { - - if($is_partial_amount) { + foreach ($available_credits as $key => $credit) { + if ($is_partial_amount) { //more credit than needed - if($credit->balance >= $this->invoice->partial) { + if ($credit->balance >= $this->invoice->partial) { $this->used_credit[$key]['credit_id'] = $credit->id; $this->used_credit[$key]['amount'] = $this->invoice->partial; $this->invoice->balance -= $this->invoice->partial; $this->invoice->partial = 0; break; - } - else { + } else { $this->used_credit[$key]['credit_id'] = $credit->id; $this->used_credit[$key]['amount'] = $credit->balance; $this->invoice->partial -= $credit->balance; $this->invoice->balance -= $credit->balance; } - } - else { + } else { //more credit than needed - if($credit->balance >= $this->invoice->balance) { + if ($credit->balance >= $this->invoice->balance) { $this->used_credit[$key]['credit_id'] = $credit->id; $this->used_credit[$key]['amount'] = $this->invoice->balance; $this->invoice->balance = 0; break; - } - else { + } else { $this->used_credit[$key]['credit_id'] = $credit->id; $this->used_credit[$key]['amount'] = $credit->balance; $this->invoice->balance -= $credit->balance; } - } } @@ -233,7 +231,6 @@ class AutoBillInvoice extends AbstractService private function applyPaymentToCredit($credit, $amount) :Credit { - $credit_item = new InvoiceItem; $credit_item->type_id = '1'; $credit_item->product_key = ctrans('texts.credit'); diff --git a/app/Services/Invoice/HandleReversal.php b/app/Services/Invoice/HandleReversal.php index 9abac432f916..15e1abc2578a 100644 --- a/app/Services/Invoice/HandleReversal.php +++ b/app/Services/Invoice/HandleReversal.php @@ -97,8 +97,7 @@ class HandleReversal extends AbstractService } /*If there is a payment linked, then the credit needs to be linked back to that payment in case of refund*/ - if($paymentables->count() > 0){ - + if ($paymentables->count() > 0) { $payment = $paymentables->first()->payment; $payment->credits()->save($credit); @@ -110,7 +109,6 @@ class HandleReversal extends AbstractService //harvest the credit record and add in the amount for the credit. $paymentable_credit->pivot->amount = $total_paid; $paymentable_credit->pivot->save(); - } /* Set invoice balance to 0 */ @@ -136,5 +134,4 @@ class HandleReversal extends AbstractService return $this->invoice; //create a ledger row for this with the resulting Credit ( also include an explanation in the notes section ) } - } diff --git a/app/Services/Invoice/InvoiceService.php b/app/Services/Invoice/InvoiceService.php index 820da9613352..a75f23a13076 100644 --- a/app/Services/Invoice/InvoiceService.php +++ b/app/Services/Invoice/InvoiceService.php @@ -118,8 +118,9 @@ class InvoiceService { $this->invoice = (new UpdateBalance($this->invoice, $balance_adjustment))->run(); - if((int)$this->invoice->balance == 0) - $this->invoice->next_send_date = null; + if ((int)$this->invoice->balance == 0) { + $this->invoice->next_send_date = null; + } return $this; } @@ -143,7 +144,7 @@ class InvoiceService return (new GetInvoicePdf($this->invoice, $contact))->run(); } - public function getInvoiceDeliveryNote(\App\Models\Invoice $invoice, \App\Models\ClientContact $contact = null) + public function getInvoiceDeliveryNote(\App\Models\Invoice $invoice, \App\Models\ClientContact $contact = null) { return (new GenerateDeliveryNote($invoice, $contact))->run(); } @@ -225,22 +226,24 @@ class InvoiceService public function setCalculatedStatus() { - if((int)$this->invoice->balance == 0) + if ((int)$this->invoice->balance == 0) { $this->setStatus(Invoice::STATUS_PAID); - elseif($this->invoice->balance > 0 && $this->invoice->balance < $this->invoice->amount) + } elseif ($this->invoice->balance > 0 && $this->invoice->balance < $this->invoice->amount) { $this->setStatus(Invoice::STATUS_PARTIAL); + } return $this; } public function updateStatus() { - - if((int)$this->invoice->balance == 0) + if ((int)$this->invoice->balance == 0) { $this->setStatus(Invoice::STATUS_PAID); + } - if($this->invoice->balance > 0 && $this->invoice->balance < $this->invoice->amount) + if ($this->invoice->balance > 0 && $this->invoice->balance < $this->invoice->amount) { $this->setStatus(Invoice::STATUS_PARTIAL); + } return $this; } @@ -265,7 +268,7 @@ class InvoiceService public function deletePdf() { - UnlinkFile::dispatchNow(config('filesystems.default'),$this->invoice->client->invoice_filepath() . $this->invoice->number.'.pdf'); + UnlinkFile::dispatchNow(config('filesystems.default'), $this->invoice->client->invoice_filepath() . $this->invoice->number.'.pdf'); return $this; } @@ -306,7 +309,7 @@ class InvoiceService */ public function touchPdf() { - $this->invoice->invitations->each(function ($invitation){ + $this->invoice->invitations->each(function ($invitation) { CreateEntityPdf::dispatch($invitation); }); @@ -344,20 +347,20 @@ class InvoiceService $this->invoice->tasks()->update(['invoice_id' => null]); //set all tasks.invoice_ids = x with the current line_items - $tasks = collect($this->invoice->line_items)->map(function ($item){ - - if(isset($item->task_id)) + $tasks = collect($this->invoice->line_items)->map(function ($item) { + if (isset($item->task_id)) { $item->task_id = $this->decodePrimaryKey($item->task_id); + } - if(isset($item->expense_id)) + if (isset($item->expense_id)) { $item->expense_id = $this->decodePrimaryKey($item->expense_id); + } return $item; - }); - Task::whereIn('id',$tasks->pluck('task_id'))->update(['invoice_id' => $this->invoice->id]); - Expense::whereIn('id',$tasks->pluck('expense_id'))->update(['invoice_id' => $this->invoice->id]); + Task::whereIn('id', $tasks->pluck('task_id'))->update(['invoice_id' => $this->invoice->id]); + Expense::whereIn('id', $tasks->pluck('expense_id'))->update(['invoice_id' => $this->invoice->id]); return $this; } @@ -367,17 +370,20 @@ class InvoiceService { $settings = $this->invoice->client->getMergedSettings(); - if(! $this->invoice->design_id) + if (! $this->invoice->design_id) { $this->invoice->design_id = $this->decodePrimaryKey($settings->invoice_design_id); + } - if(!isset($this->invoice->footer)) + if (!isset($this->invoice->footer)) { $this->invoice->footer = $settings->invoice_footer; + } - if(!isset($this->invoice->terms)) + if (!isset($this->invoice->terms)) { $this->invoice->terms = $settings->invoice_terms; + } - return $this; + return $this; } /** diff --git a/app/Services/Invoice/MarkInvoiceDeleted.php b/app/Services/Invoice/MarkInvoiceDeleted.php index 7d245d64b487..a4bf50842c4b 100644 --- a/app/Services/Invoice/MarkInvoiceDeleted.php +++ b/app/Services/Invoice/MarkInvoiceDeleted.php @@ -40,15 +40,13 @@ class MarkInvoiceDeleted extends AbstractService public function run() { - $check = false; - $x=0; - - do { - - $number = $this->calcNumber($x); - $check = $this->checkNumberAvailable(Invoice::class, $this->invoice, $number); - $x++; + $check = false; + $x=0; + do { + $number = $this->calcNumber($x); + $check = $this->checkNumberAvailable(Invoice::class, $this->invoice, $number); + $x++; } while (!$check); $this->invoice->number = $number; @@ -63,13 +61,12 @@ class MarkInvoiceDeleted extends AbstractService private function calcNumber($x) { - if($x==0) - $number = $this->invoice->number . '_' . ctrans('texts.deleted'); - else - $number = $this->invoice->number . '_' . ctrans('texts.deleted') . '_'. $x; - - return $number; + if ($x==0) { + $number = $this->invoice->number . '_' . ctrans('texts.deleted'); + } else { + $number = $this->invoice->number . '_' . ctrans('texts.deleted') . '_'. $x; + } + return $number; } - } diff --git a/app/Services/Invoice/MarkPaid.php b/app/Services/Invoice/MarkPaid.php index a39d60885723..abf4e8e53e8a 100644 --- a/app/Services/Invoice/MarkPaid.php +++ b/app/Services/Invoice/MarkPaid.php @@ -75,8 +75,9 @@ class MarkPaid extends AbstractService ->applyNumber() ->save(); - if($this->invoice->client->getSetting('client_manual_payment_notification')) + if ($this->invoice->client->getSetting('client_manual_payment_notification')) { EmailPayment::dispatch($payment, $payment->company, $payment->client->primary_contact()->first()); + } /* Update Invoice balance */ event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); diff --git a/app/Services/Invoice/SendEmail.php b/app/Services/Invoice/SendEmail.php index 4436a5e419bb..5cf7f703d9d4 100644 --- a/app/Services/Invoice/SendEmail.php +++ b/app/Services/Invoice/SendEmail.php @@ -47,7 +47,6 @@ class SendEmail extends AbstractService $this->invoice->invitations->each(function ($invitation) { if ($invitation->contact->send_email && $invitation->contact->email) { EmailEntity::dispatchNow($invitation, $invitation->company, $this->reminder_template); - } }); } diff --git a/app/Services/Invoice/TriggeredActions.php b/app/Services/Invoice/TriggeredActions.php index caa5a5e17314..f64bef06e99d 100644 --- a/app/Services/Invoice/TriggeredActions.php +++ b/app/Services/Invoice/TriggeredActions.php @@ -68,7 +68,6 @@ class TriggeredActions extends AbstractService $reminder_template = 'payment'; $this->invoice->invitations->load('contact.client.country', 'invoice.client.country', 'invoice.company')->each(function ($invitation) use ($reminder_template) { - EmailEntity::dispatch($invitation, $this->invoice->company, $reminder_template); }); diff --git a/app/Services/Payment/DeletePayment.php b/app/Services/Payment/DeletePayment.php index 286012ca6a80..1e2272bc5d51 100644 --- a/app/Services/Payment/DeletePayment.php +++ b/app/Services/Payment/DeletePayment.php @@ -36,8 +36,9 @@ class DeletePayment public function run() { - if($this->payment->is_deleted) + if ($this->payment->is_deleted) { return $this->payment; + } return $this->setStatus(Payment::STATUS_CANCELLED) //sets status of payment ->updateCreditables() //return the credits first diff --git a/app/Services/Payment/RefundPayment.php b/app/Services/Payment/RefundPayment.php index 29e4d79491c7..350c879f7881 100644 --- a/app/Services/Payment/RefundPayment.php +++ b/app/Services/Payment/RefundPayment.php @@ -74,7 +74,6 @@ class RefundPayment { if ($this->refund_data['gateway_refund'] !== false && $this->total_refund > 0) { if ($this->payment->company_gateway) { - $response = $this->payment->company_gateway->driver($this->payment->client)->refund($this->payment, $this->total_refund); diff --git a/app/Services/Payment/UpdateInvoicePayment.php b/app/Services/Payment/UpdateInvoicePayment.php index 31643652ba2f..6d8e75881a06 100644 --- a/app/Services/Payment/UpdateInvoicePayment.php +++ b/app/Services/Payment/UpdateInvoicePayment.php @@ -42,7 +42,6 @@ class UpdateInvoicePayment $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($paid_invoices, 'invoice_id')))->get(); collect($paid_invoices)->each(function ($paid_invoice) use ($invoices) { - $invoice = $invoices->first(function ($inv) use ($paid_invoice) { return $paid_invoice->invoice_id == $inv->hashed_id; }); @@ -81,7 +80,6 @@ class UpdateInvoicePayment ->save(); event(new InvoiceWasUpdated($invoice, $invoice->company, Ninja::eventVars())); - }); $this->payment->save(); diff --git a/app/Services/PdfMaker/Design.php b/app/Services/PdfMaker/Design.php index c5174df408b3..12502c74bed9 100644 --- a/app/Services/PdfMaker/Design.php +++ b/app/Services/PdfMaker/Design.php @@ -214,9 +214,9 @@ class Design extends BaseDesign public function deliveryNoteTable(): array { - if ($this->type !== 'delivery_note') { - return []; - } + if ($this->type !== 'delivery_note') { + return []; + } $elements = [ ['element' => 'thead', 'elements' => [ @@ -232,8 +232,8 @@ class Design extends BaseDesign /** * Parent method for building products table. - * - * @return array + * + * @return array */ public function productTable(): array { @@ -257,8 +257,8 @@ class Design extends BaseDesign /** * Parent method for building tasks table. - * - * @return array + * + * @return array */ public function taskTable(): array { @@ -282,9 +282,9 @@ class Design extends BaseDesign /** * Generate the structure of table headers. () - * + * * @param string $type "product" or "task" - * @return array + * @return array */ public function buildTableHeader(string $type): array { @@ -301,9 +301,9 @@ class Design extends BaseDesign /** * Generate the structure of table body. () - * + * * @param string $type "$product" or "$task" - * @return array + * @return array */ public function buildTableBody(string $type): array { @@ -315,7 +315,7 @@ class Design extends BaseDesign return []; } - if ($type == 'delivery_note') { + if ($type == 'delivery_note') { foreach ($items as $row) { $element = ['element' => 'tr', 'elements' => []]; @@ -365,9 +365,9 @@ class Design extends BaseDesign if ($cell == '$task.rate') { $element['elements'][] = ['element' => 'td', 'content' => $row['$task.cost']]; - } else if ($cell == '$task.hours') { + } elseif ($cell == '$task.hours') { $element['elements'][] = ['element' => 'td', 'content' => $row['$task.quantity']]; - } else if ($cell == '$task.description') { + } elseif ($cell == '$task.description') { $_element = ['element' => 'td', 'content' => '', 'elements' => [ ['element' => 'span', 'content' => $row[$cell]], ]]; diff --git a/app/Services/PdfMaker/Designs/Utilities/DesignHelpers.php b/app/Services/PdfMaker/Designs/Utilities/DesignHelpers.php index 662ba2fcd343..f06837b25ed2 100644 --- a/app/Services/PdfMaker/Designs/Utilities/DesignHelpers.php +++ b/app/Services/PdfMaker/Designs/Utilities/DesignHelpers.php @@ -98,7 +98,7 @@ trait DesignHelpers * * Logic below will help us calculate that & inject the result in the * global state of the $context (design state). - * + * * @param string $type "product" or "task" * @return void */ diff --git a/app/Services/PdfMaker/PdfMaker.php b/app/Services/PdfMaker/PdfMaker.php index cd288766f65f..da6242ba54ce 100644 --- a/app/Services/PdfMaker/PdfMaker.php +++ b/app/Services/PdfMaker/PdfMaker.php @@ -57,7 +57,7 @@ class PdfMaker public function build() { if (isset($this->data['template']) && isset($this->data['variables'])) { - $this->getEmptyElements($this->data['template'], $this->data['variables']); + $this->getEmptyElements($this->data['template'], $this->data['variables']); } if (isset($this->data['template'])) { diff --git a/app/Services/PdfMaker/PdfMakerUtilities.php b/app/Services/PdfMaker/PdfMakerUtilities.php index dec845fc6aba..a4e9d506e36a 100644 --- a/app/Services/PdfMaker/PdfMakerUtilities.php +++ b/app/Services/PdfMaker/PdfMakerUtilities.php @@ -297,7 +297,7 @@ trait PdfMakerUtilities $this->document->getElementById('repeat-content')->appendChild($clone); } - // info($this->data['options']); + // info($this->data['options']); if ( $header = $this->document->getElementById('header') && @@ -324,26 +324,28 @@ trait PdfMakerUtilities } } - public function getEmptyElements(array &$elements, array $variables) { - foreach ($elements as &$element) { - if (isset($element['elements'])) { - $this->getEmptyChildrens($element['elements'], $variables); + public function getEmptyElements(array &$elements, array $variables) + { + foreach ($elements as &$element) { + if (isset($element['elements'])) { + $this->getEmptyChildrens($element['elements'], $variables); + } } - } } - public function getEmptyChildrens(array &$children, array $variables) { - foreach ($children as $key => &$child) { - if (isset($child['content']) && isset($child['show_empty']) && $child['show_empty'] === false) { - $value = strtr($child['content'], $variables['values']); - if ($value === '' || $value === ' ') { - $child['is_empty'] = true; - } - } + public function getEmptyChildrens(array &$children, array $variables) + { + foreach ($children as $key => &$child) { + if (isset($child['content']) && isset($child['show_empty']) && $child['show_empty'] === false) { + $value = strtr($child['content'], $variables['values']); + if ($value === '' || $value === ' ') { + $child['is_empty'] = true; + } + } - if (isset($child['elements'])) { - $this->getEmptyChildrens($child['elements'], $variables); + if (isset($child['elements'])) { + $this->getEmptyChildrens($child['elements'], $variables); + } } - } } } diff --git a/app/Services/Quote/QuoteService.php b/app/Services/Quote/QuoteService.php index 6d18c5dd9d26..b09072f73d9d 100644 --- a/app/Services/Quote/QuoteService.php +++ b/app/Services/Quote/QuoteService.php @@ -117,8 +117,9 @@ class QuoteService { $this->setStatus(Quote::STATUS_APPROVED)->save(); - if(!$contact) + if (!$contact) { $contact = $this->quote->invitations->first()->contact; + } event(new QuoteWasApproved($contact, $this->quote, $this->quote->company, Ninja::eventVars())); @@ -165,17 +166,20 @@ class QuoteService { $settings = $this->quote->client->getMergedSettings(); - if(! $this->quote->design_id) + if (! $this->quote->design_id) { $this->quote->design_id = $this->decodePrimaryKey($settings->quote_design_id); + } - if(!isset($this->quote->footer)) + if (!isset($this->quote->footer)) { $this->quote->footer = $settings->quote_footer; + } - if(!isset($this->quote->terms)) + if (!isset($this->quote->terms)) { $this->quote->terms = $settings->quote_terms; + } - return $this; + return $this; } /** diff --git a/app/Services/Quote/SendEmail.php b/app/Services/Quote/SendEmail.php index ae42c3b7ad81..8e7f670f85af 100644 --- a/app/Services/Quote/SendEmail.php +++ b/app/Services/Quote/SendEmail.php @@ -46,7 +46,6 @@ class SendEmail $this->quote->invitations->each(function ($invitation) { if ($invitation->contact->send_email && $invitation->contact->email) { EmailEntity::dispatchNow($invitation, $invitation->company, $this->reminder_template); - } }); diff --git a/app/Services/Recurring/CreateRecurringInvitations.php b/app/Services/Recurring/CreateRecurringInvitations.php index b85a211e685e..5bfbdfc08849 100644 --- a/app/Services/Recurring/CreateRecurringInvitations.php +++ b/app/Services/Recurring/CreateRecurringInvitations.php @@ -44,10 +44,8 @@ class CreateRecurringInvitations extends AbstractService public function run() { - try { $this->entity->client->contacts->each(function ($contact) { - $invitation = $this->invitation_class::whereCompanyId($this->entity->company_id) ->whereClientContactId($contact->id) ->where($this->entity_id_name, $this->entity->id) @@ -62,11 +60,8 @@ class CreateRecurringInvitations extends AbstractService } elseif ($invitation && ! $contact->send_email) { $invitation->delete(); } - }); - } - catch(Exception $e) - { + } catch (Exception $e) { info($e->getMessage()); } diff --git a/app/Services/Recurring/RecurringService.php b/app/Services/Recurring/RecurringService.php index 56b75f5e679b..4db604bdb826 100644 --- a/app/Services/Recurring/RecurringService.php +++ b/app/Services/Recurring/RecurringService.php @@ -28,13 +28,13 @@ class RecurringService //set schedules - update next_send_dates /** - * Stops a recurring invoice - * + * Stops a recurring invoice + * * @return $this RecurringService object */ public function stop() { - $this->status_id = RecurringInvoice::STATUS_PAUSED; + $this->status_id = RecurringInvoice::STATUS_PAUSED; return $this; } @@ -48,17 +48,17 @@ class RecurringService public function start() { - //make sure next_send_date is either now or in the future else return. - // if(Carbon::parse($this->recurring_entity->next_send_date)->lt(now())) - // return $this; + //make sure next_send_date is either now or in the future else return. + // if(Carbon::parse($this->recurring_entity->next_send_date)->lt(now())) + // return $this; - if($this->recurring_entity->remaining_cycles == 0) + if ($this->recurring_entity->remaining_cycles == 0) { return $this; + } $this->createInvitations()->setStatus(RecurringInvoice::STATUS_ACTIVE); - return $this; - + return $this; } public function setStatus($status) @@ -81,8 +81,8 @@ class RecurringService public function save() { - $this->recurring_entity->save(); + $this->recurring_entity->save(); - return $this->recurring_entity; + return $this->recurring_entity; } } diff --git a/app/Transformers/ClientGatewayTokenTransformer.php b/app/Transformers/ClientGatewayTokenTransformer.php index 7c6958acda51..60954246e14d 100644 --- a/app/Transformers/ClientGatewayTokenTransformer.php +++ b/app/Transformers/ClientGatewayTokenTransformer.php @@ -48,20 +48,25 @@ class ClientGatewayTokenTransformer extends EntityTransformer { $casted = new stdClass; - if(property_exists($meta, 'exp_month')) + if (property_exists($meta, 'exp_month')) { $casted->exp_month = (string)$meta->exp_month; + } - if(property_exists($meta, 'exp_year')) + if (property_exists($meta, 'exp_year')) { $casted->exp_year = (string)$meta->exp_year; + } - if(property_exists($meta, 'brand')) + if (property_exists($meta, 'brand')) { $casted->brand = (string)$meta->brand; + } - if(property_exists($meta, 'last4')) + if (property_exists($meta, 'last4')) { $casted->last4 = (string)$meta->last4; + } - if(property_exists($meta, 'type')) + if (property_exists($meta, 'type')) { $casted->type = (int)$meta->type; + } return $casted; } diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php index 32147e183164..ab0d99a9574d 100644 --- a/app/Transformers/UserTransformer.php +++ b/app/Transformers/UserTransformer.php @@ -95,9 +95,8 @@ class UserTransformer extends EntityTransformer } public function includeCompanyUser(User $user) - { - - if(!$user->company_id && request()->header('X-API-TOKEN')){ + { + if (!$user->company_id && request()->header('X-API-TOKEN')) { $company_token = CompanyToken::whereRaw('BINARY `token`= ?', [request()->header('X-API-TOKEN')])->first(); $user->company_id = $company_token->company_id; } diff --git a/app/Utils/Helpers.php b/app/Utils/Helpers.php index 961daef961be..5245d109c890 100644 --- a/app/Utils/Helpers.php +++ b/app/Utils/Helpers.php @@ -19,15 +19,13 @@ class Helpers { public static function sharedEmailVariables(?Client $client, array $settings = null): array { - if(!$client){ + if (!$client) { + $elements['signature'] = ''; + $elements['settings'] = new stdClass; + $elements['whitelabel'] = true; - $elements['signature'] = ''; - $elements['settings'] = new stdClass; - $elements['whitelabel'] = true; - - return $elements; - - } + return $elements; + } $_settings = is_null($settings) ? $client->getMergedSettings() : $settings; diff --git a/app/Utils/HtmlEngine.php b/app/Utils/HtmlEngine.php index 5a1f48addc08..3605267007a2 100644 --- a/app/Utils/HtmlEngine.php +++ b/app/Utils/HtmlEngine.php @@ -44,7 +44,6 @@ class HtmlEngine public function __construct($invitation) { - $this->invitation = $invitation; $this->entity_string = $this->resolveEntityString(); @@ -60,7 +59,6 @@ class HtmlEngine $this->settings = $this->client->getMergedSettings(); $this->entity_calc = $this->entity->calc(); - } @@ -153,10 +151,11 @@ class HtmlEngine $data['$subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getSubTotal(), $this->client) ?: ' ', 'label' => ctrans('texts.subtotal')]; $data['$invoice.subtotal'] = &$data['$subtotal']; - if($this->entity->partial > 0) + if ($this->entity->partial > 0) { $data['$balance_due'] = ['value' => Number::formatMoney($this->entity->partial, $this->client) ?: ' ', 'label' => ctrans('texts.balance_due')]; - else + } else { $data['$balance_due'] = ['value' => Number::formatMoney($this->entity->balance, $this->client) ?: ' ', 'label' => ctrans('texts.balance_due')]; + } $data['$quote.balance_due'] = &$data['$balance_due']; $data['$invoice.balance_due'] = &$data['$balance_due']; @@ -319,10 +318,11 @@ class HtmlEngine $data['$task.tax_name3'] = ['value' => '', 'label' => ctrans('texts.tax')]; $data['$task.line_total'] = ['value' => '', 'label' => ctrans('texts.line_total')]; - if($this->settings->signature_on_pdf) + if ($this->settings->signature_on_pdf) { $data['$contact.signature'] = ['value' => $this->invitation->signature_base64, 'label' => ctrans('texts.signature')]; - else + } else { $data['$contact.signature'] = ['value' => '', 'label' => '']; + } $data['$thanks'] = ['value' => '', 'label' => ctrans('texts.thanks')]; $data['$from'] = ['value' => '', 'label' => ctrans('texts.from')]; @@ -384,7 +384,7 @@ class HtmlEngine $arrKeysLength = array_map('strlen', array_keys($data)); array_multisort($arrKeysLength, SORT_DESC, $data); -//info(print_r($data,1)); + //info(print_r($data,1)); return $data; } @@ -531,8 +531,9 @@ class HtmlEngine $custom_field = $custom_fields->{$field}; $custom_field_parts = explode('|', $custom_field); - if(count($custom_field_parts) >= 2) + if (count($custom_field_parts) >= 2) { $custom_field = $custom_field_parts[1]; + } } switch ($custom_field) { diff --git a/app/Utils/Ninja.php b/app/Utils/Ninja.php index d88bcf28664e..d1b4de2ffadb 100644 --- a/app/Utils/Ninja.php +++ b/app/Utils/Ninja.php @@ -128,15 +128,14 @@ class Ninja $trans = (array)$settings->translations; - if(count($trans) == 0) + if (count($trans) == 0) { return $translations; + } - foreach($trans as $key => $value) - { - $translations['texts.'.$key] = $value; + foreach ($trans as $key => $value) { + $translations['texts.'.$key] = $value; } return $translations; - } } diff --git a/app/Utils/PhantomJS/Phantom.php b/app/Utils/PhantomJS/Phantom.php index fb95c27556ae..feb36b3d9209 100644 --- a/app/Utils/PhantomJS/Phantom.php +++ b/app/Utils/PhantomJS/Phantom.php @@ -36,7 +36,7 @@ class Phantom * * @param $invitation */ - public function generate($invitation) + public function generate($invitation) { $entity = false; @@ -68,7 +68,7 @@ class Phantom $file_path = $path.$entity_obj->number.'.pdf'; $url = config('ninja.app_url').'phantom/'.$entity.'/'.$invitation->key.'?phantomjs_secret='.config('ninja.phantomjs_secret'); -info($url); + info($url); $key = config('ninja.phantomjs_key'); $secret = config('ninja.phantomjs_key'); @@ -85,7 +85,6 @@ info($url); public function displayInvitation(string $entity, string $invitation_key) { - $key = $entity.'_id'; $invitation_instance = 'App\Models\\'.Str::camel(ucfirst($entity)).'Invitation'; @@ -105,12 +104,12 @@ info($url); $html = new HtmlEngine($invitation); if ($design->is_custom) { - $options = [ + $options = [ 'custom_partials' => json_decode(json_encode($design->design), true) ]; - $template = new PdfMakerDesign(PdfDesignModel::CUSTOM, $options); + $template = new PdfMakerDesign(PdfDesignModel::CUSTOM, $options); } else { - $template = new PdfMakerDesign(strtolower($design->name)); + $template = new PdfMakerDesign(strtolower($design->name)); } $state = [ diff --git a/app/Utils/Statics.php b/app/Utils/Statics.php index 890d84af849e..32cac1188070 100644 --- a/app/Utils/Statics.php +++ b/app/Utils/Statics.php @@ -106,7 +106,6 @@ class Statics })->values(); $data['templates'] = Cache::get('templates'); - } return $data; diff --git a/app/Utils/SystemHealth.php b/app/Utils/SystemHealth.php index 3e0283dcb3d3..4931fdd2fc3f 100644 --- a/app/Utils/SystemHealth.php +++ b/app/Utils/SystemHealth.php @@ -123,7 +123,6 @@ class SystemHealth private static function checkPhpCli() { - try { exec('php -v', $foo, $exitCode); @@ -133,7 +132,6 @@ class SystemHealth } catch (Exception $e) { return false; } - } private static function extensions() :array diff --git a/app/Utils/TemplateEngine.php b/app/Utils/TemplateEngine.php index 1adbe37f2659..430125ffd485 100644 --- a/app/Utils/TemplateEngine.php +++ b/app/Utils/TemplateEngine.php @@ -76,9 +76,9 @@ class TemplateEngine if (strlen($this->entity) > 1 && strlen($this->entity_id) > 1) { $class = 'App\Models\\'.ucfirst($this->entity); $this->entity_obj = $class::whereId($this->decodePrimaryKey($this->entity_id))->company()->first(); - } - else + } else { $this->mockEntity(); + } return $this; } @@ -100,23 +100,21 @@ class TemplateEngine private function setTemplates() { if (strlen($this->subject) == 0 && strlen($this->template) > 1) { - $subject_template = str_replace('template', 'subject', $this->template); - if(strlen($this->settings_entity->getSetting($subject_template)) > 1) + if (strlen($this->settings_entity->getSetting($subject_template)) > 1) { $this->subject = $this->settings_entity->getSetting($subject_template); - else + } else { $this->subject = EmailTemplateDefaults::getDefaultTemplate($subject_template, $this->settings_entity->locale()); - + } } if (strlen($this->body) == 0 && strlen($this->template) > 1) { - - if(strlen($this->settings_entity->getSetting($this->template)) > 1) + if (strlen($this->settings_entity->getSetting($this->template)) > 1) { $this->body = $this->settings_entity->getSetting($this->template); - else + } else { $this->body = EmailTemplateDefaults::getDefaultTemplate($this->template, $this->settings_entity->locale()); - + } } return $this; @@ -247,14 +245,10 @@ class TemplateEngine $this->entity_obj->load('client'); $client->setRelation('company', auth()->user()->company()); $client->load('company'); - } private function tearDown() { - DB::rollBack(); - } - } diff --git a/app/Utils/Traits/AppSetup.php b/app/Utils/Traits/AppSetup.php index 280d2a945374..debd5750c5e6 100644 --- a/app/Utils/Traits/AppSetup.php +++ b/app/Utils/Traits/AppSetup.php @@ -60,8 +60,9 @@ trait AppSetup } /*Build template cache*/ - if (request()->has('clear_cache') || !Cache::has('templates')) + if (request()->has('clear_cache') || !Cache::has('templates')) { $this->buildTemplates(); + } } diff --git a/app/Utils/Traits/CleanLineItems.php b/app/Utils/Traits/CleanLineItems.php index be2072a37a0c..2b68155bd2d7 100644 --- a/app/Utils/Traits/CleanLineItems.php +++ b/app/Utils/Traits/CleanLineItems.php @@ -28,9 +28,7 @@ trait CleanLineItems $cleaned_items = []; foreach ($items as $item) { - $cleaned_items[] = $this->cleanLineItem($item); - } return $cleaned_items; @@ -51,20 +49,17 @@ trait CleanLineItems //if the key has not been set, we set it to a default value if (! array_key_exists($key, $item) || ! isset($item[$key])) { - - $item[$key] = $value; + $item[$key] = $value; $item[$key] = BaseSettings::castAttribute(InvoiceItem::$casts[$key], $value); - - } - else{ + } else { //always cast the value! $item[$key] = BaseSettings::castAttribute(InvoiceItem::$casts[$key], $item[$key]); } - } - if (array_key_exists('id', $item)) + if (array_key_exists('id', $item)) { unset($item['id']); + } return $item; diff --git a/app/Utils/Traits/GeneratesCounter.php b/app/Utils/Traits/GeneratesCounter.php index da5c90d62009..66d37d7257d5 100644 --- a/app/Utils/Traits/GeneratesCounter.php +++ b/app/Utils/Traits/GeneratesCounter.php @@ -70,8 +70,9 @@ trait GeneratesCounter $padding = $client->getSetting('counter_padding'); $prefix = ''; - if($invoice && $invoice->recurring_id) + if ($invoice && $invoice->recurring_id) { $prefix = $client->getSetting('recurring_number_prefix'); + } $invoice_number = $this->checkEntityNumber(Invoice::class, $client, $counter, $padding, $pattern, $prefix); @@ -281,7 +282,6 @@ trait GeneratesCounter */ public function getNextProjectNumber(Project $project) :string { - $this->resetCompanyCounters($project->company); $counter = $project->company->settings->project_number_counter; @@ -370,15 +370,15 @@ trait GeneratesCounter $number = $this->prefixCounter($number, $prefix); - if ($class == Invoice::class || $class == RecurringInvoice::class) + if ($class == Invoice::class || $class == RecurringInvoice::class) { $check = $class::whereCompanyId($entity->company_id)->whereNumber($number)->withTrashed()->first(); - elseif ($class == Client::class || $class == Vendor::class) + } elseif ($class == Client::class || $class == Vendor::class) { $check = $class::whereCompanyId($entity->company_id)->whereIdNumber($number)->withTrashed()->first(); - else + } else { $check = $class::whereCompanyId($entity->company_id)->whereNumber($number)->withTrashed()->first(); + } $counter++; - } while ($check); return $number; @@ -388,8 +388,9 @@ trait GeneratesCounter /*Check if a number is available for use. */ public function checkNumberAvailable($class, $entity, $number) :bool { - if($entity = $class::whereCompanyId($entity->company_id)->whereNumber($number)->withTrashed()->first()) + if ($entity = $class::whereCompanyId($entity->company_id)->whereNumber($number)->withTrashed()->first()) { return false; + } return true; } @@ -600,7 +601,7 @@ trait GeneratesCounter $replace[] = str_replace($format, $date, $matches[1]); } - if($entity instanceof Client || $entity instanceof Vendor){ + if ($entity instanceof Client || $entity instanceof Vendor) { $search[] = '{$client_custom1}'; $replace[] = $entity->custom_value1; @@ -615,9 +616,7 @@ trait GeneratesCounter $search[] = '{$id_number}'; $replace[] = $entity->id_number; - } - else - { + } else { $search[] = '{$client_custom1}'; $replace[] = $entity->client->custom_value1; diff --git a/app/Utils/Traits/Inviteable.php b/app/Utils/Traits/Inviteable.php index af598a3ce12b..6765c3f65eb6 100644 --- a/app/Utils/Traits/Inviteable.php +++ b/app/Utils/Traits/Inviteable.php @@ -44,7 +44,6 @@ trait Inviteable public function getLink() :string { - $entity_type = Str::snake(class_basename($this->entityType())); $domain = isset($this->company->portal_domain) ?: $this->company->domain(); diff --git a/app/Utils/Traits/MakesDates.php b/app/Utils/Traits/MakesDates.php index 739e24f741ab..f22e9315b0d7 100644 --- a/app/Utils/Traits/MakesDates.php +++ b/app/Utils/Traits/MakesDates.php @@ -58,8 +58,9 @@ trait MakesDates */ public function formatDate($date, string $format) :string { - if(!isset($date)) + if (!isset($date)) { return ''; + } // if (!$date || strlen($date) < 1) { // return ''; // } diff --git a/app/Utils/Traits/MakesReminders.php b/app/Utils/Traits/MakesReminders.php index 2dd5e0f12899..6c87794df6e3 100644 --- a/app/Utils/Traits/MakesReminders.php +++ b/app/Utils/Traits/MakesReminders.php @@ -38,81 +38,72 @@ trait MakesReminders $settings->num_days_reminder1 > 0) { $reminder_date = Carbon::parse($this->date)->addDays($settings->num_days_reminder1); - if($reminder_date->gt(Carbon::parse($this->next_send_date))); - $date_collection->push($reminder_date->format('Y-m-d')); - + if ($reminder_date->gt(Carbon::parse($this->next_send_date))); + $date_collection->push($reminder_date->format('Y-m-d')); } if ($settings->schedule_reminder1 == 'before_due_date' && $settings->num_days_reminder1 > 0) { $reminder_date = Carbon::parse($this->due_date)->subDays($settings->num_days_reminder1); - if($reminder_date->gt(Carbon::parse($this->next_send_date))); - $date_collection->push($reminder_date->format('Y-m-d')); - + if ($reminder_date->gt(Carbon::parse($this->next_send_date))); + $date_collection->push($reminder_date->format('Y-m-d')); } if ($settings->schedule_reminder1 == 'after_due_date' && $settings->num_days_reminder1 > 0) { $reminder_date = Carbon::parse($this->due_date)->addDays($settings->num_days_reminder1); - if($reminder_date->gt(Carbon::parse($this->next_send_date))); - $date_collection->push($reminder_date->format('Y-m-d')); - + if ($reminder_date->gt(Carbon::parse($this->next_send_date))); + $date_collection->push($reminder_date->format('Y-m-d')); } if ($settings->schedule_reminder2 == 'after_invoice_date' && $settings->num_days_reminder2 > 0) { $reminder_date = Carbon::parse($this->date)->addDays($settings->num_days_reminder2); - if($reminder_date->gt(Carbon::parse($this->next_send_date))); - $date_collection->push($reminder_date->format('Y-m-d')); - + if ($reminder_date->gt(Carbon::parse($this->next_send_date))); + $date_collection->push($reminder_date->format('Y-m-d')); } if ($settings->schedule_reminder2 == 'before_due_date' && $settings->num_days_reminder2 > 0) { $reminder_date = Carbon::parse($this->due_date)->subDays($settings->num_days_reminder2); - if($reminder_date->gt(Carbon::parse($this->next_send_date))); - $date_collection->push($reminder_date->format('Y-m-d')); - + if ($reminder_date->gt(Carbon::parse($this->next_send_date))); + $date_collection->push($reminder_date->format('Y-m-d')); } if ($settings->schedule_reminder2 == 'after_due_date' && $settings->num_days_reminder2 > 0) { $reminder_date = Carbon::parse($this->due_date)->addDays($settings->num_days_reminder2); - if($reminder_date->gt(Carbon::parse($this->next_send_date))); - $date_collection->push($reminder_date->format('Y-m-d')); - + if ($reminder_date->gt(Carbon::parse($this->next_send_date))); + $date_collection->push($reminder_date->format('Y-m-d')); } if ($settings->schedule_reminder3 == 'after_invoice_date' && $settings->num_days_reminder3 > 0) { $reminder_date = Carbon::parse($this->date)->addDays($settings->num_days_reminder3); - if($reminder_date->gt(Carbon::parse($this->next_send_date))); - $date_collection->push($reminder_date->format('Y-m-d')); - + if ($reminder_date->gt(Carbon::parse($this->next_send_date))); + $date_collection->push($reminder_date->format('Y-m-d')); } if ($settings->schedule_reminder3 == 'before_due_date' && $settings->num_days_reminder3 > 0) { $reminder_date = Carbon::parse($this->due_date)->subDays($settings->num_days_reminder3); - if($reminder_date->gt(Carbon::parse($this->next_send_date))); - $date_collection->push($reminder_date->format('Y-m-d')); - + if ($reminder_date->gt(Carbon::parse($this->next_send_date))); + $date_collection->push($reminder_date->format('Y-m-d')); } if ($settings->schedule_reminder3 == 'after_due_date' && $settings->num_days_reminder3 > 0) { $reminder_date = Carbon::parse($this->due_date)->addDays($settings->num_days_reminder3); - if($reminder_date->gt(Carbon::parse($this->next_send_date))); - $date_collection->push($reminder_date->format('Y-m-d')); - + if ($reminder_date->gt(Carbon::parse($this->next_send_date))); + $date_collection->push($reminder_date->format('Y-m-d')); } $this->next_send_date = $date_collection->sort()->first(); @@ -143,8 +134,9 @@ trait MakesReminders //if invoice is currently a draft, or being marked as sent, this will be the initial email $client = $this->client; - if($entity_string != 'invoice') + if ($entity_string != 'invoice') { return $entity_string; + } //if the invoice if ($this->inReminderWindow( @@ -162,13 +154,12 @@ trait MakesReminders $client->getSetting('num_days_reminder3') )) { return 'reminder3'; - } elseif($this->checkEndlessReminder( - $this->last_sent_date, + } elseif ($this->checkEndlessReminder( + $this->last_sent_date, $client->getSetting('endless_reminder_frequency_id') - )){ + )) { return 'endless_reminder'; - } - else { + } else { return $entity_string; } @@ -177,16 +168,18 @@ trait MakesReminders private function checkEndlessReminder($last_sent_date, $endless_reminder_frequency_id) :bool { - if(Carbon::now()->startOfDay()->eq($this->addTimeInterval($last_sent_date, $endless_reminder_frequency_id))) + if (Carbon::now()->startOfDay()->eq($this->addTimeInterval($last_sent_date, $endless_reminder_frequency_id))) { return true; + } return false; } private function addTimeInterval($date, $endless_reminder_frequency_id) :?Carbon { - if(!$date) + if (!$date) { return null; + } switch ($endless_reminder_frequency_id) { diff --git a/app/Utils/Traits/Notifications/UserNotifies.php b/app/Utils/Traits/Notifications/UserNotifies.php index 7a9f7c22b38c..20a1494c7020 100644 --- a/app/Utils/Traits/Notifications/UserNotifies.php +++ b/app/Utils/Traits/Notifications/UserNotifies.php @@ -78,5 +78,4 @@ trait UserNotifies return $notifiable_methods; } - } diff --git a/app/Utils/Traits/Recurring/HasRecurrence.php b/app/Utils/Traits/Recurring/HasRecurrence.php index e56bdcb00ab2..f4ac8c185461 100644 --- a/app/Utils/Traits/Recurring/HasRecurrence.php +++ b/app/Utils/Traits/Recurring/HasRecurrence.php @@ -18,11 +18,11 @@ trait HasRecurrence { /** - * Calculates the first day of the month, this will ALWAYS + * Calculates the first day of the month, this will ALWAYS * be the first of NEXT month - * + * * @param Carbon $date The given date - * @return Carbon The first of NEXT month + * @return Carbon The first of NEXT month */ public function calculateFirstDayOfMonth($date) { @@ -33,21 +33,22 @@ trait HasRecurrence * Calculates the last day of the month. * * If it is the last day of the month - we add a month on. - * + * * @param Carbon $date The start date * @return Carbon The last day of month */ public function calculateLastDayOfMonth($date) { - if($date->isLastOfMonth()) + if ($date->isLastOfMonth()) { return $date->copy()->addMonthNoOverflow()->endOfMonth(); + } return $date->copy()->endOfMonth(); } /** * Sets the day of the month, if in the past we ADD a month - * + * * @param Carbon $date The start date * @param String|Int $day_of_month The day of the month */ @@ -59,14 +60,15 @@ trait HasRecurrence //If the set date is less than the original date we need to add a month. //If we are overflowing dates, then we need to diff the dates and ensure it doesn't equal 0 - if($set_date->lte($date) || $set_date->diffInDays($carbon_date) == 0) + if ($set_date->lte($date) || $set_date->diffInDays($carbon_date) == 0) { $set_date->addMonthNoOverflow(); + } - if($day_of_month == '31') + if ($day_of_month == '31') { $set_date->endOfMonth(); + } return $set_date; } - -} \ No newline at end of file +} diff --git a/app/Utils/Traits/SavesDocuments.php b/app/Utils/Traits/SavesDocuments.php index 2ce496f9b378..ff1b25575c63 100644 --- a/app/Utils/Traits/SavesDocuments.php +++ b/app/Utils/Traits/SavesDocuments.php @@ -67,6 +67,5 @@ trait SavesDocuments null, $is_public ); - } } diff --git a/app/Utils/Traits/Uploadable.php b/app/Utils/Traits/Uploadable.php index 7be78167d596..9f656f3b9734 100644 --- a/app/Utils/Traits/Uploadable.php +++ b/app/Utils/Traits/Uploadable.php @@ -20,7 +20,6 @@ use Illuminate\Support\Facades\Storage; */ trait Uploadable { - public function removeLogo($company) { $company_logo = $company->settings->company_logo; @@ -32,8 +31,6 @@ trait Uploadable if (Storage::exists($storage_path)) { UnlinkFile::dispatchNow(config('filesystems.default'), $storage_path); } - - } public function uploadLogo($file, $company, $entity) From b2c005a1aa559dd53ac7c11053f4968e0ca1083c Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 08:07:09 +1100 Subject: [PATCH 02/12] Create driver template --- app/PaymentDrivers/AbstractPaymentDriver.php | 13 ++- app/PaymentDrivers/BaseDriver.php | 82 ++++++++------- app/PaymentDrivers/DriverTemplate.php | 101 +++++++++++++++++++ 3 files changed, 155 insertions(+), 41 deletions(-) create mode 100644 app/PaymentDrivers/DriverTemplate.php diff --git a/app/PaymentDrivers/AbstractPaymentDriver.php b/app/PaymentDrivers/AbstractPaymentDriver.php index e59df6a4116a..b13da6aa4898 100644 --- a/app/PaymentDrivers/AbstractPaymentDriver.php +++ b/app/PaymentDrivers/AbstractPaymentDriver.php @@ -11,15 +11,24 @@ namespace App\PaymentDrivers; +use App\Models\ClientGatewayToken; use App\Models\Payment; +use App\Models\PaymentHash; +use Illuminate\Http\Request; abstract class AbstractPaymentDriver { - abstract public function authorize($payment_method); + abstract public function authorizeView(array $data); - abstract public function purchase($amount, $return_client_response = false); + abstract public function authorizeResponse(Request $request); + + abstract public function processPaymentView(array $data); + + abstract public function processPaymentResponse(Request $request); abstract public function refund(Payment $payment, $refund_amount, $return_client_response = false); + abstract public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash); + abstract public function setPaymentMethod($payment_method_id); } diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index 964001db2edb..e79bd66c1870 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -60,22 +60,19 @@ class BaseDriver extends AbstractPaymentDriver /* The client */ public $client; - /* The initiated gateway driver class*/ + /* The initialized gateway driver class*/ public $payment_method; - /** - * @var PaymentHash - */ + /* PaymentHash */ public $payment_hash; + /* Array of payment methods */ public static $methods = []; public function __construct(CompanyGateway $company_gateway, Client $client = null, $invitation = false) { $this->company_gateway = $company_gateway; - $this->invitation = $invitation; - $this->client = $client; } @@ -83,23 +80,35 @@ class BaseDriver extends AbstractPaymentDriver * Authorize a payment method. * * Returns a reusable token for storage for future payments - * @param const $payment_method The GatewayType::constant - * @return void Return a view for collecting payment method information + * + * @param array $data + * @return mixed Return a view for collecting payment method information */ - public function authorize($payment_method) - { - } + public function authorizeView(array $data) {} /** - * Executes purchase attempt for a given amount. - * - * @param float $amount The amount to be collected - * @param bool $return_client_response Whether the method needs to return a response (otherwise we assume an unattended payment) - * @return mixed + * The payment authorization response + * + * @param Request $request + * @return mixed Return a response for collecting payment method information */ - public function purchase($amount, $return_client_response = false) - { - } + public function authorizeResponse(Request $request) {} + + /** + * Process a payment + * + * @param array $data + * @return mixed Return a view for the payment + */ + public function processPaymentView(array $data) {} + + /** + * Process payment response + * + * @param Request $request + * @return mixed Return a response for the payment + */ + public function processPaymentResponse(Request $request) {} /** * Executes a refund attempt for a given amount with a transaction_reference. @@ -109,23 +118,30 @@ class BaseDriver extends AbstractPaymentDriver * @param bool $return_client_response Whether the method needs to return a response (otherwise we assume an unattended payment) * @return mixed */ - public function refund(Payment $payment, $amount, $return_client_response = false) - { - } + public function refund(Payment $payment, $amount, $return_client_response = false) {} + + /** + * Process an unattended payment. + * + * @param ClientGatewayToken $cgt The client gateway token object + * @param PaymentHash $payment_hash The Payment hash containing the payment meta data + * @return void The payment response + */ + public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash){} /** * Set the inbound request payment method type for access. * * @param int $payment_method_id The Payment Method ID */ - public function setPaymentMethod($payment_method_id) - { - } + public function setPaymentMethod($payment_method_id){} + + + /************************** Helper methods *************************************/ public function setPaymentHash(PaymentHash $payment_hash) { $this->payment_hash = $payment_hash; - return $this; } @@ -186,17 +202,6 @@ class BaseDriver extends AbstractPaymentDriver return $payment->service()->applyNumber()->save(); } - /** - * Process an unattended payment. - * - * @param ClientGatewayToken $cgt The client gateway token object - * @param PaymentHash $payment_hash The Payment hash containing the payment meta data - * @return void The payment response - */ - public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash) - { - } - /** * When a successful payment is made, we need to append the gateway fee * to an invoice. @@ -212,7 +217,7 @@ class BaseDriver extends AbstractPaymentDriver /*Payment invoices*/ $payment_invoices = $payment_hash->invoices(); - // /*Fee charged at gateway*/ + /*Fee charged at gateway*/ $fee_total = $payment_hash->fee_total; // Sum of invoice amounts @@ -262,7 +267,6 @@ class BaseDriver extends AbstractPaymentDriver } } - /** * Store payment method as company gateway token. * diff --git a/app/PaymentDrivers/DriverTemplate.php b/app/PaymentDrivers/DriverTemplate.php new file mode 100644 index 000000000000..e5575f6db3ed --- /dev/null +++ b/app/PaymentDrivers/DriverTemplate.php @@ -0,0 +1,101 @@ + CreditCard::class, //maps GatewayType => Implementation class + ]; + + const SYSTEM_LOG_TYPE = SystemLog::TYPE_STRIPE; + + public function setPaymentMethod($payment_method_id) + { + $class = self::$methods[$payment_method_id]; + $this->payment_method = new $class($this); + return $this; + } + + public function authorizeView(array $data) + { + return $this->payment_method->authorizeView($data); //this is your custom implementation from here + } + + public function authorizeResponse($request) + { + return $this->payment_method->authorizeResponse($request); //this is your custom implementation from here + } + + public function processPaymentView(array $data) + { + return $this->payment_method->paymentView($data); //this is your custom implementation from here + } + + public function processPaymentResponse($request) + { + return $this->payment_method->paymentResponse($request); //this is your custom implementation from here + } + + + public function refund(Payment $payment, $amount, $return_client_response = false) + { + return $this->payment_method->yourRefundImplementationHere(); + } + + public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash) + { + return $this->payment_method->yourTokenBillingImplmentation(); + } + + /** + * Creates a payment record for the given + * data array. + * + * @param array $data An array of payment attributes + * @param float $amount The amount of the payment + * @return Payment The payment object + */ + public function createPaymentRecord($data, $amount): ?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->gateway_type_id = $data['gateway_type_id']; + $payment->type_id = $data['type_id']; + $payment->currency_id = $this->client->getSetting('currency_id'); + $payment->date = Carbon::now(); + $payment->transaction_reference = $data['transaction_reference']; + $payment->amount = $amount; + $payment->save(); + + return $payment->service()->applyNumber()->save(); + } + + +} From 56ac6c7b1f4c4eff011df960ee158586c2a89c97 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 10:42:59 +1100 Subject: [PATCH 03/12] Refactoring authorize --- app/PaymentDrivers/AuthorizePaymentDriver.php | 73 ++++++++----------- app/PaymentDrivers/BaseDriver.php | 1 + 2 files changed, 33 insertions(+), 41 deletions(-) diff --git a/app/PaymentDrivers/AuthorizePaymentDriver.php b/app/PaymentDrivers/AuthorizePaymentDriver.php index b505d3e4e3fa..41c2348089dc 100644 --- a/app/PaymentDrivers/AuthorizePaymentDriver.php +++ b/app/PaymentDrivers/AuthorizePaymentDriver.php @@ -67,6 +67,38 @@ class AuthorizePaymentDriver extends BaseDriver return $types; } + public function authorizeView($payment_method) + { + return (new AuthorizePaymentMethod($this))->authorizeView($payment_method); + } + + public function authorizeResponseView(array $data) + { + return (new AuthorizePaymentMethod($this))->authorizeResponseView($data); + } + + public function processPaymentView($data) + { + return $this->payment_method->processPaymentView($data); + } + + public function processPaymentResponse($request) + { + return $this->payment_method->processPaymentResponse($request); + } + + public function refund(Payment $payment, $refund_amount, $return_client_response = false) + { + return (new RefundTransaction($this))->refundTransaction($payment, $refund_amount); + } + + public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash) + { + $this->setPaymentMethod($cgt->gateway_type_id); + + return $this->payment_method->tokenBilling($cgt, $payment_hash); + } + public function init() { error_reporting(E_ALL & ~E_DEPRECATED); @@ -98,41 +130,6 @@ class AuthorizePaymentDriver extends BaseDriver return $env = ANetEnvironment::PRODUCTION; } - public function authorizeView($payment_method) - { - return (new AuthorizePaymentMethod($this))->authorizeView($payment_method); - } - - public function authorizeResponseView(array $data) - { - return (new AuthorizePaymentMethod($this))->authorizeResponseView($data); - } - - public function authorize($payment_method) - { - return $this->authorizeView($payment_method); - } - - public function processPaymentView($data) - { - return $this->payment_method->processPaymentView($data); - } - - public function processPaymentResponse($request) - { - return $this->payment_method->processPaymentResponse($request); - } - - public function purchase($amount, $return_client_response = false) - { - return false; - } - - public function refund(Payment $payment, $refund_amount, $return_client_response = false) - { - return (new RefundTransaction($this))->refundTransaction($payment, $refund_amount); - } - public function findClientGatewayRecord() :?ClientGatewayToken { return ClientGatewayToken::where('client_id', $this->client->id) @@ -140,12 +137,6 @@ class AuthorizePaymentDriver extends BaseDriver ->first(); } - public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash) - { - $this->setPaymentMethod($cgt->gateway_type_id); - - return $this->payment_method->tokenBilling($cgt, $payment_hash); - } /** * Detach payment method from Authorize.net. diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index e79bd66c1870..741cbe61efeb 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -33,6 +33,7 @@ use App\Utils\Traits\SystemLogTrait; use Checkout\Library\Exceptions\CheckoutHttpException; use Exception; use Illuminate\Support\Carbon; +use Illuminate\Http\Request; /** * Class BaseDriver. From 4888a7dc4f5a8b9a1a939497dc4acdcce7778667 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 13:30:36 +1100 Subject: [PATCH 04/12] Working on authorize refactor --- .../Authorize/AuthorizePaymentMethod.php | 48 +++++++++---------- app/PaymentDrivers/AuthorizePaymentDriver.php | 2 +- app/PaymentDrivers/DriverTemplate.php | 32 +------------ 3 files changed, 27 insertions(+), 55 deletions(-) diff --git a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php index b2bc21c3991f..b344283c6580 100644 --- a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php +++ b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php @@ -15,8 +15,9 @@ namespace App\PaymentDrivers\Authorize; use App\Exceptions\GenericPaymentDriverFailure; use App\Models\ClientGatewayToken; use App\Models\GatewayType; -use App\PaymentDrivers\Authorize\AuthorizeCreateCustomer; use App\PaymentDrivers\AuthorizePaymentDriver; +use App\PaymentDrivers\Authorize\AuthorizeCreateCustomer; +use App\PaymentDrivers\Authorize\AuthorizeCreditCard; use net\authorize\api\contract\v1\CreateCustomerPaymentProfileRequest; use net\authorize\api\contract\v1\CreateCustomerProfileRequest; use net\authorize\api\contract\v1\CustomerAddressType; @@ -39,27 +40,28 @@ class AuthorizePaymentMethod public $payment_method; + private $payment_method_id; + public function __construct(AuthorizePaymentDriver $authorize) { $this->authorize = $authorize; } - public function authorizeView($payment_method) + public function authorizeView() { - $this->payment_method = $payment_method; + if($this->authorize->payment_method instanceof AuthorizeCreditCard){ - switch ($payment_method) { - case GatewayType::CREDIT_CARD: - return $this->authorizeCreditCard(); - break; - case GatewayType::BANK_TRANSFER: - return $this->authorizeBankTransfer(); - break; + $this->payment_method_id = GatewayType::CREDIT_CARD; + + return $this->authorizeCreditCard(); - default: - // code... - break; } + + + // case GatewayType::BANK_TRANSFER: + // return $this->authorizeBankTransfer(); + // break; + } public function authorizeResponseView($data) @@ -115,19 +117,17 @@ class AuthorizePaymentMethod public function createClientGatewayToken($payment_profile, $gateway_customer_reference) { - // info(print_r($payment_profile,1)); - $client_gateway_token = new ClientGatewayToken(); - $client_gateway_token->company_id = $this->authorize->client->company_id; - $client_gateway_token->client_id = $this->authorize->client->id; - $client_gateway_token->token = $payment_profile->getPaymentProfile()->getCustomerPaymentProfileId(); - $client_gateway_token->company_gateway_id = $this->authorize->company_gateway->id; - $client_gateway_token->gateway_type_id = $this->payment_method; - $client_gateway_token->gateway_customer_reference = $gateway_customer_reference; - $client_gateway_token->meta = $this->buildPaymentMethod($payment_profile); - $client_gateway_token->save(); + $data = []; + $additonal = []; - return $client_gateway_token; + $data['token'] = $payment_profile->getPaymentProfile()->getCustomerPaymentProfileId(); + $data['payment_method_id'] = $this->payment_method_id; + $data['payment_meta'] = $this->buildPaymentMethod($payment_profile); + + $additional['gateway_customer_reference'] = $gateway_customer_reference; + + $this->authorize->storeGatewayToken($data, $additional); } public function buildPaymentMethod($payment_profile) diff --git a/app/PaymentDrivers/AuthorizePaymentDriver.php b/app/PaymentDrivers/AuthorizePaymentDriver.php index 41c2348089dc..d8dc9b201a6e 100644 --- a/app/PaymentDrivers/AuthorizePaymentDriver.php +++ b/app/PaymentDrivers/AuthorizePaymentDriver.php @@ -69,7 +69,7 @@ class AuthorizePaymentDriver extends BaseDriver public function authorizeView($payment_method) { - return (new AuthorizePaymentMethod($this))->authorizeView($payment_method); + return (new AuthorizePaymentMethod($this))->authorizeView(); } public function authorizeResponseView(array $data) diff --git a/app/PaymentDrivers/DriverTemplate.php b/app/PaymentDrivers/DriverTemplate.php index e5575f6db3ed..4e98461d1d18 100644 --- a/app/PaymentDrivers/DriverTemplate.php +++ b/app/PaymentDrivers/DriverTemplate.php @@ -13,7 +13,6 @@ namespace App\PaymentDrivers; use App\Utils\Traits\MakesHash; - class YourGatewayPaymentDriver extends BaseDriver { use MakesHash; @@ -61,41 +60,14 @@ class YourGatewayPaymentDriver extends BaseDriver return $this->payment_method->paymentResponse($request); //this is your custom implementation from here } - public function refund(Payment $payment, $amount, $return_client_response = false) { - return $this->payment_method->yourRefundImplementationHere(); + return $this->payment_method->yourRefundImplementationHere(); //this is your custom implementation from here } public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash) { - return $this->payment_method->yourTokenBillingImplmentation(); + return $this->payment_method->yourTokenBillingImplmentation(); //this is your custom implementation from here } - - /** - * Creates a payment record for the given - * data array. - * - * @param array $data An array of payment attributes - * @param float $amount The amount of the payment - * @return Payment The payment object - */ - public function createPaymentRecord($data, $amount): ?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->gateway_type_id = $data['gateway_type_id']; - $payment->type_id = $data['type_id']; - $payment->currency_id = $this->client->getSetting('currency_id'); - $payment->date = Carbon::now(); - $payment->transaction_reference = $data['transaction_reference']; - $payment->amount = $amount; - $payment->save(); - - return $payment->service()->applyNumber()->save(); - } - } From 72bbf24c69b57a94d3c567f982db2c4352f5f864 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 15:43:53 +1100 Subject: [PATCH 05/12] Working on refactor --- .../Authorize/AuthorizeCreditCard.php | 56 ++++++++++++++++--- 1 file changed, 48 insertions(+), 8 deletions(-) diff --git a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php index 4324369b0a8e..c876737b0a52 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php +++ b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php @@ -100,18 +100,27 @@ class AuthorizeCreditCard $data = (new ChargePaymentProfile($this->authorize))->chargeCustomerProfile($cgt->gateway_customer_reference, $cgt->token, $amount); + /*Refactor and push to BaseDriver*/ if ($data['response'] != null && $data['response']->getMessages()->getResultCode() == 'Ok') { - $payment = $this->createPaymentRecord($data, $amount); - $payment->meta = $cgt->meta; - $payment->save(); + + $payment_record = []; + $payment_record['amount'] = $amount; + $payment_record['payment_type'] = PaymentType::CREDIT_CARD_OTHER;; + $payment_record['transaction_reference'] = $data['response']->getTransactionResponse()->getTransId(); + + $this->authorize->createPayment($payment_record); - $payment_hash->payment_id = $payment->id; - $payment_hash->save(); + // $payment = $this->createPaymentRecord($data, $amount); + // $payment->meta = $cgt->meta; + // $payment->save(); + + // $payment_hash->payment_id = $payment->id; + // $payment_hash->save(); - $this->authorize->attachInvoices($payment, $payment_hash); - $payment->service()->updateInvoicePayment($payment_hash); + // $this->authorize->attachInvoices($payment, $payment_hash); + // $payment->service()->updateInvoicePayment($payment_hash); - event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); + // event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); $vars = [ 'hashed_ids' => $invoice->hashed_id, @@ -131,6 +140,37 @@ class AuthorizeCreditCard } } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + private function handleResponse($data, $request) { $response = $data['response']; From 5e0bcfbc8889a78cda6faf49626746ce70871e49 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 20:39:35 +1100 Subject: [PATCH 06/12] working on authorize --- app/Helpers/Invoice/InvoiceSum.php | 8 ++++---- app/Helpers/Invoice/InvoiceSumInclusive.php | 8 ++++---- app/Utils/PhantomJS/Phantom.php | 2 ++ config/filesystems.php | 3 ++- 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php index a3c496dcde87..4ef116934266 100644 --- a/app/Helpers/Invoice/InvoiceSum.php +++ b/app/Helpers/Invoice/InvoiceSum.php @@ -160,19 +160,19 @@ class InvoiceSum { $this->total += $this->total_taxes; - if (is_numeric($this->invoice->custom_value1) && $this->invoice->custom_value1 > 0) { + if (is_numeric($this->invoice->custom_value1)) { $this->total += $this->invoice->custom_value1; } - if (is_numeric($this->invoice->custom_value2) && $this->invoice->custom_value2 > 0) { + if (is_numeric($this->invoice->custom_value2)) { $this->total += $this->invoice->custom_value2; } - if (is_numeric($this->invoice->custom_value3) && $this->invoice->custom_value3 > 0) { + if (is_numeric($this->invoice->custom_value3)) { $this->total += $this->invoice->custom_value3; } - if (is_numeric($this->invoice->custom_value4) && $this->invoice->custom_value4 > 0) { + if (is_numeric($this->invoice->custom_value4)) { $this->total += $this->invoice->custom_value4; } diff --git a/app/Helpers/Invoice/InvoiceSumInclusive.php b/app/Helpers/Invoice/InvoiceSumInclusive.php index f04818f62f52..3cba2e4a2944 100644 --- a/app/Helpers/Invoice/InvoiceSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceSumInclusive.php @@ -172,19 +172,19 @@ class InvoiceSumInclusive { //$this->total += $this->total_taxes; - if (is_numeric($this->invoice->custom_value1) && $this->invoice->custom_value1 > 0) { + if (is_numeric($this->invoice->custom_value1)) { $this->total += $this->invoice->custom_value1; } - if (is_numeric($this->invoice->custom_value2) && $this->invoice->custom_value2 > 0) { + if (is_numeric($this->invoice->custom_value2)) { $this->total += $this->invoice->custom_value2; } - if (is_numeric($this->invoice->custom_value3) && $this->invoice->custom_value3 > 0) { + if (is_numeric($this->invoice->custom_value3)) { $this->total += $this->invoice->custom_value3; } - if (is_numeric($this->invoice->custom_value4) && $this->invoice->custom_value4 > 0) { + if (is_numeric($this->invoice->custom_value4)) { $this->total += $this->invoice->custom_value4; } diff --git a/app/Utils/PhantomJS/Phantom.php b/app/Utils/PhantomJS/Phantom.php index feb36b3d9209..5c160624adef 100644 --- a/app/Utils/PhantomJS/Phantom.php +++ b/app/Utils/PhantomJS/Phantom.php @@ -76,6 +76,8 @@ class Phantom $phantom_url = "https://phantomjscloud.com/api/browser/v2/{$key}/?request=%7Burl:%22{$url}%22,renderType:%22pdf%22%7D"; $pdf = CurlUtils::get($phantom_url); + //info($pdf); + Storage::makeDirectory($path, 0775); $instance = Storage::disk(config('filesystems.default'))->put($file_path, $pdf); diff --git a/config/filesystems.php b/config/filesystems.php index 816d65b2b38c..76d21e4bac5d 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -60,7 +60,8 @@ return [ 'public' => [ 'driver' => 'local', - 'root' => storage_path('app/public'), + 'root' => 'storage/', + // 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', 'permissions' => [ From 150bb9c39698041f151140bad428e4dd76cc5de7 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 20:53:01 +1100 Subject: [PATCH 07/12] Fix for payment method route --- app/PaymentDrivers/AuthorizePaymentDriver.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/PaymentDrivers/AuthorizePaymentDriver.php b/app/PaymentDrivers/AuthorizePaymentDriver.php index d8dc9b201a6e..4666d3b3d5bb 100644 --- a/app/PaymentDrivers/AuthorizePaymentDriver.php +++ b/app/PaymentDrivers/AuthorizePaymentDriver.php @@ -72,7 +72,7 @@ class AuthorizePaymentDriver extends BaseDriver return (new AuthorizePaymentMethod($this))->authorizeView(); } - public function authorizeResponseView(array $data) + public function authorizeResponse(array $data) { return (new AuthorizePaymentMethod($this))->authorizeResponseView($data); } From ed1539db50bbead932f8c3d2a9dd81b1039f5115 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 21:00:55 +1100 Subject: [PATCH 08/12] Fixes for authorize --- app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php | 4 +++- app/PaymentDrivers/AuthorizePaymentDriver.php | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php index b344283c6580..0a68cfcf4ca9 100644 --- a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php +++ b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php @@ -64,8 +64,10 @@ class AuthorizePaymentMethod } - public function authorizeResponseView($data) + public function authorizeResponseView($request) { + $data = $request->all(); + $this->payment_method = $data['payment_method_id']; switch ($this->payment_method) { diff --git a/app/PaymentDrivers/AuthorizePaymentDriver.php b/app/PaymentDrivers/AuthorizePaymentDriver.php index 4666d3b3d5bb..f462024ece3a 100644 --- a/app/PaymentDrivers/AuthorizePaymentDriver.php +++ b/app/PaymentDrivers/AuthorizePaymentDriver.php @@ -72,9 +72,9 @@ class AuthorizePaymentDriver extends BaseDriver return (new AuthorizePaymentMethod($this))->authorizeView(); } - public function authorizeResponse(array $data) + public function authorizeResponse($request) { - return (new AuthorizePaymentMethod($this))->authorizeResponseView($data); + return (new AuthorizePaymentMethod($this))->authorizeResponseView($request); } public function processPaymentView($data) From a8daa31167c921f15de870bc738de32c4266164b Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 21:12:36 +1100 Subject: [PATCH 09/12] Fixes for authorize --- app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php | 2 +- .../ninja2020/gateways/authorize/add_credit_card.blade.php | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php index 0a68cfcf4ca9..28e44d11467a 100644 --- a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php +++ b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php @@ -68,7 +68,7 @@ class AuthorizePaymentMethod { $data = $request->all(); - $this->payment_method = $data['payment_method_id']; + $this->payment_method_id = $data['method']; switch ($this->payment_method) { case GatewayType::CREDIT_CARD: diff --git a/resources/views/portal/ninja2020/gateways/authorize/add_credit_card.blade.php b/resources/views/portal/ninja2020/gateways/authorize/add_credit_card.blade.php index cd725c0f083a..fa1f016a990e 100644 --- a/resources/views/portal/ninja2020/gateways/authorize/add_credit_card.blade.php +++ b/resources/views/portal/ninja2020/gateways/authorize/add_credit_card.blade.php @@ -17,7 +17,8 @@ @endpush @section('body') -
+ + @csrf From 0e1b6c9341907441de58ece3f28d5b171aa7d94d Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 22:22:33 +1100 Subject: [PATCH 10/12] Fixes for authorize --- app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php index 28e44d11467a..a3fca5069931 100644 --- a/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php +++ b/app/PaymentDrivers/Authorize/AuthorizePaymentMethod.php @@ -70,7 +70,7 @@ class AuthorizePaymentMethod $this->payment_method_id = $data['method']; - switch ($this->payment_method) { + switch ($this->payment_method_id) { case GatewayType::CREDIT_CARD: return $this->authorizeCreditCardResponse($data); break; From dff41d4881bfe74814556e7292ea1ea68dc2c648 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 22:27:32 +1100 Subject: [PATCH 11/12] Fixes for authorize --- app/PaymentDrivers/Authorize/AuthorizeCreditCard.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php index c876737b0a52..9b5f187be2db 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php +++ b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php @@ -103,10 +103,12 @@ class AuthorizeCreditCard /*Refactor and push to BaseDriver*/ if ($data['response'] != null && $data['response']->getMessages()->getResultCode() == 'Ok') { + $response = $data['response']; + $payment_record = []; $payment_record['amount'] = $amount; $payment_record['payment_type'] = PaymentType::CREDIT_CARD_OTHER;; - $payment_record['transaction_reference'] = $data['response']->getTransactionResponse()->getTransId(); + $payment_record['transaction_reference'] = $response->getTransactionResponse()->getTransId(); $this->authorize->createPayment($payment_record); From ccac43297833e8de3bf7cb77ee2d7d9e280bbea3 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 26 Nov 2020 22:35:17 +1100 Subject: [PATCH 12/12] Fixes for authorize --- .../Authorize/AuthorizeCreditCard.php | 55 +++++-------------- 1 file changed, 15 insertions(+), 40 deletions(-) diff --git a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php index 9b5f187be2db..3963c1ba3be8 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php +++ b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php @@ -103,14 +103,16 @@ class AuthorizeCreditCard /*Refactor and push to BaseDriver*/ if ($data['response'] != null && $data['response']->getMessages()->getResultCode() == 'Ok') { - $response = $data['response']; - - $payment_record = []; - $payment_record['amount'] = $amount; - $payment_record['payment_type'] = PaymentType::CREDIT_CARD_OTHER;; - $payment_record['transaction_reference'] = $response->getTransactionResponse()->getTransId(); + // $response = $data['response']; - $this->authorize->createPayment($payment_record); + // $payment_record = []; + // $payment_record['amount'] = $amount; + // $payment_record['payment_type'] = PaymentType::CREDIT_CARD_OTHER;; + // $payment_record['transaction_reference'] = $response->getTransactionResponse()->getTransId(); + + // $this->authorize->createPayment($payment_record); + + $this->storePayment($payment_hash, $data); // $payment = $this->createPaymentRecord($data, $amount); // $payment->meta = $cgt->meta; @@ -148,31 +150,6 @@ class AuthorizeCreditCard - - - - - - - - - - - - - - - - - - - - - - - - - private function handleResponse($data, $request) { $response = $data['response']; @@ -190,16 +167,14 @@ class AuthorizeCreditCard { $amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total; - $payment = $this->createPaymentRecord($data, $amount); - - $payment_hash->payment_id = $payment->id; - $payment_hash->save(); + $response = $data['response']; - $this->authorize->attachInvoices($payment, $payment_hash); + $payment_record = []; + $payment_record['amount'] = $amount; + $payment_record['payment_type'] = PaymentType::CREDIT_CARD_OTHER;; + $payment_record['transaction_reference'] = $response->getTransactionResponse()->getTransId(); - $payment->service()->updateInvoicePayment($payment_hash); - - event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); + $payment = $this->authorize->createPayment($payment_record); return $payment; }