From 5dfb031621fe089ff4b92f4e36758e3ee2f555d4 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sun, 6 Aug 2023 16:10:47 +1000 Subject: [PATCH 01/33] Fixes for bulk quote approval --- app/Http/Controllers/ClientPortal/QuoteController.php | 8 ++++---- phpstan.neon | 2 +- resources/views/portal/ninja2020/quotes/approve.blade.php | 8 +++++--- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/app/Http/Controllers/ClientPortal/QuoteController.php b/app/Http/Controllers/ClientPortal/QuoteController.php index 83c541452f..d53d668ee2 100644 --- a/app/Http/Controllers/ClientPortal/QuoteController.php +++ b/app/Http/Controllers/ClientPortal/QuoteController.php @@ -96,7 +96,7 @@ class QuoteController extends Controller $client_contact = auth()->user(); $data['quotes'] = Quote::whereIn('id', $ids) - ->whereClientId($client_contact->client->id) + ->where('client_id', $client_contact->client_id) ->withTrashed() ->get(); @@ -195,10 +195,10 @@ class QuoteController extends Controller } } - if (count($ids) == 1) { + if ($quotes->count() == 1) { //forward client to the invoice if it exists - if ($quote->invoice()->exists()) { - return redirect()->route('client.invoice.show', $quote->invoice->hashed_id); + if ($quotes->first()->invoice()->exists()) { + return redirect()->route('client.invoice.show', $quotes->first()->invoice->hashed_id); } return redirect()->route('client.quote.show', $quotes->first()->hashed_id); diff --git a/phpstan.neon b/phpstan.neon index 2b60d7d202..4514c5ecc8 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -17,5 +17,5 @@ parameters: ignoreErrors: - '#Call to an undefined method [a-zA-Z0-9\\_]+::company\(\)#' - '#Call to an undefined method [a-zA-Z0-9\\_]+::entityFilter\(\)#' - - '#Call to an undefined method [a-zA-Z0-9\\_]+::withTrashed()\(\)#' + - '#Call to an undefined method [a-zA-Z0-9\\_]+::withTrashed\(\)#' - '#Undefined method#' \ No newline at end of file diff --git a/resources/views/portal/ninja2020/quotes/approve.blade.php b/resources/views/portal/ninja2020/quotes/approve.blade.php index 4eab04f486..67fab2fe8f 100644 --- a/resources/views/portal/ninja2020/quotes/approve.blade.php +++ b/resources/views/portal/ninja2020/quotes/approve.blade.php @@ -4,6 +4,7 @@ @push('head') + @endpush @@ -41,7 +42,7 @@

- {{ ctrans('texts.invoice') }} + {{ ctrans('texts.quote') }} ({{ $quote->number }}) @@ -82,11 +83,12 @@

+@endsection +@section('footer') + @include('portal.ninja2020.quotes.includes.user-input') @include('portal.ninja2020.invoices.includes.terms', ['entities' => $quotes, 'entity_type' => ctrans('texts.quote')]) @include('portal.ninja2020.invoices.includes.signature') - - @endsection @push('footer') From b13783d75bcab7b0d7d1f34e2b411f88271a015f Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sun, 6 Aug 2023 17:03:12 +1000 Subject: [PATCH 02/33] Migration for dashboard permissions --- .../Subscription/SubscriptionCalculator.php | 2 +- app/Http/Controllers/BaseController.php | 2 +- .../ClientPortal/ApplePayDomainController.php | 3 +- .../ClientPortal/DocumentController.php | 2 +- .../ClientPortal/InvoiceController.php | 16 +++++-- .../ClientPortal/NinjaPlanController.php | 6 +-- .../ClientPortal/PaymentController.php | 2 +- .../ClientPortal/QuoteController.php | 9 ++-- app/Http/Controllers/CreditController.php | 12 +++-- app/Http/Controllers/DocumentController.php | 2 +- .../PreviewPurchaseOrderController.php | 2 +- .../VendorPortal/DocumentController.php | 2 +- .../VendorPortal/PurchaseOrderController.php | 3 +- .../VendorContactHashLoginController.php | 2 +- .../ValidCreditsPresentRule.php | 2 +- .../ValidPayableInvoicesRule.php | 2 +- .../ValidRefundableInvoices.php | 2 +- app/Jobs/Bank/MatchBankTransactions.php | 2 +- app/Jobs/Document/ZipDocuments.php | 2 +- app/Jobs/Mail/PaymentFailedMailer.php | 2 +- app/Mail/Admin/AutoBillingFailureObject.php | 2 +- app/Mail/Engine/InvoiceEmailEngine.php | 4 +- app/Models/Account.php | 7 ++- app/Models/BankTransaction.php | 2 +- app/Models/BaseModel.php | 13 +++--- app/Models/Company.php | 5 ++- app/Models/CompanyGateway.php | 2 +- app/Models/Invoice.php | 4 +- app/Models/PurchaseOrder.php | 14 +----- app/Models/Quote.php | 2 + app/Models/Traits/Excludable.php | 6 +++ app/Models/User.php | 2 +- .../Authorize/AuthorizeTransaction.php | 2 +- .../Authorize/ChargePaymentProfile.php | 2 +- app/PaymentDrivers/BaseDriver.php | 10 ++--- app/PaymentDrivers/BraintreePaymentDriver.php | 2 +- .../CheckoutComPaymentDriver.php | 2 +- app/PaymentDrivers/GoCardless/ACH.php | 2 +- app/PaymentDrivers/GoCardless/DirectDebit.php | 2 +- app/PaymentDrivers/GoCardless/SEPA.php | 2 +- .../GoCardlessPaymentDriver.php | 2 +- app/PaymentDrivers/MolliePaymentDriver.php | 2 +- app/PaymentDrivers/SquarePaymentDriver.php | 2 +- .../BankTransactionRepository.php | 2 +- .../Migration/PaymentMigrationRepository.php | 4 +- app/Repositories/PaymentRepository.php | 2 +- app/Services/ClientPortal/InstantPayment.php | 2 +- app/Services/Credit/CreateInvitations.php | 3 +- app/Services/Email/EmailDefaults.php | 4 +- app/Services/Email/EmailMailable.php | 4 +- app/Services/Invoice/InvoiceService.php | 4 +- app/Services/Payment/UpdateInvoicePayment.php | 2 +- app/Services/Quote/CreateInvitations.php | 3 +- .../Subscription/SubscriptionService.php | 10 ++--- .../Traits/GeneratesConvertedQuoteCounter.php | 2 +- ...te_view_dashboard_permission_migration.php | 45 +++++++++++++++++++ phpstan.neon | 1 + 57 files changed, 161 insertions(+), 97 deletions(-) create mode 100644 database/migrations/2023_08_06_070205_create_view_dashboard_permission_migration.php diff --git a/app/Helpers/Subscription/SubscriptionCalculator.php b/app/Helpers/Subscription/SubscriptionCalculator.php index 99049bab39..2c5cd39988 100644 --- a/app/Helpers/Subscription/SubscriptionCalculator.php +++ b/app/Helpers/Subscription/SubscriptionCalculator.php @@ -40,7 +40,7 @@ class SubscriptionCalculator */ public function isPaidUp() :bool { - $outstanding_invoices_exist = Invoice::whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) + $outstanding_invoices_exist = Invoice::query()->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('subscription_id', $this->invoice->subscription_id) ->where('client_id', $this->invoice->client_id) ->where('balance', '>', 0) diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index b61390e347..d320a8fad2 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -532,7 +532,7 @@ class BaseController extends Controller /** @phpstan-ignore-next-line */ $query = $paginator->getCollection(); /** @phpstan-ignore-line */ - + /** @phpstan-ignore-line */ $resource = new Collection($query, $transformer, $this->entity_type); diff --git a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php index c4b016c647..ed1e174a95 100644 --- a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php +++ b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php @@ -26,7 +26,8 @@ class ApplePayDomainController extends Controller /* Self Host */ if (Ninja::isSelfHost()) { - $cgs = CompanyGateway::whereIn('gateway_key', $this->stripe_keys) + $cgs = CompanyGateway::query() + ->whereIn('gateway_key', $this->stripe_keys) ->where('is_deleted', false) ->get(); diff --git a/app/Http/Controllers/ClientPortal/DocumentController.php b/app/Http/Controllers/ClientPortal/DocumentController.php index 1f4da5d024..88024a39a3 100644 --- a/app/Http/Controllers/ClientPortal/DocumentController.php +++ b/app/Http/Controllers/ClientPortal/DocumentController.php @@ -71,7 +71,7 @@ class DocumentController extends Controller public function downloadMultiple(DownloadMultipleDocumentsRequest $request) { /** @var \Illuminate\Database\Eloquent\Collection $documents **/ - $documents = Document::whereIn('id', $this->transformKeys($request->file_hash)) + $documents = Document::query()->whereIn('id', $this->transformKeys($request->file_hash)) ->where('company_id', auth()->guard('contact')->user()->company_id) ->get(); diff --git a/app/Http/Controllers/ClientPortal/InvoiceController.php b/app/Http/Controllers/ClientPortal/InvoiceController.php index cb6764c6a8..f67ae60427 100644 --- a/app/Http/Controllers/ClientPortal/InvoiceController.php +++ b/app/Http/Controllers/ClientPortal/InvoiceController.php @@ -87,7 +87,8 @@ class InvoiceController extends Controller public function showBlob($hash) { $data = Cache::get($hash); - + $invitation = false; + match($data['entity_type']){ 'invoice' => $invitation = InvoiceInvitation::withTrashed()->find($data['invitation_id']), 'quote' => $invitation = QuoteInvitation::withTrashed()->find($data['invitation_id']), @@ -95,6 +96,10 @@ class InvoiceController extends Controller 'recurring_invoice' => $invitation = RecurringInvoiceInvitation::withTrashed()->find($data['invitation_id']), }; + if (! $invitation) { + return redirect('/'); + } + $file = (new \App\Jobs\Entity\CreateRawPdf($invitation, $invitation->company->db))->handle(); $headers = ['Content-Type' => 'application/pdf']; @@ -128,7 +133,8 @@ class InvoiceController extends Controller public function downloadInvoices($ids) { - $data['invoices'] = Invoice::whereIn('id', $ids) + $data['invoices'] = Invoice::query() + ->whereIn('id', $ids) ->whereClientId(auth()->guard('contact')->user()->client->id) ->withTrashed() ->get(); @@ -153,7 +159,8 @@ class InvoiceController extends Controller */ private function makePayment(array $ids) { - $invoices = Invoice::whereIn('id', $ids) + $invoices = Invoice::query() + ->whereIn('id', $ids) ->whereClientId(auth()->guard('contact')->user()->client->id) ->withTrashed() ->get(); @@ -215,7 +222,8 @@ class InvoiceController extends Controller */ private function downloadInvoicePDF(array $ids) { - $invoices = Invoice::whereIn('id', $ids) + $invoices = Invoice::query() + ->whereIn('id', $ids) ->withTrashed() ->whereClientId(auth()->guard('contact')->user()->client->id) ->get(); diff --git a/app/Http/Controllers/ClientPortal/NinjaPlanController.php b/app/Http/Controllers/ClientPortal/NinjaPlanController.php index 996b8c2209..f0346d2371 100644 --- a/app/Http/Controllers/ClientPortal/NinjaPlanController.php +++ b/app/Http/Controllers/ClientPortal/NinjaPlanController.php @@ -40,13 +40,13 @@ class NinjaPlanController extends Controller public function index(string $contact_key, string $account_or_company_key) { MultiDB::findAndSetDbByCompanyKey($account_or_company_key); - $company = Company::where('company_key', $account_or_company_key)->first(); + $company = Company::query()->where('company_key', $account_or_company_key)->first(); if (! $company) { MultiDB::findAndSetDbByAccountKey($account_or_company_key); /** @var \App\Models\Account $account **/ - $account = Account::where('key', $account_or_company_key)->first(); + $account = Account::query()->where('key', $account_or_company_key)->first(); } else { $account = $company->account; } @@ -181,7 +181,7 @@ class NinjaPlanController extends Controller ->increment() ->queue(); - $old_recurring = RecurringInvoice::where('company_id', config('ninja.ninja_default_company_id')) + $old_recurring = RecurringInvoice::query()->where('company_id', config('ninja.ninja_default_company_id')) ->where('client_id', $client->id) ->where('id', '!=', $recurring_invoice->id) ->first(); diff --git a/app/Http/Controllers/ClientPortal/PaymentController.php b/app/Http/Controllers/ClientPortal/PaymentController.php index d696c083de..841a61a105 100644 --- a/app/Http/Controllers/ClientPortal/PaymentController.php +++ b/app/Http/Controllers/ClientPortal/PaymentController.php @@ -169,7 +169,7 @@ class PaymentController extends Controller $payment = $payment->service()->applyCredits($payment_hash)->save(); /** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Invoice> $invoices */ - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id'))); + $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id'))); $invoices->each(function ($invoice) { /** @var \App\Models\Invoice $invoice **/ diff --git a/app/Http/Controllers/ClientPortal/QuoteController.php b/app/Http/Controllers/ClientPortal/QuoteController.php index d53d668ee2..6d3eb9c033 100644 --- a/app/Http/Controllers/ClientPortal/QuoteController.php +++ b/app/Http/Controllers/ClientPortal/QuoteController.php @@ -95,7 +95,8 @@ class QuoteController extends Controller /** @var \App\Models\ClientContact $client_contact **/ $client_contact = auth()->user(); - $data['quotes'] = Quote::whereIn('id', $ids) + $data['quotes'] = Quote::query() + ->whereIn('id', $ids) ->where('client_id', $client_contact->client_id) ->withTrashed() ->get(); @@ -120,7 +121,8 @@ class QuoteController extends Controller /** @var \App\Models\ClientContact $client_contact **/ $client_contact = auth()->user(); - $quotes = Quote::whereIn('id', $ids) + $quotes = Quote::query() + ->whereIn('id', $ids) ->whereClientId($client_contact->client_id) ->withTrashed() ->get(); @@ -168,7 +170,8 @@ class QuoteController extends Controller protected function approve(array $ids, $process = false) { - $quotes = Quote::whereIn('id', $ids) + $quotes = Quote::query() + ->whereIn('id', $ids) ->where('client_id', auth()->guard('contact')->user()->client->id) ->where('company_id', auth()->guard('contact')->user()->client->company_id) ->whereIn('status_id', [Quote::STATUS_DRAFT, Quote::STATUS_SENT]) diff --git a/app/Http/Controllers/CreditController.php b/app/Http/Controllers/CreditController.php index fb48ea46cb..e502f7ba29 100644 --- a/app/Http/Controllers/CreditController.php +++ b/app/Http/Controllers/CreditController.php @@ -148,10 +148,10 @@ class CreditController extends BaseController */ public function create(CreateCreditRequest $request) { - /** @var \App\Models\User $user**/ + /** @var \App\Models\User $user **/ $user = auth()->user(); - $credit = CreditFactory::create($user->company()->id, auth()->user()->id); + $credit = CreditFactory::create($user->company()->id, $user->id); return $this->itemResponse($credit); } @@ -197,11 +197,9 @@ class CreditController extends BaseController public function store(StoreCreditRequest $request) { - /** @var \App\Models\User $user**/ + /** @var \App\Models\User $user **/ $user = auth()->user(); - // $client = Client::find($request->input('client_id')); - $credit = $this->credit_repository->save($request->all(), CreditFactory::create($user->company()->id, $user->id)); $credit = $credit->service() @@ -506,7 +504,7 @@ class CreditController extends BaseController public function bulk(BulkCreditRequest $request) { - /** @var \App\Models\User $user**/ + /** @var \App\Models\User $user **/ $user = auth()->user(); $action = $request->input('action'); @@ -725,7 +723,7 @@ class CreditController extends BaseController * Update the specified resource in storage. * * @param UploadCreditRequest $request - * @param Credit $client + * @param Credit $credit * @return Response * * diff --git a/app/Http/Controllers/DocumentController.php b/app/Http/Controllers/DocumentController.php index 0d65af5d84..70d4b1e8a1 100644 --- a/app/Http/Controllers/DocumentController.php +++ b/app/Http/Controllers/DocumentController.php @@ -128,7 +128,7 @@ class DocumentController extends BaseController /** * Show the form for editing the specified resource. * - * @param EditDocumentRegquest $request + * @param EditDocumentRequest $request * @param Document $document * @return Response */ diff --git a/app/Http/Controllers/PreviewPurchaseOrderController.php b/app/Http/Controllers/PreviewPurchaseOrderController.php index bdc90f3f8d..6aac31cbac 100644 --- a/app/Http/Controllers/PreviewPurchaseOrderController.php +++ b/app/Http/Controllers/PreviewPurchaseOrderController.php @@ -95,7 +95,7 @@ class PreviewPurchaseOrderController extends BaseController return response()->json(['message' => ctrans('texts.invalid_design_object')], 400); } - $entity_obj = PurchaseOrder::whereId($this->decodePrimaryKey(request()->input('entity_id')))->company()->first(); + $entity_obj = PurchaseOrder::query()->whereId($this->decodePrimaryKey(request()->input('entity_id')))->company()->first(); if (! $entity_obj) { return $this->blankEntity(); diff --git a/app/Http/Controllers/VendorPortal/DocumentController.php b/app/Http/Controllers/VendorPortal/DocumentController.php index 537326b29c..e622106904 100644 --- a/app/Http/Controllers/VendorPortal/DocumentController.php +++ b/app/Http/Controllers/VendorPortal/DocumentController.php @@ -96,7 +96,7 @@ class DocumentController extends Controller public function downloadMultiple(DownloadMultipleDocumentsRequest $request) { /** @var \Illuminate\Database\Eloquent\Collection $documents */ - $documents = Document::whereIn('id', $this->transformKeys($request->file_hash)) + $documents = Document::query()->whereIn('id', $this->transformKeys($request->file_hash)) ->where('company_id', auth()->guard('vendor')->user()->company_id) ->get(); diff --git a/app/Http/Controllers/VendorPortal/PurchaseOrderController.php b/app/Http/Controllers/VendorPortal/PurchaseOrderController.php index 589c7d53dd..775758dc89 100644 --- a/app/Http/Controllers/VendorPortal/PurchaseOrderController.php +++ b/app/Http/Controllers/VendorPortal/PurchaseOrderController.php @@ -203,7 +203,8 @@ class PurchaseOrderController extends Controller public function downloadInvoices($ids) { - $purchase_orders = PurchaseOrder::whereIn('id', $ids) + $purchase_orders = PurchaseOrder::query() + ->whereIn('id', $ids) ->where('vendor_id', auth()->guard('vendor')->user()->vendor_id) ->withTrashed() ->get(); diff --git a/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php b/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php index 96190431d6..102b3634a2 100644 --- a/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php +++ b/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php @@ -19,7 +19,7 @@ class VendorContactHashLoginController extends Controller /** * Logs a user into the client portal using their contact_key * @param string $contact_key The contact key - * @return Auth|Redirect + * @return Auth|\Illuminate\Support\Facades\Redirect */ public function login(string $contact_key) { diff --git a/app/Http/ValidationRules/ValidCreditsPresentRule.php b/app/Http/ValidationRules/ValidCreditsPresentRule.php index 5b662da16a..00979435e3 100644 --- a/app/Http/ValidationRules/ValidCreditsPresentRule.php +++ b/app/Http/ValidationRules/ValidCreditsPresentRule.php @@ -52,7 +52,7 @@ class ValidCreditsPresentRule implements Rule //todo need to ensure the clients credits are here not random ones! if (array_key_exists('credits', $this->input) && is_array($this->input['credits']) && count($this->input['credits']) > 0) { - $credit_collection = Credit::whereIn('id', array_column($this->input['credits'], 'credit_id'))->count(); + $credit_collection = Credit::query()->whereIn('id', array_column($this->input['credits'], 'credit_id'))->count(); return $credit_collection == count($this->input['credits']); } diff --git a/app/Http/ValidationRules/ValidPayableInvoicesRule.php b/app/Http/ValidationRules/ValidPayableInvoicesRule.php index a83eba85c6..93503c7a36 100644 --- a/app/Http/ValidationRules/ValidPayableInvoicesRule.php +++ b/app/Http/ValidationRules/ValidPayableInvoicesRule.php @@ -35,7 +35,7 @@ class ValidPayableInvoicesRule implements Rule $invoices = []; if (is_array($value)) { - $invoices = Invoice::whereIn('id', array_column($value, 'invoice_id'))->company()->get(); + $invoices = Invoice::query()->whereIn('id', array_column($value, 'invoice_id'))->company()->get(); } foreach ($invoices as $invoice) { diff --git a/app/Http/ValidationRules/ValidRefundableInvoices.php b/app/Http/ValidationRules/ValidRefundableInvoices.php index 5c3d57334a..7b4abfce5e 100644 --- a/app/Http/ValidationRules/ValidRefundableInvoices.php +++ b/app/Http/ValidationRules/ValidRefundableInvoices.php @@ -58,7 +58,7 @@ class ValidRefundableInvoices implements Rule $invoices = []; if (is_array($value)) { - $invoices = Invoice::whereIn('id', array_column($this->input['invoices'], 'invoice_id'))->company()->get(); + $invoices = Invoice::query()->whereIn('id', array_column($this->input['invoices'], 'invoice_id'))->company()->get(); } else { return true; } diff --git a/app/Jobs/Bank/MatchBankTransactions.php b/app/Jobs/Bank/MatchBankTransactions.php index bc3c0fc3a2..c4084047df 100644 --- a/app/Jobs/Bank/MatchBankTransactions.php +++ b/app/Jobs/Bank/MatchBankTransactions.php @@ -113,7 +113,7 @@ class MatchBankTransactions implements ShouldQueue } } - return BankTransaction::whereIn('id', $this->bts); + return BankTransaction::query()->whereIn('id', $this->bts); } private function getInvoices(string $invoice_hashed_ids): array diff --git a/app/Jobs/Document/ZipDocuments.php b/app/Jobs/Document/ZipDocuments.php index c713e778e5..393aeec3bb 100644 --- a/app/Jobs/Document/ZipDocuments.php +++ b/app/Jobs/Document/ZipDocuments.php @@ -85,7 +85,7 @@ class ZipDocuments implements ShouldQueue $path = $this->company->file_path(); try { - $documents = Document::whereIn('id', $this->document_ids)->get(); + $documents = Document::query()->whereIn('id', $this->document_ids)->get(); foreach ($documents as $document) { $zipFile->addFromString($this->buildFileName($document), $document->getFile()); diff --git a/app/Jobs/Mail/PaymentFailedMailer.php b/app/Jobs/Mail/PaymentFailedMailer.php index 12f3bc6f02..461b1a01c6 100644 --- a/app/Jobs/Mail/PaymentFailedMailer.php +++ b/app/Jobs/Mail/PaymentFailedMailer.php @@ -81,7 +81,7 @@ class PaymentFailedMailer implements ShouldQueue if ($this->payment_hash) { // $amount = array_sum(array_column($this->payment_hash->invoices(), 'amount')) + $this->payment_hash->fee_total; $amount =$this->payment_hash?->amount_with_fee() ?: 0; - $invoice = Invoice::whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); + $invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); } //iterate through company_users diff --git a/app/Mail/Admin/AutoBillingFailureObject.php b/app/Mail/Admin/AutoBillingFailureObject.php index d72d62ecea..a937aecf25 100644 --- a/app/Mail/Admin/AutoBillingFailureObject.php +++ b/app/Mail/Admin/AutoBillingFailureObject.php @@ -63,7 +63,7 @@ class AutoBillingFailureObject /* Set customized translations _NOW_ */ $t->replace(Ninja::transformTranslations($this->company->settings)); - $this->invoices = Invoice::whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->get(); + $this->invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->get(); $mail_obj = new stdClass; $mail_obj->amount = $this->getAmount(); diff --git a/app/Mail/Engine/InvoiceEmailEngine.php b/app/Mail/Engine/InvoiceEmailEngine.php index debd20eaa6..79826b3a03 100644 --- a/app/Mail/Engine/InvoiceEmailEngine.php +++ b/app/Mail/Engine/InvoiceEmailEngine.php @@ -171,7 +171,7 @@ class InvoiceEmailEngine extends BaseEmailEngine } if (count($expense_ids) > 0) { - $expenses = Expense::whereIn('id', $this->transformKeys($expense_ids)) + $expenses = Expense::query()->whereIn('id', $this->transformKeys($expense_ids)) ->where('invoice_documents', 1) ->cursor() ->each(function ($expense) { @@ -192,7 +192,7 @@ class InvoiceEmailEngine extends BaseEmailEngine } if (count($task_ids) > 0 && $this->invoice->company->invoice_task_documents) { - $tasks = Task::whereIn('id', $this->transformKeys($task_ids)) + $tasks = Task::query()->whereIn('id', $this->transformKeys($task_ids)) ->cursor() ->each(function ($task) { foreach ($task->documents as $document) { diff --git a/app/Models/Account.php b/app/Models/Account.php index 8af6bc7e40..595661a4f5 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -87,6 +87,7 @@ use Laracasts\Presenter\PresentableTrait; * @method static \Illuminate\Database\Eloquent\Builder|Account first() * @method static \Illuminate\Database\Eloquent\Builder|Account with() * @method static \Illuminate\Database\Eloquent\Builder|Account count() + * @method static \Illuminate\Database\Eloquent\Builder|Account where($query) * @property-read \Illuminate\Database\Eloquent\Collection $bank_integrations * @property-read \Illuminate\Database\Eloquent\Collection $companies * @property-read \Illuminate\Database\Eloquent\Collection $company_users @@ -215,7 +216,11 @@ class Account extends BaseModel return $this->hasMany(CompanyUser::class); } - public function owner(): \Illuminate\Database\Eloquent\Relations\HasMany + /** + * Returns the owner of the Account - not a HasMany relation + * @return \App\Models\User | bool + */ + public function owner() { return $this->hasMany(CompanyUser::class)->where('is_owner', true)->first() ? $this->hasMany(CompanyUser::class)->where('is_owner', true)->first()->user : false; } diff --git a/app/Models/BankTransaction.php b/app/Models/BankTransaction.php index 2772e0d146..29dd6eb430 100644 --- a/app/Models/BankTransaction.php +++ b/app/Models/BankTransaction.php @@ -156,7 +156,7 @@ class BankTransaction extends BaseModel public function account(): \Illuminate\Database\Eloquent\Relations\BelongsTo { - return $this->belongsTo(Account::class)->withTrashed(); + return $this->belongsTo(Account::class); } public function payment(): \Illuminate\Database\Eloquent\Relations\BelongsTo diff --git a/app/Models/BaseModel.php b/app/Models/BaseModel.php index 05fe216aa8..60071ce53b 100644 --- a/app/Models/BaseModel.php +++ b/app/Models/BaseModel.php @@ -35,7 +35,11 @@ use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundExceptio * @property int $id * @property int $user_id * @property int $assigned_user_id + * @method BaseModel service() * @property \App\Models\Company $company + * @method static BaseModel find($value) + * @method BaseModel company() + * @method static \Illuminate\Database\Eloquent\Builder|BaseModel company() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|Illuminate\Database\Eloquent\Relations\BelongsTo|\Awobaz\Compoships\Database\Eloquent\Relations\BelongsTo|\App\Models\Company company() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|Illuminate\Database\Eloquent\Relations\HasMany|BaseModel orderBy() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel exclude($columns) @@ -43,26 +47,23 @@ use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundExceptio * @method static \Illuminate\Database\Eloquent\Builder|BaseModel newModelQuery($query) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel newQuery($query) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel query() - * @method static \Illuminate\Database\Eloquent\Builder|BaseModel exclude(array $excludeable) - * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|\Illuminate\Database\Query\Builder withTrashed(bool $withTrashed = true) - * @method static \Illuminate\Database\Eloquent\Builder|BaseModel scopeExclude($query) - * @method static BaseModel find($value) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel whereId($query) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel whereIn($query) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel where($query) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel count() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel create($query) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel insert($query) - * @method BaseModel service() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel orderBy($column, $direction) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel invitations() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel whereHas($query) * @property-read \Illuminate\Database\Eloquent\Collection $invitations * @property-read int|null $invitations_count - * @method static \Illuminate\Database\Eloquent\Builder company() * @method int companyId() * @method createInvitations() * @method Builder scopeCompany(Builder $builder) + * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|\Illuminate\Database\Query\Builder withTrashed(bool $withTrashed = true) + * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|\Illuminate\Database\Query\Builder onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|\Illuminate\Database\Query\Builder withoutTrashed() * @mixin \Eloquent * @mixin \Illuminate\Database\Eloquent\Builder */ diff --git a/app/Models/Company.php b/app/Models/Company.php index d928507598..f1fbea97fd 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -199,6 +199,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; * @property-read \Illuminate\Database\Eloquent\Collection $vendors * @property-read int|null $vendors_count * @property-read \Illuminate\Database\Eloquent\Collection $webhooks + * @method static \Illuminate\Database\Eloquent\Builder|Company where($query) * @property-read int|null $webhooks_count * @property int $calculate_taxes * @property mixed $tax_data @@ -439,7 +440,7 @@ class Company extends BaseModel return $this->encodePrimaryKey($this->id); } - public function account() + public function account(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Account::class); } @@ -449,7 +450,7 @@ class Company extends BaseModel return $this->hasMany(ClientContact::class)->withTrashed(); } - public function users() + public function users(): \Illuminate\Database\Eloquent\Relations\HasManyThrough { return $this->hasManyThrough(User::class, CompanyUser::class, 'company_id', 'id', 'id', 'user_id')->withTrashed(); } diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php index aeaca5d2ce..e4c2aa5505 100644 --- a/app/Models/CompanyGateway.php +++ b/app/Models/CompanyGateway.php @@ -51,8 +51,8 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property-read \App\Models\Company $company * @property-read \App\Models\Gateway $gateway * @property-read mixed $hashed_id + * @method getConfigField(string $field) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel company() - * @method static \Illuminate\Database\Eloquent\Builder|BaseModel exclude($columns) * @method static \Illuminate\Database\Eloquent\Builder|CompanyGateway filter(\App\Filters\QueryFilters $filters) * @method static \Illuminate\Database\Eloquent\Builder|CompanyGateway newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|CompanyGateway newQuery() diff --git a/app/Models/Invoice.php b/app/Models/Invoice.php index 018d8722e8..f0b0f37ea2 100644 --- a/app/Models/Invoice.php +++ b/app/Models/Invoice.php @@ -678,7 +678,7 @@ class Invoice extends BaseModel } } - return Expense::whereIn('id', $this->transformKeys($expense_ids)) + return Expense::query()->whereIn('id', $this->transformKeys($expense_ids)) ->where('invoice_documents', 1) ->where('company_id', $this->company_id) ->cursor(); @@ -696,7 +696,7 @@ class Invoice extends BaseModel } } - return Task::whereIn('id', $this->transformKeys($task_ids)) + return Task::query()->whereIn('id', $this->transformKeys($task_ids)) ->whereHas('company', function ($query) { $query->where('invoice_task_documents', 1); }) diff --git a/app/Models/PurchaseOrder.php b/app/Models/PurchaseOrder.php index e634636acd..3639469776 100644 --- a/app/Models/PurchaseOrder.php +++ b/app/Models/PurchaseOrder.php @@ -86,29 +86,19 @@ use Illuminate\Support\Facades\Storage; * @property int|null $updated_at * @property int|null $expense_id * @property int|null $currency_id - * @property-read \Illuminate\Database\Eloquent\Collection $activities * @property-read int|null $activities_count * @property-read \App\Models\User|null $assigned_user * @property-read \App\Models\Client|null $client * @property-read \App\Models\Company $company - * @property-read \Illuminate\Database\Eloquent\Collection $documents * @property-read int|null $documents_count * @property-read \App\Models\Expense|null $expense * @property-read mixed $hashed_id - * @property-read \Illuminate\Database\Eloquent\Collection $history - * @property-read int|null $history_count - * @property-read \Illuminate\Database\Eloquent\Collection $invitations - * @property-read int|null $invitations_count * @property-read \App\Models\Invoice|null $invoice - * @property-read \Illuminate\Database\Eloquent\Collection $invoices - * @property-read int|null $invoices_count - * @property-read \Illuminate\Database\Eloquent\Collection $payments - * @property-read int|null $payments_count * @property-read \App\Models\Project|null $project * @property-read \App\Models\User $user * @property \App\Models\Vendor|null $vendor - * @method static \Illuminate\Database\Eloquent\Builder|BaseModel company() - * @method static \Illuminate\Database\Eloquent\Builder|BaseModel exclude($columns) + * @method static \Illuminate\Database\Eloquent\Builder|PurchaseOrder company() + * @method static \Illuminate\Database\Eloquent\Builder|PurchaseOrder exclude($columns) * @method static \Database\Factories\PurchaseOrderFactory factory($count = null, $state = []) * @method static \Illuminate\Database\Eloquent\Builder|PurchaseOrder filter(\App\Filters\QueryFilters $filters) * @method static \Illuminate\Database\Eloquent\Builder|PurchaseOrder newModelQuery() diff --git a/app/Models/Quote.php b/app/Models/Quote.php index da496f7d63..38a3443460 100644 --- a/app/Models/Quote.php +++ b/app/Models/Quote.php @@ -108,7 +108,9 @@ use Laracasts\Presenter\PresentableTrait; * @property-read \Illuminate\Database\Eloquent\Collection $documents * @property-read \Illuminate\Database\Eloquent\Collection $history * @property-read \Illuminate\Database\Eloquent\Collection $invitations + * * @mixin \Eloquent + * @mixin \Illuminate\Database\Eloquent\Builder */ class Quote extends BaseModel { diff --git a/app/Models/Traits/Excludable.php b/app/Models/Traits/Excludable.php index 272c5e7cc8..d4da440d35 100644 --- a/app/Models/Traits/Excludable.php +++ b/app/Models/Traits/Excludable.php @@ -14,6 +14,8 @@ namespace App\Models\Traits; use Illuminate\Support\Facades\Schema; /** + * @method static Builder scopeExclude(Builder $builder) + * @method static Builder exclude(Builder $builder) * @template TModelClass of \Illuminate\Database\Eloquent\Model * @extends \Illuminate\Database\Eloquent\Builder * @mixin \Illuminate\Database\Eloquent\Builder @@ -33,6 +35,10 @@ trait Excludable /** * Exclude an array of elements from the result. + * + * @method static \Illuminate\Database\Eloquent\Builder exclude($columns) + * @method static \Illuminate\Database\Eloquent\Builder exclude($columns) + * * @param \Illuminate\Database\Eloquent\Builder $query * @param array $columns * diff --git a/app/Models/User.php b/app/Models/User.php index db2f875064..7e1784d941 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -280,7 +280,7 @@ class User extends Authenticatable implements MustVerifyEmail * * @return \App\Models\Company $company */ - public function company(): Company + public function company(): \App\Models\Company { return $this->getCompany(); } diff --git a/app/PaymentDrivers/Authorize/AuthorizeTransaction.php b/app/PaymentDrivers/Authorize/AuthorizeTransaction.php index 7f4511a186..20f184a17f 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeTransaction.php +++ b/app/PaymentDrivers/Authorize/AuthorizeTransaction.php @@ -60,7 +60,7 @@ class AuthorizeTransaction if ($this->authorize->payment_hash->data) { $invoice_numbers = collect($this->authorize->payment_hash->data->invoices)->pluck('invoice_number')->implode(','); - $invObj = Invoice::whereIn('id', $this->transformKeys(array_column($this->authorize->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); + $invObj = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->authorize->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); $po_numbers = $invObj->pluck('po_number')->implode(','); diff --git a/app/PaymentDrivers/Authorize/ChargePaymentProfile.php b/app/PaymentDrivers/Authorize/ChargePaymentProfile.php index 65fcb33590..ca032fbedd 100644 --- a/app/PaymentDrivers/Authorize/ChargePaymentProfile.php +++ b/app/PaymentDrivers/Authorize/ChargePaymentProfile.php @@ -56,7 +56,7 @@ class ChargePaymentProfile if ($this->authorize->payment_hash->data) { $invoice_numbers = collect($this->authorize->payment_hash->data->invoices)->pluck('invoice_number')->implode(','); - $invObj = Invoice::whereIn('id', $this->transformKeys(array_column($this->authorize->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); + $invObj = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->authorize->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); $po_numbers = $invObj->pluck('po_number')->implode(','); diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index 632c8c36e1..fcfd766837 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -279,7 +279,7 @@ class BaseDriver extends AbstractPaymentDriver public function attachInvoices(Payment $payment, PaymentHash $payment_hash): Payment { $paid_invoices = $payment_hash->invoices(); - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($paid_invoices, 'invoice_id')))->withTrashed()->get(); + $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($paid_invoices, 'invoice_id')))->withTrashed()->get(); $payment->invoices()->sync($invoices); $payment->service()->applyNumber()->save(); @@ -392,7 +392,7 @@ class BaseDriver extends AbstractPaymentDriver $fee_total = $this->payment_hash->fee_total; /*Hydrate invoices*/ - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($payment_invoices, 'invoice_id')))->withTrashed()->get(); + $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($payment_invoices, 'invoice_id')))->withTrashed()->get(); $invoices->each(function ($invoice) { if (collect($invoice->line_items)->contains('type_id', '3')) { @@ -410,7 +410,7 @@ class BaseDriver extends AbstractPaymentDriver */ public function unWindGatewayFees(PaymentHash $payment_hash) { - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); + $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); $invoices->each(function ($invoice) { $invoice->service()->removeUnpaidGatewayFees(); @@ -522,7 +522,7 @@ class BaseDriver extends AbstractPaymentDriver $nmo->company = $this->client->company; $nmo->settings = $this->client->company->settings; - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); + $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); $invoices->each(function ($invoice) { $invoice->service()->deletePdf(); @@ -567,7 +567,7 @@ class BaseDriver extends AbstractPaymentDriver $nmo->company = $this->client->company; $nmo->settings = $this->client->company->settings; - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); + $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->payment_hash->invoices(), 'invoice_id')))->withTrashed()->get(); $invoices->each(function ($invoice) { $invoice->service()->deletePdf(); diff --git a/app/PaymentDrivers/BraintreePaymentDriver.php b/app/PaymentDrivers/BraintreePaymentDriver.php index b9c2db92b3..a92ae417f7 100644 --- a/app/PaymentDrivers/BraintreePaymentDriver.php +++ b/app/PaymentDrivers/BraintreePaymentDriver.php @@ -238,7 +238,7 @@ class BraintreePaymentDriver extends BaseDriver { $amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total; - $invoice = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); + $invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); if ($invoice) { $description = "Invoice {$invoice->number} for {$amount} for client {$this->client->present()->name()}"; diff --git a/app/PaymentDrivers/CheckoutComPaymentDriver.php b/app/PaymentDrivers/CheckoutComPaymentDriver.php index 7c65fadc85..bfeee03569 100644 --- a/app/PaymentDrivers/CheckoutComPaymentDriver.php +++ b/app/PaymentDrivers/CheckoutComPaymentDriver.php @@ -324,7 +324,7 @@ class CheckoutComPaymentDriver extends BaseDriver public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash) { $amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total; - $invoice = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); + $invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); $this->init(); diff --git a/app/PaymentDrivers/GoCardless/ACH.php b/app/PaymentDrivers/GoCardless/ACH.php index 9819a08b4f..2f1c5f6a0b 100644 --- a/app/PaymentDrivers/GoCardless/ACH.php +++ b/app/PaymentDrivers/GoCardless/ACH.php @@ -163,7 +163,7 @@ class ACH implements MethodInterface { $this->go_cardless->ensureMandateIsReady($request->source); - $invoice = Invoice::whereIn('id', $this->transformKeys(array_column($this->go_cardless->payment_hash->invoices(), 'invoice_id'))) + $invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->go_cardless->payment_hash->invoices(), 'invoice_id'))) ->withTrashed() ->first(); diff --git a/app/PaymentDrivers/GoCardless/DirectDebit.php b/app/PaymentDrivers/GoCardless/DirectDebit.php index 94328a537e..48274891e8 100644 --- a/app/PaymentDrivers/GoCardless/DirectDebit.php +++ b/app/PaymentDrivers/GoCardless/DirectDebit.php @@ -257,7 +257,7 @@ class DirectDebit implements MethodInterface { $this->go_cardless->ensureMandateIsReady($request->source); - $invoice = Invoice::whereIn('id', $this->transformKeys(array_column($this->go_cardless->payment_hash->invoices(), 'invoice_id'))) + $invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->go_cardless->payment_hash->invoices(), 'invoice_id'))) ->withTrashed() ->first(); diff --git a/app/PaymentDrivers/GoCardless/SEPA.php b/app/PaymentDrivers/GoCardless/SEPA.php index 4ea4886182..458b34d9e2 100644 --- a/app/PaymentDrivers/GoCardless/SEPA.php +++ b/app/PaymentDrivers/GoCardless/SEPA.php @@ -162,7 +162,7 @@ class SEPA implements MethodInterface { $this->go_cardless->ensureMandateIsReady($request->source); - $invoice = Invoice::whereIn('id', $this->transformKeys(array_column($this->go_cardless->payment_hash->invoices(), 'invoice_id'))) + $invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($this->go_cardless->payment_hash->invoices(), 'invoice_id'))) ->withTrashed() ->first(); diff --git a/app/PaymentDrivers/GoCardlessPaymentDriver.php b/app/PaymentDrivers/GoCardlessPaymentDriver.php index 2a251a5b58..c798c5c1e9 100644 --- a/app/PaymentDrivers/GoCardlessPaymentDriver.php +++ b/app/PaymentDrivers/GoCardlessPaymentDriver.php @@ -327,7 +327,7 @@ class GoCardlessPaymentDriver extends BaseDriver ); if ($billing_request->status === 'fulfilled') { - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($hash->invoices(), 'invoice_id')))->withTrashed()->get(); + $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($hash->invoices(), 'invoice_id')))->withTrashed()->get(); $this->client = $invoices->first()->client; diff --git a/app/PaymentDrivers/MolliePaymentDriver.php b/app/PaymentDrivers/MolliePaymentDriver.php index 247c698871..cc263acfcf 100644 --- a/app/PaymentDrivers/MolliePaymentDriver.php +++ b/app/PaymentDrivers/MolliePaymentDriver.php @@ -194,7 +194,7 @@ class MolliePaymentDriver extends BaseDriver public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash) { $amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total; - $invoice = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); + $invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); if ($invoice) { $description = "Invoice {$invoice->number} for {$amount} for client {$this->client->present()->name()}"; diff --git a/app/PaymentDrivers/SquarePaymentDriver.php b/app/PaymentDrivers/SquarePaymentDriver.php index bb2e9f6fef..cdae15876a 100644 --- a/app/PaymentDrivers/SquarePaymentDriver.php +++ b/app/PaymentDrivers/SquarePaymentDriver.php @@ -114,7 +114,7 @@ class SquarePaymentDriver extends BaseDriver $amount = array_sum(array_column($payment_hash->invoices(), 'amount')) + $payment_hash->fee_total; $amount = $this->convertAmount($amount); - $invoice = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); + $invoice = Invoice::query()->whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id')))->withTrashed()->first(); if ($invoice) { $description = "Invoice {$invoice->number} for {$amount} for client {$this->client->present()->name()}"; diff --git a/app/Repositories/BankTransactionRepository.php b/app/Repositories/BankTransactionRepository.php index 4130e72333..e16ba4f0fd 100644 --- a/app/Repositories/BankTransactionRepository.php +++ b/app/Repositories/BankTransactionRepository.php @@ -52,7 +52,7 @@ class BankTransactionRepository extends BaseRepository $bt->payment_id = null; } - $e = Expense::whereIn('id', $this->transformKeys(explode(",", $bt->expense_id))) + $e = Expense::query()->whereIn('id', $this->transformKeys(explode(",", $bt->expense_id))) ->cursor() ->each(function ($expense){ diff --git a/app/Repositories/Migration/PaymentMigrationRepository.php b/app/Repositories/Migration/PaymentMigrationRepository.php index 00bf928ae3..683355f423 100644 --- a/app/Repositories/Migration/PaymentMigrationRepository.php +++ b/app/Repositories/Migration/PaymentMigrationRepository.php @@ -120,7 +120,7 @@ class PaymentMigrationRepository extends BaseRepository $invoice_totals = array_sum(array_column($data['invoices'], 'amount')); $refund_totals = array_sum(array_column($data['invoices'], 'refunded')); - $invoices = Invoice::whereIn('id', array_column($data['invoices'], 'invoice_id'))->withTrashed()->get(); + $invoices = Invoice::query()->whereIn('id', array_column($data['invoices'], 'invoice_id'))->withTrashed()->get(); $payment->invoices()->saveMany($invoices); // 1:1 relationship so this is ok @@ -150,7 +150,7 @@ class PaymentMigrationRepository extends BaseRepository /** @var float $credit_totals **/ $credit_totals = array_sum(array_column($data['credits'], 'amount')); - $credits = Credit::whereIn('id', array_column($data['credits'], 'credit_id'))->withTrashed()->get(); + $credits = Credit::query()->whereIn('id', array_column($data['credits'], 'credit_id'))->withTrashed()->get(); $payment->credits()->saveMany($credits); diff --git a/app/Repositories/PaymentRepository.php b/app/Repositories/PaymentRepository.php index 4400e66155..48fdd4a8e5 100644 --- a/app/Repositories/PaymentRepository.php +++ b/app/Repositories/PaymentRepository.php @@ -170,7 +170,7 @@ class PaymentRepository extends BaseRepository if (array_key_exists('credits', $data) && is_array($data['credits'])) { $credit_totals = array_sum(array_column($data['credits'], 'amount')); - $credits = Credit::whereIn('id', array_column($data['credits'], 'credit_id'))->get(); + $credits = Credit::query()->whereIn('id', array_column($data['credits'], 'credit_id'))->get(); //todo optimize into a single query foreach ($data['credits'] as $paid_credit) { diff --git a/app/Services/ClientPortal/InstantPayment.php b/app/Services/ClientPortal/InstantPayment.php index c9366ad83b..91832d9f20 100644 --- a/app/Services/ClientPortal/InstantPayment.php +++ b/app/Services/ClientPortal/InstantPayment.php @@ -60,7 +60,7 @@ class InstantPayment * ['invoice_id' => xxx, 'amount' => 22.00] */ $payable_invoices = collect($this->request->payable_invoices); - $invoices = Invoice::whereIn('id', $this->transformKeys($payable_invoices->pluck('invoice_id')->toArray()))->withTrashed()->get(); + $invoices = Invoice::query()->whereIn('id', $this->transformKeys($payable_invoices->pluck('invoice_id')->toArray()))->withTrashed()->get(); $invoices->each(function ($invoice) { $invoice->service() diff --git a/app/Services/Credit/CreateInvitations.php b/app/Services/Credit/CreateInvitations.php index b00a177e20..cf413f2444 100644 --- a/app/Services/Credit/CreateInvitations.php +++ b/app/Services/Credit/CreateInvitations.php @@ -42,7 +42,8 @@ class CreateInvitations extends AbstractService } $contacts->each(function ($contact) { - $invitation = CreditInvitation::whereCompanyId($this->credit->company_id) + $invitation = CreditInvitation::query() + ->where('company_id', $this->credit->company_id) ->whereClientContactId($contact->id) ->whereCreditId($this->credit->id) ->withTrashed() diff --git a/app/Services/Email/EmailDefaults.php b/app/Services/Email/EmailDefaults.php index 65a104b88f..a374ddfa35 100644 --- a/app/Services/Email/EmailDefaults.php +++ b/app/Services/Email/EmailDefaults.php @@ -361,7 +361,7 @@ class EmailDefaults } if (count($expense_ids) > 0) { - Expense::whereIn('id', $this->transformKeys($expense_ids)) + Expense::query()->whereIn('id', $this->transformKeys($expense_ids)) ->where('invoice_documents', 1) ->cursor() ->each(function ($expense) { @@ -370,7 +370,7 @@ class EmailDefaults } if (count($task_ids) > 0 && $this->email->company->invoice_task_documents) { - Task::whereIn('id', $this->transformKeys($task_ids)) + Task::query()->whereIn('id', $this->transformKeys($task_ids)) ->cursor() ->each(function ($task) { $this->email->email_object->documents = array_merge($this->email->email_object->documents, $task->documents->pluck('id')->toArray()); diff --git a/app/Services/Email/EmailMailable.php b/app/Services/Email/EmailMailable.php index d25ae3b365..399b0629e9 100644 --- a/app/Services/Email/EmailMailable.php +++ b/app/Services/Email/EmailMailable.php @@ -57,7 +57,7 @@ class EmailMailable extends Mailable */ public function content() { - $links = Document::whereIn('id', $this->email_object->documents) + $links = Document::query()->whereIn('id', $this->email_object->documents) ->where('size', '>', $this->max_attachment_size) ->cursor() ->map(function ($document) { @@ -94,7 +94,7 @@ class EmailMailable extends Mailable return Attachment::fromData(fn () => base64_decode($file['file']), $file['name']); }); - $documents = Document::whereIn('id', $this->email_object->documents) + $documents = Document::query()->whereIn('id', $this->email_object->documents) ->where('size', '<', $this->max_attachment_size) ->cursor() ->map(function ($document) { diff --git a/app/Services/Invoice/InvoiceService.php b/app/Services/Invoice/InvoiceService.php index 8558c0128e..0adec81b6c 100644 --- a/app/Services/Invoice/InvoiceService.php +++ b/app/Services/Invoice/InvoiceService.php @@ -541,8 +541,8 @@ class InvoiceService 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::query()->whereIn('id', $tasks->pluck('task_id'))->update(['invoice_id' => $this->invoice->id]); + Expense::query()->whereIn('id', $tasks->pluck('expense_id'))->update(['invoice_id' => $this->invoice->id]); return $this; } diff --git a/app/Services/Payment/UpdateInvoicePayment.php b/app/Services/Payment/UpdateInvoicePayment.php index 882cba3e95..e0e793bd6e 100644 --- a/app/Services/Payment/UpdateInvoicePayment.php +++ b/app/Services/Payment/UpdateInvoicePayment.php @@ -38,7 +38,7 @@ class UpdateInvoicePayment { $paid_invoices = $this->payment_hash->invoices(); - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($paid_invoices, 'invoice_id')))->withTrashed()->get(); + $invoices = Invoice::query()->whereIn('id', $this->transformKeys(array_column($paid_invoices, 'invoice_id')))->withTrashed()->get(); $client = $this->payment->client; diff --git a/app/Services/Quote/CreateInvitations.php b/app/Services/Quote/CreateInvitations.php index 34468adaac..8ba5090c39 100644 --- a/app/Services/Quote/CreateInvitations.php +++ b/app/Services/Quote/CreateInvitations.php @@ -41,7 +41,8 @@ class CreateInvitations } $contacts->each(function ($contact) { - $invitation = QuoteInvitation::whereCompanyId($this->quote->company_id) + $invitation = QuoteInvitation::query() + ->where('company_id',$this->quote->company_id) ->whereClientContactId($contact->id) ->whereQuoteId($this->quote->id) ->withTrashed() diff --git a/app/Services/Subscription/SubscriptionService.php b/app/Services/Subscription/SubscriptionService.php index 782f08446b..efb3035286 100644 --- a/app/Services/Subscription/SubscriptionService.php +++ b/app/Services/Subscription/SubscriptionService.php @@ -574,7 +574,7 @@ class SubscriptionService $credit = false; /* Get last invoice */ - $last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id) + $last_invoice = Invoice::query()->where('subscription_id', $recurring_invoice->subscription_id) ->where('client_id', $recurring_invoice->client_id) ->where('is_proforma', 0) ->where('is_deleted', 0) @@ -1166,7 +1166,7 @@ class SubscriptionService $keys = $this->transformKeys(explode(",", $this->subscription->product_ids)); if (is_array($keys)) { - return Product::whereIn('id', $keys)->get(); + return Product::query()->whereIn('id', $keys)->get(); } else { return Product::where('id', $keys)->get(); } @@ -1186,7 +1186,7 @@ class SubscriptionService $keys = $this->transformKeys(explode(",", $this->subscription->recurring_product_ids)); if (is_array($keys)) { - return Product::whereIn('id', $keys)->get(); + return Product::query()->whereIn('id', $keys)->get(); } else { return Product::where('id', $keys)->get(); } @@ -1207,7 +1207,7 @@ class SubscriptionService $keys = $this->transformKeys(explode(",", $this->subscription->optional_product_ids)); if (is_array($keys)) { - return Product::whereIn('id', $keys)->get(); + return Product::query()->whereIn('id', $keys)->get(); } else { return Product::where('id', $keys)->get(); } @@ -1227,7 +1227,7 @@ class SubscriptionService $keys = $this->transformKeys(explode(",", $this->subscription->optional_recurring_product_ids)); if (is_array($keys)) { - return Product::whereIn('id', $keys)->get(); + return Product::query()->whereIn('id', $keys)->get(); } else { return Product::where('id', $keys)->get(); } diff --git a/app/Utils/Traits/GeneratesConvertedQuoteCounter.php b/app/Utils/Traits/GeneratesConvertedQuoteCounter.php index 06cf6fa365..314b994e1b 100644 --- a/app/Utils/Traits/GeneratesConvertedQuoteCounter.php +++ b/app/Utils/Traits/GeneratesConvertedQuoteCounter.php @@ -69,7 +69,7 @@ trait GeneratesConvertedQuoteCounter $number = $this->applyNumberPattern($invoice, $number, $pattern); - $check = Invoice::whereCompanyId($client->company_id)->whereNumber($number)->withTrashed()->exists(); + $check = Invoice::query()->whereCompanyId($client->company_id)->whereNumber($number)->withTrashed()->exists(); if ($check) { return false; diff --git a/database/migrations/2023_08_06_070205_create_view_dashboard_permission_migration.php b/database/migrations/2023_08_06_070205_create_view_dashboard_permission_migration.php new file mode 100644 index 0000000000..ae8dbe4456 --- /dev/null +++ b/database/migrations/2023_08_06_070205_create_view_dashboard_permission_migration.php @@ -0,0 +1,45 @@ +cursor()->each(function ($cu) { + $permissions = $cu->permissions; + + if (!$permissions || strlen($permissions) == 0) { + $permissions = 'view_dashboard'; + $cu->permissions = $permissions; + $cu->save(); + } else { + $permissions_array = explode(',', $permissions); + + $permissions_array[] = 'view_dashboard'; + + $modified_permissions_string = implode(",", $permissions_array); + + $cu->permissions = $modified_permissions_string; + $cu->save(); + } + }); + + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + } +}; diff --git a/phpstan.neon b/phpstan.neon index 4514c5ecc8..42ed898676 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -18,4 +18,5 @@ parameters: - '#Call to an undefined method [a-zA-Z0-9\\_]+::company\(\)#' - '#Call to an undefined method [a-zA-Z0-9\\_]+::entityFilter\(\)#' - '#Call to an undefined method [a-zA-Z0-9\\_]+::withTrashed\(\)#' + - '#Call to an undefined method [a-zA-Z0-9\\_]+::exclude\(\)#' - '#Undefined method#' \ No newline at end of file From 98efe4b4a997f2e05845d59b98f204d141e12a37 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sun, 6 Aug 2023 17:03:48 +1000 Subject: [PATCH 03/33] Migration for view_dashboard permission --- app/Models/BaseModel.php | 1 - app/Models/Traits/Excludable.php | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/app/Models/BaseModel.php b/app/Models/BaseModel.php index 60071ce53b..cf4e39b2e3 100644 --- a/app/Models/BaseModel.php +++ b/app/Models/BaseModel.php @@ -38,7 +38,6 @@ use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundExceptio * @method BaseModel service() * @property \App\Models\Company $company * @method static BaseModel find($value) - * @method BaseModel company() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel company() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|Illuminate\Database\Eloquent\Relations\BelongsTo|\Awobaz\Compoships\Database\Eloquent\Relations\BelongsTo|\App\Models\Company company() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|Illuminate\Database\Eloquent\Relations\HasMany|BaseModel orderBy() diff --git a/app/Models/Traits/Excludable.php b/app/Models/Traits/Excludable.php index d4da440d35..e310117936 100644 --- a/app/Models/Traits/Excludable.php +++ b/app/Models/Traits/Excludable.php @@ -14,8 +14,8 @@ namespace App\Models\Traits; use Illuminate\Support\Facades\Schema; /** - * @method static Builder scopeExclude(Builder $builder) - * @method static Builder exclude(Builder $builder) + * @method static Builder scopeExclude(array $columns) + * @method static Builder exclude(array $columns) * @template TModelClass of \Illuminate\Database\Eloquent\Model * @extends \Illuminate\Database\Eloquent\Builder * @mixin \Illuminate\Database\Eloquent\Builder From 68ce3be42bd0549a838e160b1ea613b3f4fa3536 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sun, 6 Aug 2023 17:35:19 +1000 Subject: [PATCH 04/33] Updates for static analysis --- app/Export/CSV/ProductSalesExport.php | 2 +- app/Filters/QueryFilters.php | 10 +++-- .../PreviewPurchaseOrderController.php | 1 + app/Http/Controllers/TaskController.php | 31 +++++++++----- .../VendorContactHashLoginController.php | 4 ++ app/Http/Controllers/WebhookController.php | 19 +++++++-- app/Http/Livewire/BillingPortalPurchase.php | 1 - .../Statements/CreateStatementRequest.php | 2 +- .../Credit/UniqueCreditNumberRule.php | 2 +- .../Invoice/UniqueInvoiceNumberRule.php | 2 +- .../Payment/ValidRefundableRequest.php | 5 +-- .../Quote/UniqueQuoteNumberRule.php | 2 +- .../UniqueRecurringInvoiceNumberRule.php | 2 +- .../UniqueRecurringQuoteNumberRule.php | 2 +- app/Import/Providers/BaseImport.php | 3 +- app/Jobs/Bank/ProcessBankTransactions.php | 2 +- app/Jobs/Company/CompanyExport.php | 10 ++--- app/Jobs/Util/Import.php | 6 +-- app/Models/BaseModel.php | 3 ++ app/Models/Client.php | 41 ++++++------------- app/Models/PurchaseOrder.php | 2 + app/Observers/CompanyGatewayObserver.php | 2 +- app/Repositories/ActivityRepository.php | 2 +- app/Repositories/BaseRepository.php | 2 +- app/Repositories/CreditRepository.php | 2 +- app/Repositories/InvoiceRepository.php | 2 +- .../Migration/InvoiceMigrationRepository.php | 4 +- .../Migration/PaymentMigrationRepository.php | 2 +- app/Repositories/PaymentRepository.php | 2 +- app/Repositories/PurchaseOrderRepository.php | 6 +-- app/Repositories/QuoteRepository.php | 2 +- app/Repositories/TaskStatusRepository.php | 8 ++-- app/Repositories/UserRepository.php | 8 ++-- app/Services/Bank/BankMatchingService.php | 2 +- app/Services/Bank/BankService.php | 2 +- app/Services/Bank/ProcessBankRules.php | 4 +- app/Services/Client/ClientService.php | 4 +- app/Services/Client/Merge.php | 2 +- app/Services/ClientPortal/InstantPayment.php | 2 +- app/Services/Credit/CreateInvitations.php | 2 +- app/Services/Invoice/AutoBillInvoice.php | 2 +- app/Services/Invoice/CreateInvitations.php | 4 +- app/Services/Invoice/HandleRestore.php | 2 +- app/Services/Invoice/HandleReversal.php | 2 +- app/Services/Payment/DeletePayment.php | 2 +- .../PurchaseOrder/CreateInvitations.php | 4 +- .../PurchaseOrder/PurchaseOrderInventory.php | 2 +- app/Services/Quote/CreateInvitations.php | 2 +- .../Recurring/CreateRecurringInvitations.php | 4 +- app/Services/Recurring/UpdatePrice.php | 2 +- app/Services/Report/ClientBalanceReport.php | 2 +- app/Services/Report/ClientSalesReport.php | 2 +- app/Services/Report/ProfitLoss.php | 4 +- .../Subscription/SubscriptionService.php | 24 +++++------ app/Utils/TemplateEngine.php | 8 ++-- ...00_update_gateway_table_visible_column.php | 2 +- ..._remove_null_values_in_countries_table.php | 4 +- .../2021_03_08_205030_add_russian_lang.php | 2 +- ...21_04_12_095424_stripe_connect_gateway.php | 4 +- ...dd_property_to_checkout_gateway_config.php | 4 +- ...152940_make_braintree_provider_visible.php | 2 +- .../2021_05_05_014713_activate_we_pay.php | 2 +- ..._make_documents_assigned_user_nullable.php | 4 +- ...085821_activate_payfast_payment_driver.php | 2 +- ...21_08_05_235942_add_zelle_payment_type.php | 2 +- .../2021_09_23_100629_add_currencies.php | 2 +- ...dd_required_client_registration_fields.php | 2 +- .../2022_01_19_232436_add_kyd_currency.php | 2 +- ...5411_update_stripe_apple_domain_config.php | 2 +- ..._09_21_012417_add_threeds_to_braintree.php | 2 +- ..._11_22_215618_lock_tasks_when_invoiced.php | 2 +- .../2023_03_10_100629_add_currencies.php | 2 +- ...1_053933_tax_calculations_for_invoices.php | 2 +- ..._currency_format_for_indonesian_rupiah.php | 2 +- ...te_view_dashboard_permission_migration.php | 2 +- phpstan.neon | 1 - tests/Feature/BankTransactionApiTest.php | 2 +- tests/Feature/ClientTest.php | 2 +- tests/Feature/CompanyTest.php | 2 +- 79 files changed, 175 insertions(+), 158 deletions(-) diff --git a/app/Export/CSV/ProductSalesExport.php b/app/Export/CSV/ProductSalesExport.php index 72017220d5..2c9d170852 100644 --- a/app/Export/CSV/ProductSalesExport.php +++ b/app/Export/CSV/ProductSalesExport.php @@ -85,7 +85,7 @@ class ProductSalesExport extends BaseExport $t = app('translator'); $t->replace(Ninja::transformTranslations($this->company->settings)); - $this->products = Product::where('company_id', $this->company->id)->withTrashed()->get(); + $this->products = Product::query()->where('company_id', $this->company->id)->withTrashed()->get(); //load the CSV document from a string $this->csv = Writer::createFromString(); diff --git a/app/Filters/QueryFilters.php b/app/Filters/QueryFilters.php index 1f8f1ce420..e58f88c8c3 100644 --- a/app/Filters/QueryFilters.php +++ b/app/Filters/QueryFilters.php @@ -72,8 +72,8 @@ abstract class QueryFilters /** * Apply the filters to the builder. * - * @param Builder $builder - * @return Builder + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return \Illuminate\Database\Eloquent\Builder */ public function apply(Builder $builder) { @@ -239,7 +239,11 @@ abstract class QueryFilters } } - + /** + * + * @param string $value + * @return \Illuminate\Database\Eloquent\Builder + */ public function is_deleted($value = 'true') { if ($value == 'true') { diff --git a/app/Http/Controllers/PreviewPurchaseOrderController.php b/app/Http/Controllers/PreviewPurchaseOrderController.php index 6aac31cbac..74b73b5618 100644 --- a/app/Http/Controllers/PreviewPurchaseOrderController.php +++ b/app/Http/Controllers/PreviewPurchaseOrderController.php @@ -181,6 +181,7 @@ class PreviewPurchaseOrderController extends BaseController DB::connection(config('database.default'))->beginTransaction(); if ($request->has('entity_id')) { + /** @var \Illuminate\Database\Eloquent\Builder|\App\Models\PurchaseOrder $entity_obj|\Illuminate\Database\Eloquent\SoftDeletes */ $entity_obj = $class::on(config('database.default')) ->with('vendor.company') ->where('id', $this->decodePrimaryKey($request->input('entity_id'))) diff --git a/app/Http/Controllers/TaskController.php b/app/Http/Controllers/TaskController.php index 5deec8f665..c664a7a168 100644 --- a/app/Http/Controllers/TaskController.php +++ b/app/Http/Controllers/TaskController.php @@ -327,8 +327,11 @@ class TaskController extends BaseController * ) */ public function create(CreateTaskRequest $request) - { - $task = TaskFactory::create(auth()->user()->company()->id, auth()->user()->id); + { + /** @var \App\Models\User $user */ + $user = auth()->user(); + + $task = TaskFactory::create($user->company()->id, $user->id); return $this->itemResponse($task); } @@ -373,10 +376,13 @@ class TaskController extends BaseController */ public function store(StoreTaskRequest $request) { - $task = $this->task_repo->save($request->all(), TaskFactory::create(auth()->user()->company()->id, auth()->user()->id)); + /** @var \App\Models\User $user */ + $user = auth()->user(); + + $task = $this->task_repo->save($request->all(), TaskFactory::create($user->company()->id, $user->id)); $task = $this->task_repo->triggeredActions($request, $task); - event(new TaskWasCreated($task, $task->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); + event(new TaskWasCreated($task, $task->company, Ninja::eventVars($user->id))); event('eloquent.created: App\Models\Task', $task); @@ -499,7 +505,9 @@ class TaskController extends BaseController $tasks = Task::withTrashed()->find($this->transformKeys($ids)); $tasks->each(function ($task, $key) use ($action) { - if (auth()->user()->can('edit', $task)) { + /** @var \App\Models\User $user */ + $user = auth()->user(); + if ($user->can('edit', $task)) { $this->task_repo->{$action}($task); } }); @@ -621,10 +629,13 @@ class TaskController extends BaseController { $task_statuses = $request->input('status_ids'); $tasks = $request->input('task_ids'); + + /** @var \App\Models\User $user */ + $user = auth()->user(); - collect($task_statuses)->each(function ($task_status_hashed_id, $key) { - $task_status = TaskStatus::where('id', $this->decodePrimaryKey($task_status_hashed_id)) - ->where('company_id', auth()->user()->company()->id) + collect($task_statuses)->each(function ($task_status_hashed_id, $key) use($user){ + $task_status = TaskStatus::query()->where('id', $this->decodePrimaryKey($task_status_hashed_id)) + ->where('company_id', $user->company()->id) ->withTrashed() ->first(); @@ -636,8 +647,8 @@ class TaskController extends BaseController $sort_status_id = $this->decodePrimaryKey($key); foreach ($task_list as $key => $task) { - $task_record = Task::where('id', $this->decodePrimaryKey($task)) - ->where('company_id', auth()->user()->company()->id) + $task_record = Task::query()->where('id', $this->decodePrimaryKey($task)) + ->where('company_id', $user->company()->id) ->withTrashed() ->first(); diff --git a/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php b/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php index 102b3634a2..6ee0d7fefe 100644 --- a/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php +++ b/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php @@ -26,6 +26,10 @@ class VendorContactHashLoginController extends Controller return redirect('/vendors/purchase_orders'); } + /** + * @return \Illuminate\Support\Facades\Redirect + */ + public function magicLink(string $magic_link) { return redirect($this->setRedirectPath()); diff --git a/app/Http/Controllers/WebhookController.php b/app/Http/Controllers/WebhookController.php index d7a2a581e4..e9046d970e 100644 --- a/app/Http/Controllers/WebhookController.php +++ b/app/Http/Controllers/WebhookController.php @@ -298,7 +298,10 @@ class WebhookController extends BaseController */ public function create(CreateWebhookRequest $request) { - $webhook = WebhookFactory::create(auth()->user()->company()->id, auth()->user()->id); + /** @var \App\Models\User $user */ + $user = auth()->user(); + + $webhook = WebhookFactory::create($user->company()->id, $user->id); $webhook->fill($request->all()); $webhook->save(); @@ -483,7 +486,10 @@ class WebhookController extends BaseController $webhooks = Webhook::withTrashed()->find($this->transformKeys($ids)); $webhooks->each(function ($webhook, $key) use ($action) { - if (auth()->user()->can('edit', $webhook)) { + /** @var \App\Models\User $user */ + $user = auth()->user(); + + if ($user->can('edit', $webhook)) { $this->base_repo->{$action}($webhook); } }); @@ -493,6 +499,8 @@ class WebhookController extends BaseController public function retry(RetryWebhookRequest $request, Webhook $webhook) { + $includes = ''; + match ($request->entity) { 'invoice' => $includes ='client', 'payment' => $includes ='invoices,client', @@ -504,13 +512,16 @@ class WebhookController extends BaseController $class = 'App\Models\\'.ucfirst(Str::camel($request->entity)); - $entity = $class::withTrashed()->where('id', $this->decodePrimaryKey($request->entity_id))->company()->first(); + $entity = $class::query()->withTrashed()->where('id', $this->decodePrimaryKey($request->entity_id))->company()->first(); if (!$entity) { return response()->json(['message' => ctrans('texts.record_not_found')], 400); } + + /** @var \App\Models\User $user */ + $user = auth()->user(); - WebhookSingle::dispatchSync($webhook->id, $entity, auth()->user()->company()->db, $includes); + WebhookSingle::dispatchSync($webhook->id, $entity, $user->company()->db, $includes); return $this->itemResponse($webhook); } diff --git a/app/Http/Livewire/BillingPortalPurchase.php b/app/Http/Livewire/BillingPortalPurchase.php index 715eab092f..d578f261b7 100644 --- a/app/Http/Livewire/BillingPortalPurchase.php +++ b/app/Http/Livewire/BillingPortalPurchase.php @@ -78,7 +78,6 @@ class BillingPortalPurchase extends Component /** * Rules for validating the form. * - * @var \string[][] */ protected $rules = [ 'email' => ['required', 'email'], diff --git a/app/Http/Requests/Statements/CreateStatementRequest.php b/app/Http/Requests/Statements/CreateStatementRequest.php index a2ac1204da..3406be9468 100644 --- a/app/Http/Requests/Statements/CreateStatementRequest.php +++ b/app/Http/Requests/Statements/CreateStatementRequest.php @@ -57,6 +57,6 @@ class CreateStatementRequest extends Request public function client(): ?Client { - return Client::without('company')->where('id', $this->client_id)->withTrashed()->first(); + return Client::query()->without('company')->where('id', $this->client_id)->withTrashed()->first(); } } diff --git a/app/Http/ValidationRules/Credit/UniqueCreditNumberRule.php b/app/Http/ValidationRules/Credit/UniqueCreditNumberRule.php index b869613def..0c20629488 100644 --- a/app/Http/ValidationRules/Credit/UniqueCreditNumberRule.php +++ b/app/Http/ValidationRules/Credit/UniqueCreditNumberRule.php @@ -49,7 +49,7 @@ class UniqueCreditNumberRule implements Rule */ private function checkIfCreditNumberUnique() : bool { - $credit = Credit::where('client_id', $this->input['client_id']) + $credit = Credit::query()->where('client_id', $this->input['client_id']) ->where('number', $this->input['number']) ->withTrashed() ->exists(); diff --git a/app/Http/ValidationRules/Invoice/UniqueInvoiceNumberRule.php b/app/Http/ValidationRules/Invoice/UniqueInvoiceNumberRule.php index fa289f5e48..215367fae4 100644 --- a/app/Http/ValidationRules/Invoice/UniqueInvoiceNumberRule.php +++ b/app/Http/ValidationRules/Invoice/UniqueInvoiceNumberRule.php @@ -53,7 +53,7 @@ class UniqueInvoiceNumberRule implements Rule return true; } - $invoice = Invoice::where('client_id', $this->input['client_id']) + $invoice = Invoice::query()->where('client_id', $this->input['client_id']) ->where('number', $this->input['number']) ->withTrashed() ->exists(); diff --git a/app/Http/ValidationRules/Payment/ValidRefundableRequest.php b/app/Http/ValidationRules/Payment/ValidRefundableRequest.php index db2f8ad2e1..44e4c53ae3 100644 --- a/app/Http/ValidationRules/Payment/ValidRefundableRequest.php +++ b/app/Http/ValidationRules/Payment/ValidRefundableRequest.php @@ -46,8 +46,7 @@ class ValidRefundableRequest implements Rule return false; } - /**@var \App\Models\Payment $payment **/ - $payment = Payment::where('id', $this->input['id'])->withTrashed()->first(); + $payment = Payment::query()->where('id', $this->input['id'])->withTrashed()->first(); if (! $payment) { $this->error_msg = ctrans('texts.unable_to_retrieve_payment'); @@ -77,7 +76,7 @@ class ValidRefundableRequest implements Rule private function checkInvoiceIsPaymentable($invoice, $payment) { /**@var \App\Models\Invoice $invoice **/ - $invoice = Invoice::where('id', $invoice['invoice_id'])->where('company_id', $payment->company_id)->withTrashed()->first(); + $invoice = Invoice::query()->where('id', $invoice['invoice_id'])->where('company_id', $payment->company_id)->withTrashed()->first(); if (! $invoice) { $this->error_msg = 'Invoice not found for refund'; diff --git a/app/Http/ValidationRules/Quote/UniqueQuoteNumberRule.php b/app/Http/ValidationRules/Quote/UniqueQuoteNumberRule.php index c108673727..48acdf6ffd 100644 --- a/app/Http/ValidationRules/Quote/UniqueQuoteNumberRule.php +++ b/app/Http/ValidationRules/Quote/UniqueQuoteNumberRule.php @@ -49,7 +49,7 @@ class UniqueQuoteNumberRule implements Rule */ private function checkIfQuoteNumberUnique() : bool { - $quote = Quote::where('client_id', $this->input['client_id']) + $quote = Quote::query()->where('client_id', $this->input['client_id']) ->where('number', $this->input['number']) ->withTrashed() ->exists(); diff --git a/app/Http/ValidationRules/Recurring/UniqueRecurringInvoiceNumberRule.php b/app/Http/ValidationRules/Recurring/UniqueRecurringInvoiceNumberRule.php index 5eb1ef2b64..e87e4b97d9 100644 --- a/app/Http/ValidationRules/Recurring/UniqueRecurringInvoiceNumberRule.php +++ b/app/Http/ValidationRules/Recurring/UniqueRecurringInvoiceNumberRule.php @@ -53,7 +53,7 @@ class UniqueRecurringInvoiceNumberRule implements Rule return true; } - $invoice = RecurringInvoice::where('client_id', $this->input['client_id']) + $invoice = RecurringInvoice::query()->where('client_id', $this->input['client_id']) ->where('number', $this->input['number']) ->withTrashed() ->exists(); diff --git a/app/Http/ValidationRules/Recurring/UniqueRecurringQuoteNumberRule.php b/app/Http/ValidationRules/Recurring/UniqueRecurringQuoteNumberRule.php index 278ac21643..98951c70c9 100644 --- a/app/Http/ValidationRules/Recurring/UniqueRecurringQuoteNumberRule.php +++ b/app/Http/ValidationRules/Recurring/UniqueRecurringQuoteNumberRule.php @@ -53,7 +53,7 @@ class UniqueRecurringQuoteNumberRule implements Rule return true; } - $invoice = RecurringQuote::where('client_id', $this->input['client_id']) + $invoice = RecurringQuote::query()->where('client_id', $this->input['client_id']) ->where('number', $this->input['number']) ->withTrashed() ->exists(); diff --git a/app/Import/Providers/BaseImport.php b/app/Import/Providers/BaseImport.php index 04780c6fc2..988c85b520 100644 --- a/app/Import/Providers/BaseImport.php +++ b/app/Import/Providers/BaseImport.php @@ -95,6 +95,7 @@ class BaseImport ini_set('auto_detect_line_endings', '1'); } + /** @var strin $base64_encoded_csv */ $base64_encoded_csv = Cache::pull($this->hash.'-'.$entity_type); if (empty($base64_encoded_csv)) { @@ -103,7 +104,7 @@ class BaseImport $csv = base64_decode($base64_encoded_csv); $csv = mb_convert_encoding($csv, 'UTF-8', 'UTF-8'); - nlog($csv); + $csv = Reader::createFromString($csv); $csvdelimiter = self::detectDelimiter($csv); diff --git a/app/Jobs/Bank/ProcessBankTransactions.php b/app/Jobs/Bank/ProcessBankTransactions.php index aeb309c50e..c5af8fd49a 100644 --- a/app/Jobs/Bank/ProcessBankTransactions.php +++ b/app/Jobs/Bank/ProcessBankTransactions.php @@ -158,7 +158,7 @@ class ProcessBankTransactions implements ShouldQueue $now = now(); foreach ($transactions as $transaction) { - if (BankTransaction::where('transaction_id', $transaction['transaction_id'])->where('company_id', $this->company->id)->withTrashed()->exists()) { + if (BankTransaction::query()->where('transaction_id', $transaction['transaction_id'])->where('company_id', $this->company->id)->withTrashed()->exists()) { continue; } diff --git a/app/Jobs/Company/CompanyExport.php b/app/Jobs/Company/CompanyExport.php index b41b4ed2ef..0cbb91f9a5 100644 --- a/app/Jobs/Company/CompanyExport.php +++ b/app/Jobs/Company/CompanyExport.php @@ -187,7 +187,7 @@ class CompanyExport implements ShouldQueue })->all(); - $this->export_data['credit_invitations'] = CreditInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($credit) { + $this->export_data['credit_invitations'] = CreditInvitation::query()->where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($credit) { $credit = $this->transformArrayOfKeys($credit, ['company_id', 'user_id', 'client_contact_id', 'credit_id']); return $credit->makeVisible(['id']); @@ -236,7 +236,7 @@ class CompanyExport implements ShouldQueue })->all(); - $this->export_data['invoice_invitations'] = InvoiceInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($invoice) { + $this->export_data['invoice_invitations'] = InvoiceInvitation::query()->where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($invoice) { $invoice = $this->transformArrayOfKeys($invoice, ['company_id', 'user_id', 'client_contact_id', 'invoice_id']); return $invoice->makeVisible(['id']); @@ -280,7 +280,7 @@ class CompanyExport implements ShouldQueue })->all(); - $this->export_data['quote_invitations'] = QuoteInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($quote) { + $this->export_data['quote_invitations'] = QuoteInvitation::query()->where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($quote) { $quote = $this->transformArrayOfKeys($quote, ['company_id', 'user_id', 'client_contact_id', 'quote_id']); return $quote->makeVisible(['id']); @@ -301,7 +301,7 @@ class CompanyExport implements ShouldQueue })->all(); - $this->export_data['recurring_invoice_invitations'] = RecurringInvoiceInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($ri) { + $this->export_data['recurring_invoice_invitations'] = RecurringInvoiceInvitation::query()->where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($ri) { $ri = $this->transformArrayOfKeys($ri, ['company_id', 'user_id', 'client_contact_id', 'recurring_invoice_id']); return $ri; @@ -381,7 +381,7 @@ class CompanyExport implements ShouldQueue 'company_id',]); })->all(); - $this->export_data['purchase_order_invitations'] = PurchaseOrderInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($purchase_order) { + $this->export_data['purchase_order_invitations'] = PurchaseOrderInvitation::query()->where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($purchase_order) { $purchase_order = $this->transformArrayOfKeys($purchase_order, ['company_id', 'user_id', 'vendor_contact_id', 'purchase_order_id']); return $purchase_order->makeVisible(['id']); diff --git a/app/Jobs/Util/Import.php b/app/Jobs/Util/Import.php index 0d2e837983..d35b50cb70 100644 --- a/app/Jobs/Util/Import.php +++ b/app/Jobs/Util/Import.php @@ -1482,7 +1482,7 @@ class Import implements ShouldQueue try { $invoice_id = $this->transformId('invoices', $resource['invoice_id']); - $entity = Invoice::where('id', $invoice_id)->withTrashed()->first(); + $entity = Invoice::query()->where('id', $invoice_id)->withTrashed()->first(); } catch(\Exception $e) { nlog("i couldn't find the invoice document {$resource['invoice_id']}, perhaps it is a quote?"); nlog($e->getMessage()); @@ -1493,7 +1493,7 @@ class Import implements ShouldQueue if ($try_quote && array_key_exists('quotes', $this->ids)) { try { $quote_id = $this->transformId('quotes', $resource['invoice_id']); - $entity = Quote::where('id', $quote_id)->withTrashed()->first(); + $entity = Quote::query()->where('id', $quote_id)->withTrashed()->first(); } catch(\Exception $e) { nlog("i couldn't find the quote document {$resource['invoice_id']}, perhaps it is a quote?"); nlog($e->getMessage()); @@ -1509,7 +1509,7 @@ class Import implements ShouldQueue if (array_key_exists('expense_id', $resource) && $resource['expense_id'] && array_key_exists('expenses', $this->ids)) { $expense_id = $this->transformId('expenses', $resource['expense_id']); - $entity = Expense::where('id', $expense_id)->withTrashed()->first(); + $entity = Expense::query()->where('id', $expense_id)->withTrashed()->first(); } $file_url = $resource['url']; diff --git a/app/Models/BaseModel.php b/app/Models/BaseModel.php index cf4e39b2e3..09f5571565 100644 --- a/app/Models/BaseModel.php +++ b/app/Models/BaseModel.php @@ -37,10 +37,12 @@ use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundExceptio * @property int $assigned_user_id * @method BaseModel service() * @property \App\Models\Company $company + * @property \App\Models\Vendor $vendor * @method static BaseModel find($value) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel company() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|Illuminate\Database\Eloquent\Relations\BelongsTo|\Awobaz\Compoships\Database\Eloquent\Relations\BelongsTo|\App\Models\Company company() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel|Illuminate\Database\Eloquent\Relations\HasMany|BaseModel orderBy() + * @method static \Illuminate\Database\Eloquent\Builder|BaseModel on(?string $connection = null) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel exclude($columns) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel with($value) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel newModelQuery($query) @@ -55,6 +57,7 @@ use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundExceptio * @method static \Illuminate\Database\Eloquent\Builder|BaseModel orderBy($column, $direction) * @method static \Illuminate\Database\Eloquent\Builder|BaseModel invitations() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel whereHas($query) + * @method static \Illuminate\Database\Eloquent\Builder|BaseModel without($query) * @property-read \Illuminate\Database\Eloquent\Collection $invitations * @property-read int|null $invitations_count * @method int companyId() diff --git a/app/Models/Client.php b/app/Models/Client.php index fd85ef504d..ac764cbcf6 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -79,50 +79,33 @@ use Illuminate\Contracts\Translation\HasLocalePreference; * @property int|null $updated_at * @property int|null $deleted_at * @property string|null $id_number - * @property-read \Illuminate\Database\Eloquent\Collection $activities - * @property-read int|null $activities_count - * @property-read \App\Models\User|null $assigned_user - * @property-read \App\Models\Company $company - * @property-read \Illuminate\Database\Eloquent\Collection $company_ledger - * @property-read int|null $company_ledger_count - * @property-read \Illuminate\Database\Eloquent\Collection $contacts - * @property-read int|null $contacts_count - * @property-read \App\Models\Country|null $country - * @property-read \Illuminate\Database\Eloquent\Collection $credits - * @property-read int|null $credits_count - * @property-read \Illuminate\Database\Eloquent\Collection $documents - * @property-read int|null $documents_count - * @property-read \Illuminate\Database\Eloquent\Collection $expenses - * @property-read int|null $expenses_count - * @property-read \Illuminate\Database\Eloquent\Collection $gateway_tokens - * @property-read int|null $gateway_tokens_count * @property-read mixed $hashed_id + * @property-read \App\Models\User|null $assigned_user + * @property-read \App\Models\User $user + * @property-read \App\Models\Company $company + * @property-read \App\Models\Country|null $country + * @property-read \Illuminate\Database\Eloquent\Collection $activities + * @property-read \Illuminate\Database\Eloquent\Collection $company_ledger + * @property-read \Illuminate\Database\Eloquent\Collection $contacts + * @property-read \Illuminate\Database\Eloquent\Collection $credits + * @property-read \Illuminate\Database\Eloquent\Collection $documents + * @property-read \Illuminate\Database\Eloquent\Collection $expenses + * @property-read \Illuminate\Database\Eloquent\Collection $gateway_tokens * @property-read \Illuminate\Database\Eloquent\Collection $invoices - * @property-read int|null $invoices_count * @property-read \Illuminate\Database\Eloquent\Collection $ledger - * @property-read int|null $ledger_count * @property-read \Illuminate\Database\Eloquent\Collection $payments - * @property-read int|null $payments_count * @property-read \Illuminate\Database\Eloquent\Collection $primary_contact - * @property-read int|null $primary_contact_count * @property-read \Illuminate\Database\Eloquent\Collection $projects - * @property-read int|null $projects_count * @property-read \Illuminate\Database\Eloquent\Collection $quotes - * @property-read int|null $quotes_count * @property-read \Illuminate\Database\Eloquent\Collection $recurring_expenses - * @property-read int|null $recurring_expenses_count * @property-read \Illuminate\Database\Eloquent\Collection $recurring_invoices - * @property-read int|null $recurring_invoices_count - * @property-read \App\Models\Country|null $shipping_country * @property-read \Illuminate\Database\Eloquent\Collection $system_logs - * @property-read int|null $system_logs_count * @property-read \Illuminate\Database\Eloquent\Collection $tasks * @property-read \Illuminate\Database\Eloquent\Collection $recurring_invoices - * @property-read int|null $tasks_count - * @property-read \App\Models\User $user * @method static \Illuminate\Database\Eloquent\Builder|Client exclude($columns) * @method static \Database\Factories\ClientFactory factory($count = null, $state = []) * @method static \Illuminate\Database\Eloquent\Builder|Client filter(\App\Filters\QueryFilters $filters) + * @method static \Illuminate\Database\Eloquent\Builder|Client without() * @property string $payment_balance * @property mixed $tax_data * @property int $is_tax_exempt diff --git a/app/Models/PurchaseOrder.php b/app/Models/PurchaseOrder.php index 3639469776..917a1969e8 100644 --- a/app/Models/PurchaseOrder.php +++ b/app/Models/PurchaseOrder.php @@ -112,6 +112,8 @@ use Illuminate\Support\Facades\Storage; * @property-read \Illuminate\Database\Eloquent\Collection $invitations * @property-read \Illuminate\Database\Eloquent\Collection $invoices * @property-read \Illuminate\Database\Eloquent\Collection $payments + * @method static \Illuminate\Database\Eloquent\Builder|Task withTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Task withoutTrashed() * @mixin \Eloquent */ class PurchaseOrder extends BaseModel diff --git a/app/Observers/CompanyGatewayObserver.php b/app/Observers/CompanyGatewayObserver.php index bc40e9fb02..572c45af2e 100644 --- a/app/Observers/CompanyGatewayObserver.php +++ b/app/Observers/CompanyGatewayObserver.php @@ -54,7 +54,7 @@ class CompanyGatewayObserver public function restored(CompanyGateway $company_gateway) { //When we restore the gateway, bring back the tokens! - ClientGatewayToken::where('company_gateway_id', $company_gateway->id) + ClientGatewayToken::query()->where('company_gateway_id', $company_gateway->id) ->withTrashed()->cursor()->each(function ($cgt) { $cgt->restore(); }); diff --git a/app/Repositories/ActivityRepository.php b/app/Repositories/ActivityRepository.php index 129436d875..adafdfb2ca 100644 --- a/app/Repositories/ActivityRepository.php +++ b/app/Repositories/ActivityRepository.php @@ -99,7 +99,7 @@ class ActivityRepository extends BaseRepository { if ($event_vars['token']) { /** @var \App\Models\CompanyToken $company_token **/ - $company_token = CompanyToken::where('token', $event_vars['token'])->first(); + $company_token = CompanyToken::query()->where('token', $event_vars['token'])->first(); if ($company_token) { return $company_token->id; diff --git a/app/Repositories/BaseRepository.php b/app/Repositories/BaseRepository.php index 13df4b4d84..b2c5aaad97 100644 --- a/app/Repositories/BaseRepository.php +++ b/app/Repositories/BaseRepository.php @@ -224,7 +224,7 @@ class BaseRepository /* 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) { $invitation_class = sprintf('App\\Models\\%sInvitation', $resource); - $invitation = $invitation_class::where('key', $invitation)->first(); + $invitation = $invitation_class::query()->where('key', $invitation)->first(); if ($invitation) { $invitation->delete(); diff --git a/app/Repositories/CreditRepository.php b/app/Repositories/CreditRepository.php index f5097e8f9a..79d83c36be 100644 --- a/app/Repositories/CreditRepository.php +++ b/app/Repositories/CreditRepository.php @@ -41,7 +41,7 @@ class CreditRepository extends BaseRepository public function getInvitationByKey($key) :?CreditInvitation { - return CreditInvitation::where('key', $key)->first(); + return CreditInvitation::query()->where('key', $key)->first(); } public function delete($credit) diff --git a/app/Repositories/InvoiceRepository.php b/app/Repositories/InvoiceRepository.php index c7347da552..f3d4a4e6d4 100644 --- a/app/Repositories/InvoiceRepository.php +++ b/app/Repositories/InvoiceRepository.php @@ -49,7 +49,7 @@ class InvoiceRepository extends BaseRepository public function getInvitationByKey($key) :?InvoiceInvitation { - return InvoiceInvitation::where('key', $key)->first(); + return InvoiceInvitation::query()->where('key', $key)->first(); } /** diff --git a/app/Repositories/Migration/InvoiceMigrationRepository.php b/app/Repositories/Migration/InvoiceMigrationRepository.php index 40725e6202..da1717a2f5 100644 --- a/app/Repositories/Migration/InvoiceMigrationRepository.php +++ b/app/Repositories/Migration/InvoiceMigrationRepository.php @@ -38,9 +38,9 @@ class InvoiceMigrationRepository extends BaseRepository $class = new ReflectionClass($model); if (array_key_exists('client_id', $data)) { - $client = Client::where('id', $data['client_id'])->withTrashed()->first(); + $client = Client::query()->where('id', $data['client_id'])->withTrashed()->first(); } else { - $client = Client::where('id', $model->client_id)->withTrashed()->first(); + $client = Client::query()->where('id', $model->client_id)->withTrashed()->first(); } $state = []; diff --git a/app/Repositories/Migration/PaymentMigrationRepository.php b/app/Repositories/Migration/PaymentMigrationRepository.php index 683355f423..f8f6f686b7 100644 --- a/app/Repositories/Migration/PaymentMigrationRepository.php +++ b/app/Repositories/Migration/PaymentMigrationRepository.php @@ -206,7 +206,7 @@ class PaymentMigrationRepository extends BaseRepository return $payment; } - $client = Client::where('id', $data['client_id'])->withTrashed()->first(); + $client = Client::query()->where('id', $data['client_id'])->withTrashed()->first(); $client_currency = $client->getSetting('currency_id'); $company_currency = $client->company->settings->currency_id; diff --git a/app/Repositories/PaymentRepository.php b/app/Repositories/PaymentRepository.php index 48fdd4a8e5..f11a6f3ceb 100644 --- a/app/Repositories/PaymentRepository.php +++ b/app/Repositories/PaymentRepository.php @@ -76,7 +76,7 @@ class PaymentRepository extends BaseRepository $is_existing_payment = false; \DB::connection(config('database.default'))->transaction(function () use ($data) { - $client = Client::where('id', $data['client_id'])->withTrashed()->lockForUpdate()->first(); + $client = Client::query()->where('id', $data['client_id'])->withTrashed()->lockForUpdate()->first(); /*We only update the paid to date ONCE per payment*/ if (array_key_exists('invoices', $data) && is_array($data['invoices']) && count($data['invoices']) > 0) { diff --git a/app/Repositories/PurchaseOrderRepository.php b/app/Repositories/PurchaseOrderRepository.php index 321b4fa898..71bd54a5b9 100644 --- a/app/Repositories/PurchaseOrderRepository.php +++ b/app/Repositories/PurchaseOrderRepository.php @@ -36,7 +36,7 @@ class PurchaseOrderRepository extends BaseRepository /* Get array of Keys which have been removed from the invitations array and soft delete each invitation */ $purchase_order->invitations->pluck('key')->diff($invitations->pluck('key'))->each(function ($invitation) { - $invitation = PurchaseOrderInvitation::where('key', $invitation)->first(); + $invitation = PurchaseOrderInvitation::query()->where('key', $invitation)->first(); if ($invitation) { $invitation->delete(); @@ -86,7 +86,7 @@ class PurchaseOrderRepository extends BaseRepository public function getInvitationByKey($key) :?PurchaseOrderInvitation { - return PurchaseOrderInvitation::where('key', $key)->first(); + return PurchaseOrderInvitation::query()->where('key', $key)->first(); } public function getInvitation($invitation, $resource = null) @@ -95,7 +95,7 @@ class PurchaseOrderRepository extends BaseRepository return false; } - $invitation = PurchaseOrderInvitation::where('key', $invitation['key'])->first(); + $invitation = PurchaseOrderInvitation::query()->where('key', $invitation['key'])->first(); return $invitation; } diff --git a/app/Repositories/QuoteRepository.php b/app/Repositories/QuoteRepository.php index 3d71199a55..6a90b0c74d 100644 --- a/app/Repositories/QuoteRepository.php +++ b/app/Repositories/QuoteRepository.php @@ -26,6 +26,6 @@ class QuoteRepository extends BaseRepository public function getInvitationByKey($key) :?QuoteInvitation { - return QuoteInvitation::where('key', $key)->first(); + return QuoteInvitation::query()->where('key', $key)->first(); } } diff --git a/app/Repositories/TaskStatusRepository.php b/app/Repositories/TaskStatusRepository.php index faf650ef22..34a1f8e636 100644 --- a/app/Repositories/TaskStatusRepository.php +++ b/app/Repositories/TaskStatusRepository.php @@ -22,12 +22,12 @@ class TaskStatusRepository extends BaseRepository public function delete($task_status) { /** @var \App\Models\TaskStatus $ts **/ - $ts = TaskStatus::where('company_id', $task_status->company_id) + $ts = TaskStatus::query()->where('company_id', $task_status->company_id) ->first(); $new_status = $ts ? $ts->id : null; - Task::where('status_id', $task_status->id) + Task::query()->where('status_id', $task_status->id) ->where('company_id', $task_status->company_id) ->update(['status_id' => $new_status]); @@ -60,7 +60,7 @@ class TaskStatusRepository extends BaseRepository public function reorder(TaskStatus $task_status) { - TaskStatus::where('company_id', $task_status->company_id) + TaskStatus::query()->where('company_id', $task_status->company_id) ->where('id', '!=', $task_status->id) ->orderByRaw('ISNULL(status_order), status_order ASC') ->cursor() @@ -77,7 +77,7 @@ class TaskStatusRepository extends BaseRepository }); - TaskStatus::where('company_id', $task_status->company_id) + TaskStatus::query()->where('company_id', $task_status->company_id) ->orderByRaw('ISNULL(status_order), status_order ASC') ->cursor() ->each(function ($ts, $key) { diff --git a/app/Repositories/UserRepository.php b/app/Repositories/UserRepository.php index ce870fe557..582812b74d 100644 --- a/app/Repositories/UserRepository.php +++ b/app/Repositories/UserRepository.php @@ -81,7 +81,7 @@ class UserRepository extends BaseRepository $user->save(); if (isset($data['company_user'])) { - $cu = CompanyUser::whereUserId($user->id)->whereCompanyId($company->id)->withTrashed()->first(); + $cu = CompanyUser::query()->whereUserId($user->id)->whereCompanyId($company->id)->withTrashed()->first(); /*No company user exists - attach the user*/ if (! $cu) { @@ -129,7 +129,7 @@ class UserRepository extends BaseRepository $company = auth()->user()->company(); - $cu = CompanyUser::whereUserId($user->id) + $cu = CompanyUser::query()->whereUserId($user->id) ->whereCompanyId($company->id) ->first(); @@ -151,7 +151,7 @@ class UserRepository extends BaseRepository { $company = auth()->user()->company(); - $cu = CompanyUser::whereUserId($user->id) + $cu = CompanyUser::query()->whereUserId($user->id) ->whereCompanyId($company->id) ->first(); @@ -190,7 +190,7 @@ class UserRepository extends BaseRepository } if (Ninja::isHosted()) { - $count = User::where('account_id', auth()->user()->account_id)->count(); + $count = User::query()->where('account_id', auth()->user()->account_id)->count(); if ($count >= auth()->user()->account->num_users) { return; } diff --git a/app/Services/Bank/BankMatchingService.php b/app/Services/Bank/BankMatchingService.php index df013e77cc..30eb58943e 100644 --- a/app/Services/Bank/BankMatchingService.php +++ b/app/Services/Bank/BankMatchingService.php @@ -31,7 +31,7 @@ class BankMatchingService implements ShouldQueue { MultiDB::setDb($this->db); - BankTransaction::where('company_id', $this->company_id) + BankTransaction::query()->where('company_id', $this->company_id) ->where('status_id', BankTransaction::STATUS_UNMATCHED) ->cursor() ->each(function ($bt) { diff --git a/app/Services/Bank/BankService.php b/app/Services/Bank/BankService.php index 1fc3a77ba9..42b1027a85 100644 --- a/app/Services/Bank/BankService.php +++ b/app/Services/Bank/BankService.php @@ -24,7 +24,7 @@ class BankService public function matchInvoiceNumber() { if (strlen($this->bank_transaction->description) > 1) { - $i = Invoice::where('company_id', $this->bank_transaction->company_id) + $i = Invoice::query()->where('company_id', $this->bank_transaction->company_id) ->whereIn('status_id', [1,2,3]) ->where('is_deleted', 0) ->where('number', 'LIKE', '%'.$this->bank_transaction->description.'%') diff --git a/app/Services/Bank/ProcessBankRules.php b/app/Services/Bank/ProcessBankRules.php index 9daaacb6b1..fa9a9f6a8c 100644 --- a/app/Services/Bank/ProcessBankRules.php +++ b/app/Services/Bank/ProcessBankRules.php @@ -49,7 +49,7 @@ class ProcessBankRules extends AbstractService private function matchCredit() { /** @var \Illuminate\Database\Eloquent\Collection $this->invoices */ - $this->invoices = Invoice::where('company_id', $this->bank_transaction->company_id) + $this->invoices = Invoice::query()->where('company_id', $this->bank_transaction->company_id) ->whereIn('status_id', [1,2,3]) ->where('is_deleted', 0) ->get(); @@ -153,7 +153,7 @@ class ProcessBankRules extends AbstractService { $category = $this->categories->firstWhere('highLevelCategoryId', $this->bank_transaction->category_id); - $ec = ExpenseCategory::where('company_id', $this->bank_transaction->company_id)->where('bank_category_id', $this->bank_transaction->category_id)->first(); + $ec = ExpenseCategory::query()->where('company_id', $this->bank_transaction->company_id)->where('bank_category_id', $this->bank_transaction->category_id)->first(); if ($ec) { return $ec->id; diff --git a/app/Services/Client/ClientService.php b/app/Services/Client/ClientService.php index 6e22782a29..869f9e51f0 100644 --- a/app/Services/Client/ClientService.php +++ b/app/Services/Client/ClientService.php @@ -78,7 +78,7 @@ class ClientService public function updatePaymentBalance() { - $amount = Payment::where('client_id', $this->client->id) + $amount = Payment::query()->where('client_id', $this->client->id) ->where('is_deleted', 0) ->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) ->sum(DB::Raw('amount - applied')); @@ -115,7 +115,7 @@ class ClientService public function getCredits() { - return Credit::where('client_id', $this->client->id) + return Credit::query()->where('client_id', $this->client->id) ->where('is_deleted', false) ->where('balance', '>', 0) ->where(function ($query) { diff --git a/app/Services/Client/Merge.php b/app/Services/Client/Merge.php index a2f830a1bb..6dc11c342c 100644 --- a/app/Services/Client/Merge.php +++ b/app/Services/Client/Merge.php @@ -71,7 +71,7 @@ class Merge extends AbstractService { $balance = 0; - $company_ledger = CompanyLedger::whereClientId($this->client->id) + $company_ledger = CompanyLedger::query()->whereClientId($this->client->id) ->orderBy('id', 'DESC') ->first(); diff --git a/app/Services/ClientPortal/InstantPayment.php b/app/Services/ClientPortal/InstantPayment.php index 91832d9f20..a76482273d 100644 --- a/app/Services/ClientPortal/InstantPayment.php +++ b/app/Services/ClientPortal/InstantPayment.php @@ -233,7 +233,7 @@ class InstantPayment $hash_data['billing_context'] = Cache::get($this->request->query('hash')); } elseif ($this->request->hash) { $hash_data['billing_context'] = Cache::get($this->request->hash); - } elseif ($old_hash = PaymentHash::where('fee_invoice_id', $first_invoice->id)->whereNull('payment_id')->first()) { + } elseif ($old_hash = PaymentHash::query()->where('fee_invoice_id', $first_invoice->id)->whereNull('payment_id')->first()) { if (isset($old_hash->data->billing_context)) { $hash_data['billing_context'] = $old_hash->data->billing_context; } diff --git a/app/Services/Credit/CreateInvitations.php b/app/Services/Credit/CreateInvitations.php index cf413f2444..449a6ac6ff 100644 --- a/app/Services/Credit/CreateInvitations.php +++ b/app/Services/Credit/CreateInvitations.php @@ -66,7 +66,7 @@ class CreateInvitations extends AbstractService } else { $contact = $contacts->first(); - $invitation = CreditInvitation::where('company_id', $this->credit->company_id) + $invitation = CreditInvitation::query()->where('company_id', $this->credit->company_id) ->where('client_contact_id', $contact->id) ->where('credit_id', $this->credit->id) ->withTrashed() diff --git a/app/Services/Invoice/AutoBillInvoice.php b/app/Services/Invoice/AutoBillInvoice.php index c05aecf18b..f776cbc4af 100644 --- a/app/Services/Invoice/AutoBillInvoice.php +++ b/app/Services/Invoice/AutoBillInvoice.php @@ -250,7 +250,7 @@ class AutoBillInvoice extends AbstractService */ private function applyCreditPayment(): self { - $available_credits = Credit::where('client_id', $this->client->id) + $available_credits = Credit::query()->where('client_id', $this->client->id) ->where('is_deleted', false) ->where('balance', '>', 0) ->orderBy('created_at') diff --git a/app/Services/Invoice/CreateInvitations.php b/app/Services/Invoice/CreateInvitations.php index 5261df58f1..853090f5d1 100644 --- a/app/Services/Invoice/CreateInvitations.php +++ b/app/Services/Invoice/CreateInvitations.php @@ -39,7 +39,7 @@ class CreateInvitations extends AbstractService } $contacts->each(function ($contact) { - $invitation = InvoiceInvitation::where('company_id', $this->invoice->company_id) + $invitation = InvoiceInvitation::query()->where('company_id', $this->invoice->company_id) ->where('client_contact_id', $contact->id) ->where('invoice_id', $this->invoice->id) ->withTrashed() @@ -62,7 +62,7 @@ class CreateInvitations extends AbstractService } else { $contact = $contacts->first(); - $invitation = InvoiceInvitation::where('company_id', $this->invoice->company_id) + $invitation = InvoiceInvitation::query()->where('company_id', $this->invoice->company_id) ->where('client_contact_id', $contact->id) ->where('invoice_id', $this->invoice->id) ->withTrashed() diff --git a/app/Services/Invoice/HandleRestore.php b/app/Services/Invoice/HandleRestore.php index d5bf6c8275..de3a990baa 100644 --- a/app/Services/Invoice/HandleRestore.php +++ b/app/Services/Invoice/HandleRestore.php @@ -165,7 +165,7 @@ class HandleRestore extends AbstractService } try { - $exists = Invoice::where(['company_id' => $this->invoice->company_id, 'number' => $new_invoice_number])->exists(); + $exists = Invoice::query()->where(['company_id' => $this->invoice->company_id, 'number' => $new_invoice_number])->exists(); if ($exists) { $this->invoice->number = $this->getNextInvoiceNumber($this->invoice->client, $this->invoice, $this->invoice->recurring_id); diff --git a/app/Services/Invoice/HandleReversal.php b/app/Services/Invoice/HandleReversal.php index 58d566e51c..2b1410950e 100644 --- a/app/Services/Invoice/HandleReversal.php +++ b/app/Services/Invoice/HandleReversal.php @@ -44,7 +44,7 @@ class HandleReversal extends AbstractService $total_paid = $this->invoice->amount - $this->invoice->balance; /*Adjust payment applied and the paymentables to the correct amount */ - $paymentables = Paymentable::wherePaymentableType('invoices') + $paymentables = Paymentable::query()->wherePaymentableType('invoices') ->wherePaymentableId($this->invoice->id) ->get(); diff --git a/app/Services/Payment/DeletePayment.php b/app/Services/Payment/DeletePayment.php index 6c99757ea2..27119ec5ca 100644 --- a/app/Services/Payment/DeletePayment.php +++ b/app/Services/Payment/DeletePayment.php @@ -58,7 +58,7 @@ class DeletePayment $this->payment->is_deleted = true; $this->payment->delete(); - BankTransaction::where('payment_id', $this->payment->id)->cursor()->each(function ($bt){ + BankTransaction::query()->where('payment_id', $this->payment->id)->cursor()->each(function ($bt){ $bt->payment_id = null; $bt->save(); }); diff --git a/app/Services/PurchaseOrder/CreateInvitations.php b/app/Services/PurchaseOrder/CreateInvitations.php index c33091bdc5..cef458d4e2 100644 --- a/app/Services/PurchaseOrder/CreateInvitations.php +++ b/app/Services/PurchaseOrder/CreateInvitations.php @@ -51,7 +51,7 @@ class CreateInvitations extends AbstractService } $contacts->each(function ($contact) { - $invitation = PurchaseOrderInvitation::where('company_id', $this->purchase_order->company_id) + $invitation = PurchaseOrderInvitation::query()->where('company_id', $this->purchase_order->company_id) ->where('vendor_contact_id', $contact->id) ->where('purchase_order_id', $this->purchase_order->id) ->withTrashed() @@ -78,7 +78,7 @@ class CreateInvitations extends AbstractService } else { $contact = $contacts->first(); - $invitation = PurchaseOrderInvitation::where('company_id', $this->purchase_order->company_id) + $invitation = PurchaseOrderInvitation::query()->where('company_id', $this->purchase_order->company_id) ->where('vendor_contact_id', $contact->id) ->where('purchase_order_id', $this->purchase_order->id) ->withTrashed() diff --git a/app/Services/PurchaseOrder/PurchaseOrderInventory.php b/app/Services/PurchaseOrder/PurchaseOrderInventory.php index 298c5718f6..e3e6036bf5 100644 --- a/app/Services/PurchaseOrder/PurchaseOrderInventory.php +++ b/app/Services/PurchaseOrder/PurchaseOrderInventory.php @@ -28,7 +28,7 @@ class PurchaseOrderInventory $line_items = $this->purchase_order->line_items; foreach ($line_items as $item) { - $p = Product::where('product_key', $item->product_key)->where('company_id', $this->purchase_order->company_id)->first(); + $p = Product::query()->where('product_key', $item->product_key)->where('company_id', $this->purchase_order->company_id)->first(); if (!$p) { continue; diff --git a/app/Services/Quote/CreateInvitations.php b/app/Services/Quote/CreateInvitations.php index 8ba5090c39..933bbdbe9d 100644 --- a/app/Services/Quote/CreateInvitations.php +++ b/app/Services/Quote/CreateInvitations.php @@ -65,7 +65,7 @@ class CreateInvitations } else { $contact = $contacts->first(); - $invitation = QuoteInvitation::where('company_id', $this->quote->company_id) + $invitation = QuoteInvitation::query()->where('company_id', $this->quote->company_id) ->where('client_contact_id', $contact->id) ->where('quote_id', $this->quote->id) ->withTrashed() diff --git a/app/Services/Recurring/CreateRecurringInvitations.php b/app/Services/Recurring/CreateRecurringInvitations.php index 128c3bab19..4fb3a7b1c1 100644 --- a/app/Services/Recurring/CreateRecurringInvitations.php +++ b/app/Services/Recurring/CreateRecurringInvitations.php @@ -43,7 +43,7 @@ class CreateRecurringInvitations extends AbstractService { try { $this->entity->client->contacts->each(function ($contact) { - $invitation = $this->invitation_class::whereCompanyId($this->entity->company_id) + $invitation = $this->invitation_class::query()->whereCompanyId($this->entity->company_id) ->whereClientContactId($contact->id) ->where($this->entity_id_name, $this->entity->id) ->withTrashed() @@ -64,7 +64,7 @@ class CreateRecurringInvitations extends AbstractService } if ($this->entity->invitations()->count() == 0) { - $invitation = $this->invitation_class::where('company_id', $this->entity->company_id) + $invitation = $this->invitation_class::query()->where('company_id', $this->entity->company_id) ->where($this->entity_id_name, $this->entity->id) ->withTrashed() ->first(); diff --git a/app/Services/Recurring/UpdatePrice.php b/app/Services/Recurring/UpdatePrice.php index 77c729669b..bb8c7b2662 100644 --- a/app/Services/Recurring/UpdatePrice.php +++ b/app/Services/Recurring/UpdatePrice.php @@ -28,7 +28,7 @@ class UpdatePrice extends AbstractService foreach ($line_items as $key => $line_item) { /** @var \App\Models\Product $product **/ - $product = Product::where('company_id', $this->recurring_invoice->company_id) + $product = Product::query()->where('company_id', $this->recurring_invoice->company_id) ->where('product_key', $line_item->product_key) ->where('is_deleted', 0) ->first(); diff --git a/app/Services/Report/ClientBalanceReport.php b/app/Services/Report/ClientBalanceReport.php index d946797761..0c0eb85aca 100644 --- a/app/Services/Report/ClientBalanceReport.php +++ b/app/Services/Report/ClientBalanceReport.php @@ -105,7 +105,7 @@ class ClientBalanceReport extends BaseExport } private function buildRow(Client $client): array { - $query = Invoice::where('client_id', $client->id) + $query = Invoice::query()->where('client_id', $client->id) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]); $query = $this->addDateRange($query); diff --git a/app/Services/Report/ClientSalesReport.php b/app/Services/Report/ClientSalesReport.php index 61e25ed582..7bb5b47d83 100644 --- a/app/Services/Report/ClientSalesReport.php +++ b/app/Services/Report/ClientSalesReport.php @@ -99,7 +99,7 @@ class ClientSalesReport extends BaseExport private function buildRow(Client $client): array { - $query = Invoice::where('client_id', $client->id) + $query = Invoice::query()->where('client_id', $client->id) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID]); $query = $this->addDateRange($query); diff --git a/app/Services/Report/ProfitLoss.php b/app/Services/Report/ProfitLoss.php index d070b76366..56bf7ae7b5 100644 --- a/app/Services/Report/ProfitLoss.php +++ b/app/Services/Report/ProfitLoss.php @@ -270,7 +270,7 @@ class ProfitLoss { $this->invoice_payment_map = []; - Payment::where('company_id', $this->company->id) + Payment::query()->where('company_id', $this->company->id) ->whereIn('status_id', [1, 4, 5]) ->where('is_deleted', 0) ->whereBetween('date', [$this->start_date, $this->end_date]) @@ -452,7 +452,7 @@ class ProfitLoss private function expenseData() { - $expenses = Expense::where('company_id', $this->company->id) + $expenses = Expense::query()->where('company_id', $this->company->id) ->where('is_deleted', 0) ->withTrashed() ->whereBetween('date', [$this->start_date, $this->end_date]) diff --git a/app/Services/Subscription/SubscriptionService.php b/app/Services/Subscription/SubscriptionService.php index efb3035286..a8dbeb7da6 100644 --- a/app/Services/Subscription/SubscriptionService.php +++ b/app/Services/Subscription/SubscriptionService.php @@ -347,7 +347,7 @@ class SubscriptionService $outstanding_amounts = $outstanding->sum('balance'); - $outstanding_invoice = Invoice::where('client_id', $recurring_invoice->client_id) + $outstanding_invoice = Invoice::query()->where('client_id', $recurring_invoice->client_id) ->where('is_deleted', 0) ->where('is_proforma', 0) ->where('subscription_id', $this->subscription->id) @@ -356,7 +356,7 @@ class SubscriptionService //sometimes the last document could be a credit if the user is paying for their service with credits. if (!$outstanding_invoice) { - $outstanding_invoice = Credit::where('subscription_id', $this->subscription->id) + $outstanding_invoice = Credit::query()->where('subscription_id', $this->subscription->id) ->where('client_id', $recurring_invoice->client_id) ->where('is_proforma', 0) ->where('is_deleted', 0) @@ -655,7 +655,7 @@ class SubscriptionService $pro_rata_refund_amount = 0; $is_credit = false; - $last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id) + $last_invoice = Invoice::query()->where('subscription_id', $recurring_invoice->subscription_id) ->where('client_id', $recurring_invoice->client_id) ->where('is_deleted', 0) ->withTrashed() @@ -667,7 +667,7 @@ class SubscriptionService } elseif (!$last_invoice) { $is_credit = true; - $last_invoice = Credit::where('subscription_id', $recurring_invoice->subscription_id) + $last_invoice = Credit::query()->where('subscription_id', $recurring_invoice->subscription_id) ->where('client_id', $recurring_invoice->client_id) ->where('is_deleted', 0) ->withTrashed() @@ -728,7 +728,7 @@ class SubscriptionService $pro_rata_charge_amount = 0; $pro_rata_refund_amount = 0; - $last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id) + $last_invoice = Invoice::query()->where('subscription_id', $recurring_invoice->subscription_id) ->where('client_id', $recurring_invoice->client_id) ->where('is_proforma', 0) ->where('is_deleted', 0) @@ -773,7 +773,7 @@ class SubscriptionService $pro_rata_charge_amount = 0; $pro_rata_refund_amount = 0; - $last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id) + $last_invoice = Invoice::query()->where('subscription_id', $recurring_invoice->subscription_id) ->where('client_id', $recurring_invoice->client_id) ->where('is_deleted', 0) ->where('is_proforma', 0) @@ -1127,7 +1127,7 @@ class SubscriptionService $body = $response->getStatusCode(); } - $client = Client::where('id', $this->decodePrimaryKey($body['client']))->withTrashed()->first(); + $client = Client::query()->where('id', $this->decodePrimaryKey($body['client']))->withTrashed()->first(); SystemLogger::dispatch( $body, @@ -1168,7 +1168,7 @@ class SubscriptionService if (is_array($keys)) { return Product::query()->whereIn('id', $keys)->get(); } else { - return Product::where('id', $keys)->get(); + return Product::query()->where('id', $keys)->get(); } } @@ -1188,7 +1188,7 @@ class SubscriptionService if (is_array($keys)) { return Product::query()->whereIn('id', $keys)->get(); } else { - return Product::where('id', $keys)->get(); + return Product::query()->where('id', $keys)->get(); } } @@ -1209,7 +1209,7 @@ class SubscriptionService if (is_array($keys)) { return Product::query()->whereIn('id', $keys)->get(); } else { - return Product::where('id', $keys)->get(); + return Product::query()->where('id', $keys)->get(); } } @@ -1229,7 +1229,7 @@ class SubscriptionService if (is_array($keys)) { return Product::query()->whereIn('id', $keys)->get(); } else { - return Product::where('id', $keys)->get(); + return Product::query()->where('id', $keys)->get(); } } @@ -1267,7 +1267,7 @@ class SubscriptionService $gateway_refund_attempted = false; //only refund if they are in the refund window. - $outstanding_invoice = Invoice::where('subscription_id', $this->subscription->id) + $outstanding_invoice = Invoice::query()->where('subscription_id', $this->subscription->id) ->where('client_id', $recurring_invoice->client_id) ->where('status_id', Invoice::STATUS_PAID) ->where('is_deleted', 0) diff --git a/app/Utils/TemplateEngine.php b/app/Utils/TemplateEngine.php index 09b5ea8b9c..a0a1610c6d 100644 --- a/app/Utils/TemplateEngine.php +++ b/app/Utils/TemplateEngine.php @@ -98,17 +98,17 @@ class TemplateEngine if (strlen($this->entity) > 1 && strlen($this->entity_id) > 1) { $class = 'App\Models\\' . ucfirst(Str::camel($this->entity)); $this->entity_obj = $class::withTrashed()->where('id', $this->decodePrimaryKey($this->entity_id))->company()->first(); - } elseif (stripos($this->template, 'quote') !== false && $quote = Quote::whereHas('invitations')->withTrashed()->company()->first()) { + } elseif (stripos($this->template, 'quote') !== false && $quote = Quote::query()->whereHas('invitations')->withTrashed()->company()->first()) { $this->entity = 'quote'; $this->entity_obj = $quote; - } elseif (stripos($this->template, 'purchase') !== false && $purchase_order = PurchaseOrder::whereHas('invitations')->withTrashed()->company()->first()) { + } elseif (stripos($this->template, 'purchase') !== false && $purchase_order = PurchaseOrder::query()->whereHas('invitations')->withTrashed()->company()->first()) { $this->entity = 'purchase_order'; $this->entity_obj = $purchase_order; - }elseif (stripos($this->template, 'payment') !== false && $payment = Payment::withTrashed()->company()->first()) { + }elseif (stripos($this->template, 'payment') !== false && $payment = Payment::query()->withTrashed()->company()->first()) { $this->entity = 'payment'; $this->entity_obj = $payment; } - elseif ($invoice = Invoice::whereHas('invitations')->withTrashed()->company()->first()) { + elseif ($invoice = Invoice::query()->whereHas('invitations')->withTrashed()->company()->first()) { $this->entity_obj = $invoice; } else { $this->mockEntity(); diff --git a/database/migrations/2020_09_27_215800_update_gateway_table_visible_column.php b/database/migrations/2020_09_27_215800_update_gateway_table_visible_column.php index a92881cca4..f246f588bf 100644 --- a/database/migrations/2020_09_27_215800_update_gateway_table_visible_column.php +++ b/database/migrations/2020_09_27_215800_update_gateway_table_visible_column.php @@ -23,7 +23,7 @@ return new class extends Migration { { Gateway::query()->update(['visible' => 0]); - Gateway::whereIn('id', [1, 15, 20, 39])->update(['visible' => 1]); + Gateway::query()->whereIn('id', [1, 15, 20, 39])->update(['visible' => 1]); Schema::table('recurring_invoice_invitations', function ($t) { $t->string('transaction_reference')->nullable(); diff --git a/database/migrations/2020_12_23_220648_remove_null_values_in_countries_table.php b/database/migrations/2020_12_23_220648_remove_null_values_in_countries_table.php index d7c605e661..d18acf9b66 100644 --- a/database/migrations/2020_12_23_220648_remove_null_values_in_countries_table.php +++ b/database/migrations/2020_12_23_220648_remove_null_values_in_countries_table.php @@ -13,8 +13,8 @@ return new class extends Migration { */ public function up() { - $countries = Country::whereNull('thousand_separator')->update(['thousand_separator' => '']); - $countries = Country::whereNull('decimal_separator')->update(['decimal_separator' => '']); + $countries = Country::query()->whereNull('thousand_separator')->update(['thousand_separator' => '']); + $countries = Country::query()->whereNull('decimal_separator')->update(['decimal_separator' => '']); } /** diff --git a/database/migrations/2021_03_08_205030_add_russian_lang.php b/database/migrations/2021_03_08_205030_add_russian_lang.php index f13e135706..24bf0df260 100644 --- a/database/migrations/2021_03_08_205030_add_russian_lang.php +++ b/database/migrations/2021_03_08_205030_add_russian_lang.php @@ -23,7 +23,7 @@ return new class extends Migration { $table->integer('default_password_timeout')->default(30); }); - Company::whereNotNull('id')->update(['default_password_timeout' => 30]); + Company::query()->whereNotNull('id')->update(['default_password_timeout' => 30]); } /** diff --git a/database/migrations/2021_04_12_095424_stripe_connect_gateway.php b/database/migrations/2021_04_12_095424_stripe_connect_gateway.php index 8a5dff4845..a53d737ad8 100644 --- a/database/migrations/2021_04_12_095424_stripe_connect_gateway.php +++ b/database/migrations/2021_04_12_095424_stripe_connect_gateway.php @@ -27,8 +27,8 @@ return new class extends Migration { Gateway::create($gateway); if (Ninja::isHosted()) { - Gateway::whereIn('id', [20])->update(['visible' => 0]); - Gateway::whereIn('id', [56])->update(['visible' => 1]); + Gateway::query()->whereIn('id', [20])->update(['visible' => 0]); + Gateway::query()->whereIn('id', [56])->update(['visible' => 1]); } } diff --git a/database/migrations/2021_04_22_110240_add_property_to_checkout_gateway_config.php b/database/migrations/2021_04_22_110240_add_property_to_checkout_gateway_config.php index 937dd3bace..734063651b 100644 --- a/database/migrations/2021_04_22_110240_add_property_to_checkout_gateway_config.php +++ b/database/migrations/2021_04_22_110240_add_property_to_checkout_gateway_config.php @@ -15,7 +15,7 @@ return new class extends Migration { */ public function up() { - $gateway = Gateway::where('key', '3758e7f7c6f4cecf0f4f348b9a00f456')->first(); + $gateway = Gateway::query()->where('key', '3758e7f7c6f4cecf0f4f348b9a00f456')->first(); if ($gateway) { $fields = json_decode($gateway->fields); @@ -25,7 +25,7 @@ return new class extends Migration { $gateway->save(); } - CompanyGateway::where('gateway_key', '3758e7f7c6f4cecf0f4f348b9a00f456')->each(function ($checkout) { + CompanyGateway::query()->where('gateway_key', '3758e7f7c6f4cecf0f4f348b9a00f456')->each(function ($checkout) { $config = json_decode(decrypt($checkout->config)); $config->threeds = false; diff --git a/database/migrations/2021_05_03_152940_make_braintree_provider_visible.php b/database/migrations/2021_05_03_152940_make_braintree_provider_visible.php index b4610612d9..20ff447540 100644 --- a/database/migrations/2021_05_03_152940_make_braintree_provider_visible.php +++ b/database/migrations/2021_05_03_152940_make_braintree_provider_visible.php @@ -11,7 +11,7 @@ return new class extends Migration { */ public function up() { - Gateway::where('id', 50)->update(['visible' => 1]); + Gateway::query()->where('id', 50)->update(['visible' => 1]); } /** diff --git a/database/migrations/2021_05_05_014713_activate_we_pay.php b/database/migrations/2021_05_05_014713_activate_we_pay.php index ab88783c5e..1cbfa10ad1 100644 --- a/database/migrations/2021_05_05_014713_activate_we_pay.php +++ b/database/migrations/2021_05_05_014713_activate_we_pay.php @@ -13,7 +13,7 @@ return new class extends Migration { public function up() { if (Gateway::count() >= 1 && Ninja::isHosted()) { - Gateway::whereIn('id', [49])->update(['visible' => true]); + Gateway::query()->whereIn('id', [49])->update(['visible' => true]); } } diff --git a/database/migrations/2021_05_30_100933_make_documents_assigned_user_nullable.php b/database/migrations/2021_05_30_100933_make_documents_assigned_user_nullable.php index b5d6ed974f..f2a65b7399 100644 --- a/database/migrations/2021_05_30_100933_make_documents_assigned_user_nullable.php +++ b/database/migrations/2021_05_30_100933_make_documents_assigned_user_nullable.php @@ -18,14 +18,14 @@ return new class extends Migration { $table->unsignedInteger('assigned_user_id')->nullable()->change(); }); - Document::where('assigned_user_id', 0)->update(['assigned_user_id' => null]); + Document::query()->where('assigned_user_id', 0)->update(['assigned_user_id' => null]); if (config('ninja.db.multi_db_enabled')) { foreach (MultiDB::$dbs as $db) { Document::on($db)->where('assigned_user_id', 0)->update(['assigned_user_id' => null]); } } else { - Document::where('assigned_user_id', 0)->update(['assigned_user_id' => null]); + Document::query()->where('assigned_user_id', 0)->update(['assigned_user_id' => null]); } } diff --git a/database/migrations/2021_07_10_085821_activate_payfast_payment_driver.php b/database/migrations/2021_07_10_085821_activate_payfast_payment_driver.php index fb0345a8c3..f87334dc8e 100644 --- a/database/migrations/2021_07_10_085821_activate_payfast_payment_driver.php +++ b/database/migrations/2021_07_10_085821_activate_payfast_payment_driver.php @@ -11,7 +11,7 @@ return new class extends Migration { */ public function up() { - Gateway::whereIn('id', [11])->update(['visible' => 1]); + Gateway::query()->whereIn('id', [11])->update(['visible' => 1]); } /** diff --git a/database/migrations/2021_08_05_235942_add_zelle_payment_type.php b/database/migrations/2021_08_05_235942_add_zelle_payment_type.php index 9b88b6d7e9..7104b7dbee 100644 --- a/database/migrations/2021_08_05_235942_add_zelle_payment_type.php +++ b/database/migrations/2021_08_05_235942_add_zelle_payment_type.php @@ -14,7 +14,7 @@ return new class extends Migration { { Model::unguard(); - $pt = PaymentType::where('name', 'Zelle')->first(); + $pt = PaymentType::query()->where('name', 'Zelle')->first(); if (! $pt) { $payment_type = new PaymentType(); diff --git a/database/migrations/2021_09_23_100629_add_currencies.php b/database/migrations/2021_09_23_100629_add_currencies.php index 46a8ec71ae..3e319f8a71 100644 --- a/database/migrations/2021_09_23_100629_add_currencies.php +++ b/database/migrations/2021_09_23_100629_add_currencies.php @@ -25,7 +25,7 @@ return new class extends Migration { ]; foreach ($currencies as $currency) { - $record = Currency::whereCode($currency['code'])->first(); + $record = Currency::query()->whereCode($currency['code'])->first(); if ($record) { $record->name = $currency['name']; $record->symbol = $currency['symbol']; diff --git a/database/migrations/2021_09_29_190258_add_required_client_registration_fields.php b/database/migrations/2021_09_29_190258_add_required_client_registration_fields.php index ca5cfc7178..3b2a37765f 100644 --- a/database/migrations/2021_09_29_190258_add_required_client_registration_fields.php +++ b/database/migrations/2021_09_29_190258_add_required_client_registration_fields.php @@ -32,7 +32,7 @@ return new class extends Migration { ]; foreach ($currencies as $currency) { - $record = Currency::whereCode($currency['code'])->first(); + $record = Currency::query()->whereCode($currency['code'])->first(); if ($record) { $record->name = $currency['name']; $record->symbol = $currency['symbol']; diff --git a/database/migrations/2022_01_19_232436_add_kyd_currency.php b/database/migrations/2022_01_19_232436_add_kyd_currency.php index ecac6e4dc3..6bd5cb02a2 100644 --- a/database/migrations/2022_01_19_232436_add_kyd_currency.php +++ b/database/migrations/2022_01_19_232436_add_kyd_currency.php @@ -18,7 +18,7 @@ return new class extends Migration { ]; foreach ($currencies as $currency) { - $record = Currency::whereCode($currency['code'])->first(); + $record = Currency::query()->whereCode($currency['code'])->first(); if ($record) { $record->name = $currency['name']; $record->symbol = $currency['symbol']; diff --git a/database/migrations/2022_02_25_015411_update_stripe_apple_domain_config.php b/database/migrations/2022_02_25_015411_update_stripe_apple_domain_config.php index 81d7736510..01f04630c9 100644 --- a/database/migrations/2022_02_25_015411_update_stripe_apple_domain_config.php +++ b/database/migrations/2022_02_25_015411_update_stripe_apple_domain_config.php @@ -11,7 +11,7 @@ return new class extends Migration { */ public function up() { - CompanyGateway::whereIn('gateway_key', ['d14dd26a47cecc30fdd65700bfb67b34', 'd14dd26a37cecc30fdd65700bfb55b23'])->cursor()->each(function ($cg) { + CompanyGateway::query()->whereIn('gateway_key', ['d14dd26a47cecc30fdd65700bfb67b34', 'd14dd26a37cecc30fdd65700bfb55b23'])->cursor()->each(function ($cg) { $config = $cg->getConfig(); if (! property_exists($config, 'appleDomainVerification')) { diff --git a/database/migrations/2022_09_21_012417_add_threeds_to_braintree.php b/database/migrations/2022_09_21_012417_add_threeds_to_braintree.php index d3f7033b1c..af159d2645 100644 --- a/database/migrations/2022_09_21_012417_add_threeds_to_braintree.php +++ b/database/migrations/2022_09_21_012417_add_threeds_to_braintree.php @@ -22,7 +22,7 @@ return new class extends Migration { $g->save(); } - CompanyGateway::where('gateway_key', 'f7ec488676d310683fb51802d076d713')->cursor()->each(function ($cg) { + CompanyGateway::query()->where('gateway_key', 'f7ec488676d310683fb51802d076d713')->cursor()->each(function ($cg) { $config = $cg->getConfig(); $config->threeds = false; $cg->setConfig($config); diff --git a/database/migrations/2022_11_22_215618_lock_tasks_when_invoiced.php b/database/migrations/2022_11_22_215618_lock_tasks_when_invoiced.php index 75b0d655b4..29bb60d3f6 100644 --- a/database/migrations/2022_11_22_215618_lock_tasks_when_invoiced.php +++ b/database/migrations/2022_11_22_215618_lock_tasks_when_invoiced.php @@ -43,7 +43,7 @@ return new class extends Migration { ]; foreach ($currencies as $currency) { - $record = Currency::whereCode($currency['code'])->first(); + $record = Currency::query()->whereCode($currency['code'])->first(); if ($record) { $record->name = $currency['name']; $record->symbol = $currency['symbol']; diff --git a/database/migrations/2023_03_10_100629_add_currencies.php b/database/migrations/2023_03_10_100629_add_currencies.php index b0a15d6a7d..5e3be49173 100644 --- a/database/migrations/2023_03_10_100629_add_currencies.php +++ b/database/migrations/2023_03_10_100629_add_currencies.php @@ -19,7 +19,7 @@ return new class extends Migration { ]; foreach ($currencies as $currency) { - $record = Currency::whereCode($currency['code'])->first(); + $record = Currency::query()->whereCode($currency['code'])->first(); if ($record) { $record->name = $currency['name']; $record->symbol = $currency['symbol']; diff --git a/database/migrations/2023_03_21_053933_tax_calculations_for_invoices.php b/database/migrations/2023_03_21_053933_tax_calculations_for_invoices.php index 7602205623..8d5d3c1ce7 100644 --- a/database/migrations/2023_03_21_053933_tax_calculations_for_invoices.php +++ b/database/migrations/2023_03_21_053933_tax_calculations_for_invoices.php @@ -42,7 +42,7 @@ return new class extends Migration $table->string('name', 191)->nullable()->change(); }); - CompanyUser::where('is_admin', 0)->cursor()->each(function ($cu) { + CompanyUser::query()->where('is_admin', 0)->cursor()->each(function ($cu) { $permissions = $cu->permissions; if (!$permissions || strlen($permissions) == 0) { diff --git a/database/migrations/2023_07_22_234329_change_currency_format_for_indonesian_rupiah.php b/database/migrations/2023_07_22_234329_change_currency_format_for_indonesian_rupiah.php index c8a1a8abb0..20316a338f 100644 --- a/database/migrations/2023_07_22_234329_change_currency_format_for_indonesian_rupiah.php +++ b/database/migrations/2023_07_22_234329_change_currency_format_for_indonesian_rupiah.php @@ -13,7 +13,7 @@ return new class extends Migration */ public function up() { - $ir = \App\Models\Currency::where('code', 'IDR')->first(); + $ir = \App\Models\Currency::query()->where('code', 'IDR')->first(); if($ir){ $ir->thousand_separator = '.'; diff --git a/database/migrations/2023_08_06_070205_create_view_dashboard_permission_migration.php b/database/migrations/2023_08_06_070205_create_view_dashboard_permission_migration.php index ae8dbe4456..472f6b92c5 100644 --- a/database/migrations/2023_08_06_070205_create_view_dashboard_permission_migration.php +++ b/database/migrations/2023_08_06_070205_create_view_dashboard_permission_migration.php @@ -13,7 +13,7 @@ return new class extends Migration */ public function up() { - \App\Models\CompanyUser::where('is_admin', 0)->cursor()->each(function ($cu) { + \App\Models\CompanyUser::query()->where('is_admin', 0)->cursor()->each(function ($cu) { $permissions = $cu->permissions; if (!$permissions || strlen($permissions) == 0) { diff --git a/phpstan.neon b/phpstan.neon index 42ed898676..8e7747dc3a 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -17,6 +17,5 @@ parameters: ignoreErrors: - '#Call to an undefined method [a-zA-Z0-9\\_]+::company\(\)#' - '#Call to an undefined method [a-zA-Z0-9\\_]+::entityFilter\(\)#' - - '#Call to an undefined method [a-zA-Z0-9\\_]+::withTrashed\(\)#' - '#Call to an undefined method [a-zA-Z0-9\\_]+::exclude\(\)#' - '#Undefined method#' \ No newline at end of file diff --git a/tests/Feature/BankTransactionApiTest.php b/tests/Feature/BankTransactionApiTest.php index f27aa681f8..a79cd8e507 100644 --- a/tests/Feature/BankTransactionApiTest.php +++ b/tests/Feature/BankTransactionApiTest.php @@ -147,7 +147,7 @@ class BankTransactionApiTest extends TestCase 'ids' => [$this->encodePrimaryKey($bank_transaction->id)], ]; - nlog($bank_transaction->toArray()); + // nlog($bank_transaction->toArray()); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, diff --git a/tests/Feature/ClientTest.php b/tests/Feature/ClientTest.php index 83c8420161..8fcef3d6c1 100644 --- a/tests/Feature/ClientTest.php +++ b/tests/Feature/ClientTest.php @@ -113,7 +113,7 @@ class ClientTest extends TestCase $c = $c->fresh(); - nlog($c->contacts->pluck('email')); + // nlog($c->contacts->pluck('email')); $this->assertEquals(4, $c->contacts->count()); diff --git a/tests/Feature/CompanyTest.php b/tests/Feature/CompanyTest.php index af02f493ea..6d0fefbc2b 100644 --- a/tests/Feature/CompanyTest.php +++ b/tests/Feature/CompanyTest.php @@ -143,7 +143,7 @@ class CompanyTest extends TestCase $company->settings = $settings; - nlog($company->toArray()); + // nlog($company->toArray()); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), From 4290ba9db6ac183ec324a77ce8b89b006f793d1b Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sun, 6 Aug 2023 17:41:40 +1000 Subject: [PATCH 05/33] Updates for static analysis --- app/Http/Livewire/BillingPortalPurchasev2.php | 4 ++-- app/Models/Client.php | 16 ++++++++-------- app/Models/CompanyGateway.php | 2 +- app/Models/Subscription.php | 2 +- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/app/Http/Livewire/BillingPortalPurchasev2.php b/app/Http/Livewire/BillingPortalPurchasev2.php index 2e1272e5e8..c7e83488b1 100644 --- a/app/Http/Livewire/BillingPortalPurchasev2.php +++ b/app/Http/Livewire/BillingPortalPurchasev2.php @@ -122,7 +122,7 @@ class BillingPortalPurchasev2 extends Component /** * Instance of company. * - * @var Company + * @var \App\Models\Company */ public $company; @@ -498,7 +498,7 @@ class BillingPortalPurchasev2 extends Component /** * Method to handle events before payments. * - * @return void + * @return self */ public function handleBeforePaymentEvents() :self { diff --git a/app/Models/Client.php b/app/Models/Client.php index ac764cbcf6..0370601cba 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -231,7 +231,7 @@ class Client extends BaseModel implements HasLocalePreference return self::class; } - public function ledger() + public function ledger(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(CompanyLedger::class)->orderBy('id', 'desc'); } @@ -241,17 +241,17 @@ class Client extends BaseModel implements HasLocalePreference return $this->morphMany(CompanyLedger::class, 'company_ledgerable'); } - public function gateway_tokens() + public function gateway_tokens(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(ClientGatewayToken::class)->orderBy('is_default', 'DESC'); } - public function expenses() + public function expenses(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Expense::class)->withTrashed(); } - public function projects() + public function projects(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Project::class)->withTrashed(); } @@ -275,17 +275,17 @@ class Client extends BaseModel implements HasLocalePreference ->first(); } - public function credits() + public function credits(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Credit::class)->withTrashed(); } - public function purgeable_activities() + public function purgeable_activities(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Activity::class); } - public function activities() + public function activities(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Activity::class)->take(50)->orderBy('id', 'desc'); } @@ -350,7 +350,7 @@ class Client extends BaseModel implements HasLocalePreference return $this->hasMany(RecurringExpense::class)->withTrashed(); } - public function shipping_country() + public function shipping_country():\Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Country::class, 'shipping_country_id', 'id'); } diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php index e4c2aa5505..a8e7540eae 100644 --- a/app/Models/CompanyGateway.php +++ b/app/Models/CompanyGateway.php @@ -61,8 +61,8 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @method static \Illuminate\Database\Eloquent\Builder|BaseModel scope() * @method static \Illuminate\Database\Eloquent\Builder|CompanyGateway withTrashed() * @method static \Illuminate\Database\Eloquent\Builder|CompanyGateway withoutTrashed() - * @method static CompanyGateway find() * @property-read \Illuminate\Database\Eloquent\Collection $client_gateway_tokens + * @method static CompanyGateway find($value) * @mixin \Eloquent */ class CompanyGateway extends BaseModel diff --git a/app/Models/Subscription.php b/app/Models/Subscription.php index 3798a69433..ea3cfcb49c 100644 --- a/app/Models/Subscription.php +++ b/app/Models/Subscription.php @@ -53,7 +53,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property int $use_inventory_management * @property string|null $optional_product_ids * @property string|null $optional_recurring_product_ids - * @property-read \App\Models\Company $company + * @property \App\Models\Company $company * @property-read mixed $hashed_id * @property-read \App\Models\GroupSetting|null $group_settings * @property-read \App\Models\User $user From d9589bdea27bba6cbd7e35dbba69708014ffef93 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sun, 6 Aug 2023 17:52:19 +1000 Subject: [PATCH 06/33] Updates for static analysis --- app/Utils/Traits/Payment/Refundable.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Utils/Traits/Payment/Refundable.php b/app/Utils/Traits/Payment/Refundable.php index 482db74c39..08943fb402 100644 --- a/app/Utils/Traits/Payment/Refundable.php +++ b/app/Utils/Traits/Payment/Refundable.php @@ -237,6 +237,7 @@ trait Refundable $adjustment_amount = 0; foreach ($data['invoices'] as $refunded_invoice) { + /** @var \App\Models\Invoice $invoice */ $invoice = Invoice::find($refunded_invoice['invoice_id']); $invoice->service()->updateBalance($refunded_invoice['amount'])->save(); From e76b650a0b3b5fed205356bf660f758699a68a62 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sun, 6 Aug 2023 17:53:06 +1000 Subject: [PATCH 07/33] Updates for static analysis --- app/Utils/Traits/Payment/Refundable.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Utils/Traits/Payment/Refundable.php b/app/Utils/Traits/Payment/Refundable.php index 08943fb402..2c908894dc 100644 --- a/app/Utils/Traits/Payment/Refundable.php +++ b/app/Utils/Traits/Payment/Refundable.php @@ -109,6 +109,7 @@ trait Refundable $ledger_string = ''; foreach ($data['invoices'] as $invoice) { + /** @var \App\Models\Invoice $inv */ $inv = Invoice::find($invoice['invoice_id']); $credit_line_item = InvoiceItemFactory::create(); From 81bad287ca5ad26247ffc74c5ee0ea2d8d6af249 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sun, 6 Aug 2023 17:56:26 +1000 Subject: [PATCH 08/33] Updates for static analysis --- app/Models/Client.php | 6 +++--- app/Models/Payment.php | 2 +- app/Utils/Traits/Payment/Refundable.php | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/Models/Client.php b/app/Models/Client.php index 0370601cba..c815fc5992 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -47,9 +47,9 @@ use Illuminate\Contracts\Translation\HasLocalePreference; * @property string|null $logo * @property string|null $phone * @property string|null $routing_id - * @property string $balance - * @property string $paid_to_date - * @property string $credit_balance + * @property float $balance + * @property float $paid_to_date + * @property float $credit_balance * @property int|null $last_login * @property int|null $industry_id * @property int|null $size_id diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 091cf57110..2da14a4ac8 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -56,7 +56,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property float $exchange_rate * @property int $currency_id * @property int|null $exchange_currency_id - * @property \App\Models\Paymentable $paymentables + * @property \App\Models\Paymentable $paymentable * @property object|null $meta * @property string|null $custom_value1 * @property string|null $custom_value2 diff --git a/app/Utils/Traits/Payment/Refundable.php b/app/Utils/Traits/Payment/Refundable.php index 2c908894dc..9033374379 100644 --- a/app/Utils/Traits/Payment/Refundable.php +++ b/app/Utils/Traits/Payment/Refundable.php @@ -171,6 +171,7 @@ trait Refundable $credit_note->save(); if ($data['gateway_refund'] !== false && $total_refund > 0) { + /** @var \App\Models\CompanyGateway $gateway */ $gateway = CompanyGateway::find($this->company_gateway_id); if ($gateway) { @@ -190,8 +191,7 @@ trait Refundable $client_balance_adjustment = $this->adjustInvoices($data); - // $credit_note->ledger()->updateCreditBalance($client_balance_adjustment, $ledger_string); - + /** @var \App\Models\Client $this->client */ $this->client->paid_to_date -= $data['amount']; $this->client->save(); From f1864227413f81cbf55f6f491d57e680e5454754 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sun, 6 Aug 2023 18:18:36 +1000 Subject: [PATCH 09/33] Updates for static analysis --- app/Http/ValidationRules/ValidRefundableInvoices.php | 1 + app/Models/Payment.php | 4 +--- app/Utils/Traits/Payment/Refundable.php | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/app/Http/ValidationRules/ValidRefundableInvoices.php b/app/Http/ValidationRules/ValidRefundableInvoices.php index 7b4abfce5e..6867b04b1e 100644 --- a/app/Http/ValidationRules/ValidRefundableInvoices.php +++ b/app/Http/ValidationRules/ValidRefundableInvoices.php @@ -72,6 +72,7 @@ class ValidRefundableInvoices implements Rule foreach ($this->input['invoices'] as $val) { if ($val['invoice_id'] == $invoice->id) { + /** @var \App\Models\Paymentable $pivot_record */ $pivot_record = $payment->paymentables->where('paymentable_id', $invoice->id)->first(); if ($val['amount'] > ($pivot_record->amount - $pivot_record->refunded)) { diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 2da14a4ac8..cc1576912a 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -77,7 +77,6 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property-read \App\Models\PaymentType|null $type * @property-read \App\Models\User|null $user * @property-read \App\Models\Vendor|null $vendor - * @method static \Illuminate\Database\Eloquent\Builder exclude($columns) * @method static \Database\Factories\PaymentFactory factory($count = null, $state = []) * @method static \Illuminate\Database\Eloquent\Builder|Payment filter(\App\Filters\QueryFilters $filters) * @method static \Illuminate\Database\Eloquent\Builder|Payment newModelQuery() @@ -90,8 +89,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property-read \Illuminate\Database\Eloquent\Collection $credits * @property-read \Illuminate\Database\Eloquent\Collection $documents * @property-read \Illuminate\Database\Eloquent\Collection $invoices - * @property-read \Illuminate\Database\Eloquent\Collection $paymentables - * @method static \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder withTrashed(bool $withTrashed = true) + * @property \Illuminate\Database\Eloquent\Collection $paymentables * @mixin \Eloquent */ class Payment extends BaseModel diff --git a/app/Utils/Traits/Payment/Refundable.php b/app/Utils/Traits/Payment/Refundable.php index 9033374379..442c1dfdad 100644 --- a/app/Utils/Traits/Payment/Refundable.php +++ b/app/Utils/Traits/Payment/Refundable.php @@ -191,7 +191,7 @@ trait Refundable $client_balance_adjustment = $this->adjustInvoices($data); - /** @var \App\Models\Client $this->client */ + /** @var \App\Models\Payment $this */ $this->client->paid_to_date -= $data['amount']; $this->client->save(); From c0bd70454ebcae2a0cb8ae0759b68dea8f0e21d5 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 07:33:33 +1000 Subject: [PATCH 10/33] Add permissions for view_dashboard --- app/DataMapper/Tax/AU/Rule.php | 4 ++-- app/Http/Requests/Chart/ShowChartRequest.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/DataMapper/Tax/AU/Rule.php b/app/DataMapper/Tax/AU/Rule.php index aa11658ae1..d6536e1a71 100644 --- a/app/DataMapper/Tax/AU/Rule.php +++ b/app/DataMapper/Tax/AU/Rule.php @@ -250,8 +250,8 @@ class Rule extends BaseRule implements RuleInterface // $this->reduced_tax_rate = $this->client->company->tax_data->regions->EU->subregions->{$this->client->company->country()->iso_3166_2}->reduced_tax_rate; // } - $this->tax_rate = $this->client->company->tax_data->regions->AU->subregions->{$this->client->company->country()->iso_3166_2}->tax_rate; - $this->reduced_tax_rate = $this->client->company->tax_data->regions->AU->subregions->{$this->client->company->country()->iso_3166_2}->tax_rate; + $this->tax_rate = $this->client->company->tax_data->regions->AU->subregions->{$this->client->company->country()->iso_3166_2}->tax_rate ?? 0; + $this->reduced_tax_rate = $this->client->company->tax_data->regions->AU->subregions->{$this->client->company->country()->iso_3166_2}->tax_rate ?? 0; return $this; diff --git a/app/Http/Requests/Chart/ShowChartRequest.php b/app/Http/Requests/Chart/ShowChartRequest.php index 39517cd29d..afeb28ca36 100644 --- a/app/Http/Requests/Chart/ShowChartRequest.php +++ b/app/Http/Requests/Chart/ShowChartRequest.php @@ -28,7 +28,7 @@ class ShowChartRequest extends Request /**@var \App\Models\User auth()->user */ $user = auth()->user(); - return $user->isAdmin(); + return $user->isAdmin() || $user->hasPermission('view_dashboard'); } public function rules() From 73274f545ac55515a727a64e7c1fca013b49869d Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 07:34:37 +1000 Subject: [PATCH 11/33] Static analysis --- app/Http/Requests/Chart/ShowChartRequest.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/Http/Requests/Chart/ShowChartRequest.php b/app/Http/Requests/Chart/ShowChartRequest.php index afeb28ca36..8aa72afb38 100644 --- a/app/Http/Requests/Chart/ShowChartRequest.php +++ b/app/Http/Requests/Chart/ShowChartRequest.php @@ -42,10 +42,14 @@ class ShowChartRequest extends Request public function prepareForValidation() { + + /**@var \App\Models\User auth()->user */ + $user = auth()->user(); + $input = $this->all(); if(isset($input['date_range'])) { - $dates = $this->calculateStartAndEndDates($input, auth()->user()->company()); + $dates = $this->calculateStartAndEndDates($input, $user->company()); $input['start_date'] = $dates[0]; $input['end_date'] = $dates[1]; } From f01fa763c10db356396458d70bec8edbac3975c8 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 08:23:13 +1000 Subject: [PATCH 12/33] Updates for static analysis --- app/Export/CSV/RecurringInvoiceExport.php | 1 - app/Http/Livewire/InvoicesTable.php | 5 +- .../PaymentMethods/UpdateDefaultMethod.php | 2 +- app/Http/Livewire/RequiredClientInfo.php | 3 +- app/Http/Livewire/WepaySignup.php | 6 +- app/Http/Middleware/ClientPortalEnabled.php | 5 +- app/Http/Middleware/ContactAccount.php | 1 + app/Http/Middleware/ContactKeyLogin.php | 4 +- app/Http/Middleware/ContactRegister.php | 2 +- app/Jobs/Cron/UpdateCalculatedFields.php | 2 +- app/Libraries/OAuth/OAuth.php | 2 +- app/Mail/DownloadBackup.php | 2 +- app/Models/Client.php | 1 + app/Models/ClientContact.php | 1 - app/Models/ClientGatewayToken.php | 10 +- app/Models/CompanyGateway.php | 2 +- app/Models/CompanyUser.php | 50 ++---- app/Models/Payment.php | 38 ++-- .../CheckoutCom/CheckoutSetupWebhook.php | 1 + app/PaymentDrivers/Stripe/ACH.php | 2 +- .../Subscription/SubscriptionService.php | 16 +- .../TaskScheduler/TaskSchedulerService.php | 165 ------------------ app/Transformers/TaskStatusTransformer.php | 2 +- 23 files changed, 75 insertions(+), 248 deletions(-) delete mode 100644 app/Services/TaskScheduler/TaskSchedulerService.php diff --git a/app/Export/CSV/RecurringInvoiceExport.php b/app/Export/CSV/RecurringInvoiceExport.php index 6df397c648..330f29695c 100644 --- a/app/Export/CSV/RecurringInvoiceExport.php +++ b/app/Export/CSV/RecurringInvoiceExport.php @@ -66,7 +66,6 @@ class RecurringInvoiceExport extends BaseExport 'vendor' => 'vendor_id', 'project' => 'project_id', 'frequency_id' => 'frequency_id', - 'next_send_date' => 'next_send_date' ]; private array $decorate_keys = [ diff --git a/app/Http/Livewire/InvoicesTable.php b/app/Http/Livewire/InvoicesTable.php index 9a84f50870..80b43cdd00 100644 --- a/app/Http/Livewire/InvoicesTable.php +++ b/app/Http/Livewire/InvoicesTable.php @@ -89,9 +89,12 @@ class InvoicesTable extends Component ->withTrashed() ->paginate($this->per_page); + /** @var \App\Models\ClientContact $client_contact */ + $client_contact = auth()->user(); + return render('components.livewire.invoices-table', [ 'invoices' => $query, - 'gateway_available' => ! empty(auth()->user()->client->service()->getPaymentMethods(-1)), + 'gateway_available' => ! empty($client_contact->client->service()->getPaymentMethods(-1)), ]); } } diff --git a/app/Http/Livewire/PaymentMethods/UpdateDefaultMethod.php b/app/Http/Livewire/PaymentMethods/UpdateDefaultMethod.php index e8f6786393..565d08b0da 100644 --- a/app/Http/Livewire/PaymentMethods/UpdateDefaultMethod.php +++ b/app/Http/Livewire/PaymentMethods/UpdateDefaultMethod.php @@ -32,7 +32,7 @@ class UpdateDefaultMethod extends Component MultiDB::setDb($this->company->db); - $this->is_disabled = $this->token->is_default; + // $this->is_disabled = $this->token->is_default; } public function makeDefault(): void diff --git a/app/Http/Livewire/RequiredClientInfo.php b/app/Http/Livewire/RequiredClientInfo.php index f877753867..4027c8698c 100644 --- a/app/Http/Livewire/RequiredClientInfo.php +++ b/app/Http/Livewire/RequiredClientInfo.php @@ -52,7 +52,7 @@ class RequiredClientInfo extends Component public $contact; /** - * @var Client + * @var \App\Models\Client */ public $client; @@ -227,6 +227,7 @@ class RequiredClientInfo extends Component ->push(); if ($contact_update && $client_update) { + /** @var \App\Models\CompanyGateway $cg */ $cg = CompanyGateway::find($this->company_gateway_id); if ($cg && $cg->update_details) { diff --git a/app/Http/Livewire/WepaySignup.php b/app/Http/Livewire/WepaySignup.php index 7ef0b68ea0..5524cc1731 100644 --- a/app/Http/Livewire/WepaySignup.php +++ b/app/Http/Livewire/WepaySignup.php @@ -53,7 +53,7 @@ class WepaySignup extends Component public $saved; - public $company; + public Company $company; protected $rules = [ 'first_name' => ['required'], @@ -71,7 +71,7 @@ class WepaySignup extends Component MultiDB::setDb($this->company->db); $user = User::find($this->user_id); - $this->company = Company::where('company_key', $this->company->company_key)->first(); + $this->company = Company::query()->where('company_key', $this->company->company_key)->first(); $this->fill([ 'wepay_payment_tos_agree' => '', @@ -100,7 +100,7 @@ class WepaySignup extends Component $data = $this->validate($this->rules); //need to create or get a new WePay CompanyGateway - $cg = CompanyGateway::where('gateway_key', '8fdeed552015b3c7b44ed6c8ebd9e992') + $cg = CompanyGateway::query()->where('gateway_key', '8fdeed552015b3c7b44ed6c8ebd9e992') ->where('company_id', $this->company->id) ->firstOrNew(); diff --git a/app/Http/Middleware/ClientPortalEnabled.php b/app/Http/Middleware/ClientPortalEnabled.php index 57b63d02ce..c26e8ed64e 100644 --- a/app/Http/Middleware/ClientPortalEnabled.php +++ b/app/Http/Middleware/ClientPortalEnabled.php @@ -25,7 +25,10 @@ class ClientPortalEnabled */ public function handle($request, Closure $next) { - if (auth()->user()->client->getSetting('enable_client_portal') === false) { + /** @var \App\Models\ClientContact $client_contact */ + $client_contact = auth()->user(); + + if ($client_contact->client->getSetting('enable_client_portal') === false) { return redirect()->route('client.error')->with(['title' => ctrans('texts.client_portal'), 'notification' => 'This section of the app has been disabled by the administrator.']); } diff --git a/app/Http/Middleware/ContactAccount.php b/app/Http/Middleware/ContactAccount.php index 1cecef46a1..c91dbb7133 100644 --- a/app/Http/Middleware/ContactAccount.php +++ b/app/Http/Middleware/ContactAccount.php @@ -28,6 +28,7 @@ class ContactAccount public function handle($request, Closure $next) { if (! Ninja::isHosted()) { + /** @var \App\Models\Account $account */ $account = Account::first(); session()->put('account_key', $account->key); diff --git a/app/Http/Middleware/ContactKeyLogin.php b/app/Http/Middleware/ContactKeyLogin.php index b45f1c465c..e49306665e 100644 --- a/app/Http/Middleware/ContactKeyLogin.php +++ b/app/Http/Middleware/ContactKeyLogin.php @@ -67,7 +67,7 @@ class ContactKeyLogin } } elseif ($request->segment(3) && config('ninja.db.multi_db_enabled')) { if (MultiDB::findAndSetDbByContactKey($request->segment(3))) { - if ($client_contact = ClientContact::with('company')->where('contact_key', $request->segment(3))->first()) { + if ($client_contact = ClientContact::query()->with('company')->where('contact_key', $request->segment(3))->first()) { if ($client_contact->company->settings->enable_client_portal_password) { return redirect()->route('client.login', ['company_key' => $client_contact->company->company_key]); } @@ -107,7 +107,7 @@ class ContactKeyLogin } } elseif ($request->has('client_hash') && config('ninja.db.multi_db_enabled')) { if (MultiDB::findAndSetDbByClientHash($request->input('client_hash'))) { - if ($client = Client::where('client_hash', $request->input('client_hash'))->first()) { + if ($client = Client::query()->where('client_hash', $request->input('client_hash'))->first()) { $primary_contact = $client->primary_contact()->first(); if (empty($primary_contact->email)) { diff --git a/app/Http/Middleware/ContactRegister.php b/app/Http/Middleware/ContactRegister.php index 60e48d8771..97237cda8d 100644 --- a/app/Http/Middleware/ContactRegister.php +++ b/app/Http/Middleware/ContactRegister.php @@ -30,7 +30,7 @@ class ContactRegister 'portal_mode' => 'subdomain', ]; - $company = Company::where($query)->first(); + $company = Company::query()->where($query)->first(); if ($company) { if (! $company->client_can_register) { diff --git a/app/Jobs/Cron/UpdateCalculatedFields.php b/app/Jobs/Cron/UpdateCalculatedFields.php index 62ace5ac7d..e60b8483bb 100644 --- a/app/Jobs/Cron/UpdateCalculatedFields.php +++ b/app/Jobs/Cron/UpdateCalculatedFields.php @@ -43,7 +43,7 @@ class UpdateCalculatedFields if (! config('ninja.db.multi_db_enabled')) { - Project::with('tasks')->whereHas('tasks', function ($query){ + Project::query()->with('tasks')->whereHas('tasks', function ($query){ $query->where('updated_at', '>', now()->subHours(2)); }) ->cursor() diff --git a/app/Libraries/OAuth/OAuth.php b/app/Libraries/OAuth/OAuth.php index 59582bad18..c684c62ac6 100644 --- a/app/Libraries/OAuth/OAuth.php +++ b/app/Libraries/OAuth/OAuth.php @@ -40,7 +40,7 @@ class OAuth const SOCIAL_APPLE = 8; /** - * @param Socialite $user + * @param \Laravel\Socialite\Facades\Socialite $socialite_user * @return bool | \App\Models\User | \App\Models\User | null */ public static function handleAuth($socialite_user, $provider) diff --git a/app/Mail/DownloadBackup.php b/app/Mail/DownloadBackup.php index ffc89d21d0..d3daecacda 100644 --- a/app/Mail/DownloadBackup.php +++ b/app/Mail/DownloadBackup.php @@ -36,7 +36,7 @@ class DownloadBackup extends Mailable { App::setLocale($this->company->getLocale()); - $company = Company::where('company_key', $this->company->company_key)->first(); + $company = Company::query()->where('company_key', $this->company->company_key)->first(); return $this->from(config('mail.from.address'), config('mail.from.name')) ->subject(ctrans('texts.download_backup_subject', ['company' => $company->present()->name()])) diff --git a/app/Models/Client.php b/app/Models/Client.php index c815fc5992..f14e741e1e 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -106,6 +106,7 @@ use Illuminate\Contracts\Translation\HasLocalePreference; * @method static \Database\Factories\ClientFactory factory($count = null, $state = []) * @method static \Illuminate\Database\Eloquent\Builder|Client filter(\App\Filters\QueryFilters $filters) * @method static \Illuminate\Database\Eloquent\Builder|Client without() + * @method static \Illuminate\Database\Eloquent\Builder|Client select() * @property string $payment_balance * @property mixed $tax_data * @property int $is_tax_exempt diff --git a/app/Models/ClientContact.php b/app/Models/ClientContact.php index 0116d611b4..0ff98447c3 100644 --- a/app/Models/ClientContact.php +++ b/app/Models/ClientContact.php @@ -76,7 +76,6 @@ use Laracasts\Presenter\PresentableTrait; * @property-read int|null $quote_invitations_count * @property-read int|null $recurring_invoice_invitations_count * @property-read \App\Models\User $user - * @method static \Illuminate\Database\Eloquent\Builder|ClientContact company() * @method static \Database\Factories\ClientContactFactory factory($count = null, $state = []) * @method static \Illuminate\Database\Eloquent\Builder|ClientContact newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|ClientContact newQuery() diff --git a/app/Models/ClientGatewayToken.php b/app/Models/ClientGatewayToken.php index 2b6950048d..fd5ed8795b 100644 --- a/app/Models/ClientGatewayToken.php +++ b/app/Models/ClientGatewayToken.php @@ -69,27 +69,27 @@ class ClientGatewayToken extends BaseModel return self::class; } - public function client() + public function client(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Client::class)->withTrashed(); } - public function gateway() + public function gateway(): \Illuminate\Database\Eloquent\Relations\HasOne { return $this->hasOne(CompanyGateway::class, 'id', 'company_gateway_id'); } - public function gateway_type() + public function gateway_type(): \Illuminate\Database\Eloquent\Relations\HasOne { return $this->hasOne(GatewayType::class, 'id', 'gateway_type_id'); } - public function company() + public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Company::class); } - public function user() + public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(User::class)->withTrashed(); } diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php index a8e7540eae..0ad3651ec1 100644 --- a/app/Models/CompanyGateway.php +++ b/app/Models/CompanyGateway.php @@ -28,7 +28,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property bool $update_details * @property bool $is_deleted * @property string $config - * @property object $fees_and_limits + * @property mixed $fees_and_limits * @property string|null $custom_value1 * @property string|null $custom_value2 * @property string|null $custom_value3 diff --git a/app/Models/CompanyUser.php b/app/Models/CompanyUser.php index c07e2ed6a7..ba3306808f 100644 --- a/app/Models/CompanyUser.php +++ b/app/Models/CompanyUser.php @@ -13,8 +13,6 @@ namespace App\Models; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\Relations\Pivot; -use Illuminate\Database\Eloquent\Relations\HasOne; -use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * App\Models\CompanyUser @@ -79,34 +77,6 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; * @property-read \Illuminate\Database\Eloquent\Collection $cu * @property-read \Illuminate\Database\Eloquent\Collection $token * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users - * @property-read \Illuminate\Database\Eloquent\Collection $token - * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users - * @property-read \Illuminate\Database\Eloquent\Collection $token - * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users - * @property-read \Illuminate\Database\Eloquent\Collection $token - * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users - * @property-read \Illuminate\Database\Eloquent\Collection $token - * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users - * @property-read \Illuminate\Database\Eloquent\Collection $token - * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users - * @property-read \Illuminate\Database\Eloquent\Collection $token - * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users - * @property-read \Illuminate\Database\Eloquent\Collection $token - * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users - * @property-read \Illuminate\Database\Eloquent\Collection $token - * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users - * @property-read \Illuminate\Database\Eloquent\Collection $token - * @property-read \Illuminate\Database\Eloquent\Collection $tokens - * @property-read \Illuminate\Database\Eloquent\Collection $users * @mixin \Eloquent */ class CompanyUser extends Pivot @@ -153,32 +123,40 @@ class CompanyUser extends Pivot return self::class; } - public function account() + public function account(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Account::class); } + /** + * + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ public function user_pivot() { return $this->hasOne(User::class)->withPivot('permissions', 'settings', 'react_settings', 'is_admin', 'is_owner', 'is_locked', 'slack_webhook_url', 'migrating'); } - + + /** + * + * @return \Illuminate\Database\Eloquent\Relations\HasOne + */ public function company_pivot() { return $this->hasOne(Company::class)->withPivot('permissions', 'settings', 'react_settings', 'is_admin', 'is_owner', 'is_locked', 'slack_webhook_url', 'migrating'); } - public function user(): BelongsTo + public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(User::class)->withTrashed(); } - public function company() + public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Company::class); } - public function users() + public function users(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(User::class)->withTrashed(); } @@ -189,7 +167,7 @@ class CompanyUser extends Pivot return $this->hasMany(CompanyToken::class, 'user_id', 'user_id'); } - public function tokens() + public function tokens(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(CompanyToken::class, 'user_id', 'user_id'); } diff --git a/app/Models/Payment.php b/app/Models/Payment.php index cc1576912a..3fc2bd5cb4 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -180,46 +180,52 @@ class Payment extends BaseModel return self::class; } - public function client() + public function client(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Client::class)->withTrashed(); } - public function company_gateway() + public function company_gateway(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(CompanyGateway::class)->withTrashed(); } - public function company() + public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Company::class); } - public function contact() + public function contact(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(ClientContact::class); } - public function user() + public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(User::class)->withTrashed(); } - public function assigned_user() + public function assigned_user(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(User::class, 'assigned_user_id', 'id')->withTrashed(); } - public function documents() + public function documents(): \Illuminate\Database\Eloquent\Relations\MorphMany { return $this->morphMany(Document::class, 'documentable'); } + /** + * @return MorphedByMany + */ public function invoices() { return $this->morphedByMany(Invoice::class, 'paymentable')->withTrashed()->withPivot('amount', 'refunded')->withTimestamps(); } + /** + * @return MorphedByMany + */ public function credits() { return $this->morphedByMany(Credit::class, 'paymentable')->withTrashed()->withPivot('amount', 'refunded')->withTimestamps(); @@ -230,32 +236,32 @@ class Payment extends BaseModel return $this->morphMany(CompanyLedger::class, 'company_ledgerable'); } - public function type() + public function type(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(PaymentType::class); } - public function currency() + public function currency(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Currency::class); } - public function transaction() + public function transaction(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(BankTransaction::class); } - public function exchange_currency() + public function exchange_currency(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Currency::class, 'exchange_currency_id', 'id'); } - public function vendor() + public function vendor(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Vendor::class); } - public function project() + public function project(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Project::class); } @@ -271,7 +277,7 @@ class Payment extends BaseModel return $pt->name($this->type_id); } - public function gateway_type() + public function gateway_type(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(GatewayType::class); } @@ -457,12 +463,12 @@ class Payment extends BaseModel ]; } - public function translate_entity() + public function translate_entity(): string { return ctrans('texts.payment'); } - public function portalUrl($use_react_url) + public function portalUrl($use_react_url): string { return $use_react_url ? config('ninja.react_url')."/#/payments/{$this->hashed_id}/edit" : config('ninja.app_url'); } diff --git a/app/PaymentDrivers/CheckoutCom/CheckoutSetupWebhook.php b/app/PaymentDrivers/CheckoutCom/CheckoutSetupWebhook.php index f9dcc30dca..d35d07bd22 100644 --- a/app/PaymentDrivers/CheckoutCom/CheckoutSetupWebhook.php +++ b/app/PaymentDrivers/CheckoutCom/CheckoutSetupWebhook.php @@ -55,6 +55,7 @@ class CheckoutSetupWebhook implements ShouldQueue MultiDB::findAndSetDbByCompanyKey($this->company_key); + /** @var \App\Models\CompanyGateway $company_gateway */ $company_gateway = CompanyGateway::find($this->company_gateway_id); $this->checkout = $company_gateway->driver()->init(); diff --git a/app/PaymentDrivers/Stripe/ACH.php b/app/PaymentDrivers/Stripe/ACH.php index b68d4e120e..d223fc9aa9 100644 --- a/app/PaymentDrivers/Stripe/ACH.php +++ b/app/PaymentDrivers/Stripe/ACH.php @@ -95,7 +95,7 @@ class ACH { $stripe_event = $event['data']['object']; - $token = ClientGatewayToken::where('token', $stripe_event['id']) + $token = ClientGatewayToken::query()->where('token', $stripe_event['id']) ->where('gateway_customer_reference', $stripe_event['customer']) ->first(); diff --git a/app/Services/Subscription/SubscriptionService.php b/app/Services/Subscription/SubscriptionService.php index a8dbeb7da6..0e0ae3891b 100644 --- a/app/Services/Subscription/SubscriptionService.php +++ b/app/Services/Subscription/SubscriptionService.php @@ -1357,13 +1357,13 @@ class SubscriptionService case RecurringInvoice::FREQUENCY_MONTHLY: return now()->diffInDays(now()->addMonthNoOverflow()); case RecurringInvoice::FREQUENCY_TWO_MONTHS: - return now()->diffInDays(now()->addMonthNoOverflow(2)); + return now()->diffInDays(now()->addMonthsNoOverflow(2)); case RecurringInvoice::FREQUENCY_THREE_MONTHS: - return now()->diffInDays(now()->addMonthNoOverflow(3)); + return now()->diffInDays(now()->addMonthsNoOverflow(3)); case RecurringInvoice::FREQUENCY_FOUR_MONTHS: - return now()->diffInDays(now()->addMonthNoOverflow(4)); + return now()->diffInDays(now()->addMonthsNoOverflow(4)); case RecurringInvoice::FREQUENCY_SIX_MONTHS: - return now()->diffInDays(now()->addMonthNoOverflow(6)); + return now()->diffInDays(now()->addMonthsNoOverflow(6)); case RecurringInvoice::FREQUENCY_ANNUALLY: return now()->diffInDays(now()->addYear()); case RecurringInvoice::FREQUENCY_TWO_YEARS: @@ -1397,13 +1397,13 @@ class SubscriptionService case RecurringInvoice::FREQUENCY_MONTHLY: return $date->addMonthNoOverflow(); case RecurringInvoice::FREQUENCY_TWO_MONTHS: - return $date->addMonthNoOverflow(2); + return $date->addMonthsNoOverflow(2); case RecurringInvoice::FREQUENCY_THREE_MONTHS: - return $date->addMonthNoOverflow(3); + return $date->addMonthsNoOverflow(3); case RecurringInvoice::FREQUENCY_FOUR_MONTHS: - return $date->addMonthNoOverflow(4); + return $date->addMonthsNoOverflow(4); case RecurringInvoice::FREQUENCY_SIX_MONTHS: - return $date->addMonthNoOverflow(6); + return $date->addMonthsNoOverflow(6); case RecurringInvoice::FREQUENCY_ANNUALLY: return $date->addYear(); case RecurringInvoice::FREQUENCY_TWO_YEARS: diff --git a/app/Services/TaskScheduler/TaskSchedulerService.php b/app/Services/TaskScheduler/TaskSchedulerService.php deleted file mode 100644 index b5533ca8d2..0000000000 --- a/app/Services/TaskScheduler/TaskSchedulerService.php +++ /dev/null @@ -1,165 +0,0 @@ -action_name = $request->job; - $scheduler->paused = $request->get('paused', false); - $scheduler->start_from = $request->get('start_from') ? Carbon::parse((int) $request->get('start_from')) : Carbon::now(); - $scheduler->repeat_every = $request->get('repeat_every'); - $scheduler->scheduled_run = $request->get('start_from') ? Carbon::parse((int) $request->get('start_from')) : Carbon::now(); - $scheduler->company_id = auth()->user()->company()->id; - $scheduler = $this->setJobParameters($scheduler, $request); - $scheduler->save(); - } - - public function update(Scheduler $scheduler, UpdateScheduleRequest $request) - { - if (array_key_exists('job', $request->all())) { - $scheduler->action_name = $request->get('job'); - $scheduler = $this->setJobParameters($scheduler, $request); - } - $data = $request->validated(); - $update = $this->scheduler->update($data); - } - - private function runValidation($form_request, $data) - { - $_syn_request_class = new $form_request(); - $_syn_request_class->setContainer(app()); - $_syn_request_class->initialize($data); - $_syn_request_class->prepareForValidation(); - $_syn_request_class->setValidator(Validator::make($_syn_request_class->all(), $_syn_request_class->rules())); - - return $_syn_request_class->validated(); - } - - public function setJobParameters(Scheduler $scheduler, $request) - { - switch ($scheduler->action_name) { - case Scheduler::CREATE_CLIENT_REPORT: - $scheduler->action_name = Scheduler::CREATE_CLIENT_REPORT; - $scheduler->action_class = $this->getClassPath(ClientExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_CLIENT_CONTACT_REPORT: - $scheduler->action_name = Scheduler::CREATE_CLIENT_CONTACT_REPORT; - $scheduler->action_class = $this->getClassPath(ContactExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_CREDIT_REPORT: - - $scheduler->action_name = Scheduler::CREATE_CREDIT_REPORT; - $scheduler->action_class = $this->getClassPath(CreditExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_DOCUMENT_REPORT: - $scheduler->action_name = Scheduler::CREATE_DOCUMENT_REPORT; - $scheduler->action_class = $this->getClassPath(DocumentExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_EXPENSE_REPORT: - $scheduler->action_name = Scheduler::CREATE_EXPENSE_REPORT; - $scheduler->action_class = $this->getClassPath(ExpenseExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_INVOICE_ITEM_REPORT: - $scheduler->action_name = Scheduler::CREATE_INVOICE_ITEM_REPORT; - $scheduler->action_class = $this->getClassPath(InvoiceItemExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_INVOICE_REPORT: - $scheduler->action_name = Scheduler::CREATE_INVOICE_REPORT; - $scheduler->action_class = $this->getClassPath(InvoiceExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_PAYMENT_REPORT: - $scheduler->action_name = Scheduler::CREATE_PAYMENT_REPORT; - $scheduler->action_class = $this->getClassPath(PaymentExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_PRODUCT_REPORT: - $scheduler->action_name = Scheduler::CREATE_PRODUCT_REPORT; - $scheduler->action_class = $this->getClassPath(ProductExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_PROFIT_AND_LOSS_REPORT: - $scheduler->action_name = Scheduler::CREATE_PROFIT_AND_LOSS_REPORT; - $scheduler->action_class = $this->getClassPath(ProfitAndLoss::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_QUOTE_ITEM_REPORT: - $scheduler->action_name = Scheduler::CREATE_QUOTE_ITEM_REPORT; - $scheduler->action_class = $this->getClassPath(QuoteItemExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_QUOTE_REPORT: - $scheduler->action_name = Scheduler::CREATE_QUOTE_REPORT; - $scheduler->action_class = $this->getClassPath(QuoteExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_RECURRING_INVOICE_REPORT: - $scheduler->action_name = Scheduler::CREATE_RECURRING_INVOICE_REPORT; - $scheduler->action_class = $this->getClassPath(RecurringInvoiceExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - case Scheduler::CREATE_TASK_REPORT: - $scheduler->action_name = Scheduler::CREATE_TASK_REPORT; - $scheduler->action_class = $this->getClassPath(TaskExport::class); - $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); - break; - } - - return $scheduler; - } - - public function getClassPath($class): string - { - return $class = is_object($class) ? get_class($class) : $class; - } - - public function updateJob(Scheduler $scheduler, UpdateScheduledJobRequest $request) - { - $scheduler = $this->setJobParameters($scheduler, $request); - $scheduler->save(); - } -} diff --git a/app/Transformers/TaskStatusTransformer.php b/app/Transformers/TaskStatusTransformer.php index c2c2f3347f..f3f9465e29 100644 --- a/app/Transformers/TaskStatusTransformer.php +++ b/app/Transformers/TaskStatusTransformer.php @@ -24,7 +24,7 @@ class TaskStatusTransformer extends EntityTransformer 'id' => (string) $this->encodePrimaryKey($task_status->id), 'name' => (string) $task_status->name, 'color' => (string) $task_status->color, - 'sort_order' => (int) $task_status->sort_order, //deprecated + // 'sort_order' => (int) $task_status->sort_order, //deprecated 'is_deleted' => (bool) $task_status->is_deleted, 'created_at' => (int) $task_status->created_at, 'updated_at' => (int) $task_status->updated_at, From b566bf6a7fa2cd1b9fc80927c45b42a90165fa07 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 08:26:31 +1000 Subject: [PATCH 13/33] updates for static analysis --- app/Jobs/Cron/UpdateCalculatedFields.php | 2 +- app/Models/Project.php | 18 ++++++------------ app/Utils/TemplateEngine.php | 2 ++ 3 files changed, 9 insertions(+), 13 deletions(-) diff --git a/app/Jobs/Cron/UpdateCalculatedFields.php b/app/Jobs/Cron/UpdateCalculatedFields.php index e60b8483bb..98371260b0 100644 --- a/app/Jobs/Cron/UpdateCalculatedFields.php +++ b/app/Jobs/Cron/UpdateCalculatedFields.php @@ -61,7 +61,7 @@ class UpdateCalculatedFields MultiDB::setDB($db); - Project::with('tasks')->whereHas('tasks', function ($query){ + Project::query()->with('tasks')->whereHas('tasks', function ($query){ $query->where('updated_at', '>', now()->subHours(2)); }) ->cursor() diff --git a/app/Models/Project.php b/app/Models/Project.php index d25bd23630..c2d09f250a 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -83,28 +83,22 @@ class Project extends BaseModel protected $touches = []; - /** - * @return BelongsTo - */ - public function company() + public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Company::class); } - /** - * @return mixed - */ - public function client() + public function client(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Client::class)->withTrashed(); } - public function vendor() + public function vendor(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Vendor::class)->withTrashed(); } - public function project() + public function project(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(self::class)->withTrashed(); } @@ -114,12 +108,12 @@ class Project extends BaseModel return $this->morphMany(Document::class, 'documentable'); } - public function user() + public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(User::class)->withTrashed(); } - public function tasks() + public function tasks(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Task::class); } diff --git a/app/Utils/TemplateEngine.php b/app/Utils/TemplateEngine.php index a0a1610c6d..51fcb2dc1a 100644 --- a/app/Utils/TemplateEngine.php +++ b/app/Utils/TemplateEngine.php @@ -302,6 +302,8 @@ class TemplateEngine 'company_id' => $user->company()->id, ]); + + /** @var \App\Models\ClientContact $contact */ $contact = ClientContact::factory()->create([ 'user_id' => $user->id, 'company_id' => $user->company()->id, From 2d8fc80779373fcd867bf2d2cd2b9726c2206bbf Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 14:33:47 +1000 Subject: [PATCH 14/33] minor fixes --- app/Helpers/Mail/GmailTransport.php | 4 ++++ app/Http/Livewire/BillingPortalPurchase.php | 2 +- app/Http/Livewire/BillingPortalPurchasev2.php | 2 +- app/Http/Livewire/WepaySignup.php | 5 +++++ phpstan.neon | 2 ++ 5 files changed, 13 insertions(+), 2 deletions(-) diff --git a/app/Helpers/Mail/GmailTransport.php b/app/Helpers/Mail/GmailTransport.php index 4c74e0961d..0a7f582445 100644 --- a/app/Helpers/Mail/GmailTransport.php +++ b/app/Helpers/Mail/GmailTransport.php @@ -33,6 +33,8 @@ class GmailTransport extends AbstractTransport nlog("In Do Send"); $message = MessageConverter::toEmail($message->getOriginalMessage()); + + /** @phpstan-ignore-next-line */ $token = $message->getHeaders()->get('gmailtoken')->getValue(); $message->getHeaders()->remove('gmailtoken'); @@ -52,6 +54,8 @@ class GmailTransport extends AbstractTransport if ($bccs) { $bcc_list = 'Bcc: '; + + /** @phpstan-ignore-next-line */ foreach ($bccs->getAddresses() as $address) { $bcc_list .= $address->getAddress() .','; } diff --git a/app/Http/Livewire/BillingPortalPurchase.php b/app/Http/Livewire/BillingPortalPurchase.php index d578f261b7..821d8f56e6 100644 --- a/app/Http/Livewire/BillingPortalPurchase.php +++ b/app/Http/Livewire/BillingPortalPurchase.php @@ -186,7 +186,7 @@ class BillingPortalPurchase extends Component { MultiDB::setDb($this->db); - $this->subscription = Subscription::with('company')->find($this->subscription); + $this->subscription = Subscription::query()->with('company')->find($this->subscription); $this->company = $this->subscription->company; diff --git a/app/Http/Livewire/BillingPortalPurchasev2.php b/app/Http/Livewire/BillingPortalPurchasev2.php index c7e83488b1..b4fbbdd255 100644 --- a/app/Http/Livewire/BillingPortalPurchasev2.php +++ b/app/Http/Livewire/BillingPortalPurchasev2.php @@ -165,7 +165,7 @@ class BillingPortalPurchasev2 extends Component { MultiDB::setDb($this->db); - $this->subscription = Subscription::with('company')->find($this->subscription); + $this->subscription = Subscription::query()->with('company')->find($this->subscription); $this->company = $this->subscription->company; diff --git a/app/Http/Livewire/WepaySignup.php b/app/Http/Livewire/WepaySignup.php index 5524cc1731..b8fb9b7ac0 100644 --- a/app/Http/Livewire/WepaySignup.php +++ b/app/Http/Livewire/WepaySignup.php @@ -165,6 +165,7 @@ class WepaySignup extends Component } $wepay_account = $wepay->request('account/create/', $account_details); + $confirmation_required = false; try { $wepay->request('user/send_confirmation/', []); @@ -173,6 +174,8 @@ class WepaySignup extends Component if ($ex->getMessage() == 'This access_token is already approved.') { $confirmation_required = false; } else { + + /** @phpstan-ignore-next-line */ request()->session()->flash('message', $ex->getMessage()); } @@ -195,6 +198,8 @@ class WepaySignup extends Component $cg->save(); if ($confirmation_required) { + + /** @phpstan-ignore-next-line */ request()->session()->flash('message', trans('texts.created_wepay_confirmation_required')); } else { $update_uri = $wepay->request('/account/get_update_uri', [ diff --git a/phpstan.neon b/phpstan.neon index 8e7747dc3a..476dbfada6 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -10,6 +10,7 @@ parameters: - 'app/Console/Commands/*' - 'app/DataMapper/Analytics/*' - 'app/PaymentDrivers/Authorize/*' + - 'app/Utils/Traits/*' universalObjectCratesClasses: - App\DataMapper\Tax\RuleInterface - App\DataMapper\FeesAndLimits @@ -18,4 +19,5 @@ parameters: - '#Call to an undefined method [a-zA-Z0-9\\_]+::company\(\)#' - '#Call to an undefined method [a-zA-Z0-9\\_]+::entityFilter\(\)#' - '#Call to an undefined method [a-zA-Z0-9\\_]+::exclude\(\)#' + - '#Array has 2 duplicate keys with value#' - '#Undefined method#' \ No newline at end of file From fb4939c13aa331d45cb829eceef933a4a0ab74a0 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 14:50:08 +1000 Subject: [PATCH 15/33] Updated static analysis --- app/Export/CSV/ProductSalesExport.php | 1 + app/Http/Controllers/BaseController.php | 11 +++--- app/Http/Controllers/EmailController.php | 1 - app/Http/Livewire/WepaySignup.php | 2 +- app/Http/Middleware/ContactRegister.php | 2 +- app/Http/Middleware/PasswordProtection.php | 5 ++- app/Http/Middleware/VendorContactKeyLogin.php | 12 +++--- app/Http/Middleware/VerifyHash.php | 2 +- .../ClientPortal/StoreDocumentRequest.php | 3 +- .../Requests/Company/StoreCompanyRequest.php | 6 ++- .../Payments/PaymentWebhookRequest.php | 1 - .../UpdateRecurringInvoiceRequest.php | 2 +- app/Models/Client.php | 1 + app/Models/Invoice.php | 4 +- app/Models/PaymentHash.php | 14 ++++++- app/Models/PurchaseOrder.php | 38 +++++++++++++++++++ 16 files changed, 77 insertions(+), 28 deletions(-) diff --git a/app/Export/CSV/ProductSalesExport.php b/app/Export/CSV/ProductSalesExport.php index 2c9d170852..f47acfa4dc 100644 --- a/app/Export/CSV/ProductSalesExport.php +++ b/app/Export/CSV/ProductSalesExport.php @@ -187,6 +187,7 @@ class ProductSalesExport extends BaseExport $product = $this->getProduct($entity['product_key']); $entity['cost'] = $product->cost ?? 0; + /** @var float $unit_cost */ $unit_cost = $entity['cost'] == 0 ? 1 : $entity['cost']; $entity['client'] = $invoice->client->present()->name(); diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index d320a8fad2..51222f5ab4 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -530,10 +530,9 @@ class BaseController extends Controller $paginator = $query->paginate($limit); - /** @phpstan-ignore-next-line */ - $query = $paginator->getCollection(); /** @phpstan-ignore-line */ - /** @phpstan-ignore-line */ - + /** @phpstan-ignore-next-line **/ + $query = $paginator->getCollection(); + $resource = new Collection($query, $transformer, $this->entity_type); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); @@ -636,7 +635,7 @@ class BaseController extends Controller $paginator = $query->paginate($limit); - /** @phpstan-ignore-next-line */ + /** @phpstan-ignore-next-line **/ $query = $paginator->getCollection(); $resource = new Collection($query, $transformer, $this->entity_type); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); @@ -885,7 +884,7 @@ class BaseController extends Controller $paginator = $query->paginate($limit); - /** @phpstan-ignore-next-line */ + /** @phpstan-ignore-next-line **/ $query = $paginator->getCollection(); $resource = new Collection($query, $transformer, $this->entity_type); diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index 055cbfcffe..cc60c74b1f 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -125,7 +125,6 @@ class EmailController extends BaseController $this->entity_transformer = PurchaseOrderTransformer::class; } - // @phpstan-ignore-next-line return $this->itemResponse($entity_obj->fresh()); } diff --git a/app/Http/Livewire/WepaySignup.php b/app/Http/Livewire/WepaySignup.php index b8fb9b7ac0..b61af24d29 100644 --- a/app/Http/Livewire/WepaySignup.php +++ b/app/Http/Livewire/WepaySignup.php @@ -199,7 +199,7 @@ class WepaySignup extends Component if ($confirmation_required) { - /** @phpstan-ignore-next-line */ + /** @phpstan-ignore-next-line **/ request()->session()->flash('message', trans('texts.created_wepay_confirmation_required')); } else { $update_uri = $wepay->request('/account/get_update_uri', [ diff --git a/app/Http/Middleware/ContactRegister.php b/app/Http/Middleware/ContactRegister.php index 97237cda8d..3263f878ee 100644 --- a/app/Http/Middleware/ContactRegister.php +++ b/app/Http/Middleware/ContactRegister.php @@ -50,7 +50,7 @@ class ContactRegister 'portal_mode' => 'domain', ]; - if ($company = Company::where($query)->first()) { + if ($company = Company::query()->where($query)->first()) { if (! $company->client_can_register) { abort(400, 'Registration disabled'); } diff --git a/app/Http/Middleware/PasswordProtection.php b/app/Http/Middleware/PasswordProtection.php index 6789ede23c..4450ec3210 100644 --- a/app/Http/Middleware/PasswordProtection.php +++ b/app/Http/Middleware/PasswordProtection.php @@ -37,8 +37,9 @@ class PasswordProtection 'errors' => new stdClass, ]; - /** @var \App\Models\User auth()->user() */ - $timeout = auth()->user()->company()->default_password_timeout; + /** @var \App\Models\User auth()->user() */ + $user = auth()->user(); + $timeout = $user->company()->default_password_timeout; if ($timeout == 0) { $timeout = 30*60*1000*1000; diff --git a/app/Http/Middleware/VendorContactKeyLogin.php b/app/Http/Middleware/VendorContactKeyLogin.php index ae7e93ca11..352d96560c 100644 --- a/app/Http/Middleware/VendorContactKeyLogin.php +++ b/app/Http/Middleware/VendorContactKeyLogin.php @@ -49,7 +49,7 @@ class VendorContactKeyLogin $contact_email = $payload['email']; - if ($vendor_contact = VendorContact::where('email', $contact_email)->where('company_id', $payload['company_id'])->first()) { + if ($vendor_contact = VendorContact::query()->where('email', $contact_email)->where('company_id', $payload['company_id'])->first()) { if (empty($vendor_contact->email)) { $vendor_contact->email = Str::random(15).'@example.com'; } @@ -65,7 +65,7 @@ class VendorContactKeyLogin } } elseif ($request->segment(3) && config('ninja.db.multi_db_enabled')) { if (MultiDB::findAndSetDbByVendorContactKey($request->segment(3))) { - if ($vendor_contact = VendorContact::where('contact_key', $request->segment(3))->first()) { + if ($vendor_contact = VendorContact::query()->where('contact_key', $request->segment(3))->first()) { if (empty($vendor_contact->email)) { $vendor_contact->email = Str::random(6).'@example.com'; } @@ -81,7 +81,7 @@ class VendorContactKeyLogin } } } elseif ($request->segment(2) && $request->segment(2) == 'key_login' && $request->segment(3)) { - if ($vendor_contact = VendorContact::where('contact_key', $request->segment(3))->first()) { + if ($vendor_contact = VendorContact::query()->where('contact_key', $request->segment(3))->first()) { if (empty($vendor_contact->email)) { $vendor_contact->email = Str::random(6).'@example.com'; $vendor_contact->save(); @@ -97,7 +97,7 @@ class VendorContactKeyLogin } } elseif ($request->has('vendor_hash') && config('ninja.db.multi_db_enabled')) { if (MultiDB::findAndSetDbByClientHash($request->input('vendor_hash'))) { - if ($client = Vendor::where('vendor_hash', $request->input('vendor_hash'))->first()) { + if ($client = Vendor::query()->where('vendor_hash', $request->input('vendor_hash'))->first()) { $primary_contact = $client->primary_contact()->first(); if (empty($primary_contact->email)) { @@ -111,7 +111,7 @@ class VendorContactKeyLogin } } } elseif ($request->has('vendor_hash')) { - if ($client = Vendor::where('vendor_hash', $request->input('vendor_hash'))->first()) { + if ($client = Vendor::query()->where('vendor_hash', $request->input('vendor_hash'))->first()) { $primary_contact = $client->primary_contact()->first(); if (empty($primary_contact->email)) { @@ -124,7 +124,7 @@ class VendorContactKeyLogin return redirect($this->setRedirectPath()); } } elseif ($request->segment(3)) { - if ($vendor_contact = VendorContact::where('contact_key', $request->segment(3))->first()) { + if ($vendor_contact = VendorContact::query()->where('contact_key', $request->segment(3))->first()) { if (empty($vendor_contact->email)) { $vendor_contact->email = Str::random(6).'@example.com'; $vendor_contact->save(); diff --git a/app/Http/Middleware/VerifyHash.php b/app/Http/Middleware/VerifyHash.php index f06e5bca4c..4260f0dbf2 100644 --- a/app/Http/Middleware/VerifyHash.php +++ b/app/Http/Middleware/VerifyHash.php @@ -18,7 +18,7 @@ class VerifyHash public function handle($request, Closure $next) { if ($request->has('payment_hash')) { - $ph = PaymentHash::with('fee_invoice')->where('hash', $request->payment_hash)->first(); + $ph = PaymentHash::query()->with('fee_invoice')->where('hash', $request->payment_hash)->first(); if ($ph) { auth()->guard('contact')->loginUsingId($ph->fee_invoice->invitations->first()->contact->id, true); diff --git a/app/Http/Requests/ClientPortal/StoreDocumentRequest.php b/app/Http/Requests/ClientPortal/StoreDocumentRequest.php index a0d1b66af6..3e9faa1f32 100644 --- a/app/Http/Requests/ClientPortal/StoreDocumentRequest.php +++ b/app/Http/Requests/ClientPortal/StoreDocumentRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\ClientPortal; use App\Http\Requests\Request; -use Zend\Diactoros\Response\JsonResponse; class StoreDocumentRequest extends Request { @@ -35,6 +34,6 @@ class StoreDocumentRequest extends Request public function response(array $errors) { - return new JsonResponse(['error' => $errors], 400); + return response()->json(['error' => $errors], 400); } } diff --git a/app/Http/Requests/Company/StoreCompanyRequest.php b/app/Http/Requests/Company/StoreCompanyRequest.php index b9219f000d..70e116d60e 100644 --- a/app/Http/Requests/Company/StoreCompanyRequest.php +++ b/app/Http/Requests/Company/StoreCompanyRequest.php @@ -30,7 +30,9 @@ class StoreCompanyRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', Company::class); + /** @var \App\Models\User auth()->user */ + $user = auth()->user(); + return $user->can('create', Company::class); } public function rules() @@ -47,7 +49,7 @@ class StoreCompanyRequest extends Request $rules['portal_domain'] = 'sometimes|url'; } else { if (Ninja::isHosted()) { - $rules['subdomain'] = ['nullable', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9]$/', new ValidSubdomain($this->all())]; + $rules['subdomain'] = ['nullable', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9.-]+[a-zA-Z0-9]$/', new ValidSubdomain()]; } else { $rules['subdomain'] = 'nullable|alpha_num'; } diff --git a/app/Http/Requests/Payments/PaymentWebhookRequest.php b/app/Http/Requests/Payments/PaymentWebhookRequest.php index f2e00d40de..5255ef6f2a 100644 --- a/app/Http/Requests/Payments/PaymentWebhookRequest.php +++ b/app/Http/Requests/Payments/PaymentWebhookRequest.php @@ -52,7 +52,6 @@ class PaymentWebhookRequest extends Request /** * Resolve payment hash. * - * @param string $hash * @return null|\App\Models\PaymentHash */ public function getPaymentHash() diff --git a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php index 8b9795a78c..bbfa22bc0c 100644 --- a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php @@ -138,7 +138,7 @@ class UpdateRecurringInvoiceRequest extends Request * 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 + * @param string $auto_bill off/always/optin/optout * * @return bool */ diff --git a/app/Models/Client.php b/app/Models/Client.php index f14e741e1e..c4aa239c1c 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -106,6 +106,7 @@ use Illuminate\Contracts\Translation\HasLocalePreference; * @method static \Database\Factories\ClientFactory factory($count = null, $state = []) * @method static \Illuminate\Database\Eloquent\Builder|Client filter(\App\Filters\QueryFilters $filters) * @method static \Illuminate\Database\Eloquent\Builder|Client without() + * @method static \Illuminate\Database\Eloquent\Builder|Client find() * @method static \Illuminate\Database\Eloquent\Builder|Client select() * @property string $payment_balance * @property mixed $tax_data diff --git a/app/Models/Invoice.php b/app/Models/Invoice.php index f0b0f37ea2..f9903591b1 100644 --- a/app/Models/Invoice.php +++ b/app/Models/Invoice.php @@ -709,9 +709,9 @@ class Invoice extends BaseModel return ctrans('texts.invoice'); } - public function taxTypeString($id) + public function taxTypeString($id): string { - $tax_type = false; + $tax_type = ''; match(intval($id)){ Product::PRODUCT_TYPE_PHYSICAL => $tax_type = ctrans('texts.physical_goods'), diff --git a/app/Models/PaymentHash.php b/app/Models/PaymentHash.php index 019ac21ac3..d0c8722fdf 100644 --- a/app/Models/PaymentHash.php +++ b/app/Models/PaymentHash.php @@ -38,27 +38,37 @@ class PaymentHash extends Model 'data' => 'object', ]; + + /** + * @return array + */ public function invoices() { return $this->data->invoices; } + /** + * @return float|null + */ public function amount_with_fee() { return $this->data->amount_with_fee; } + /** + * @return float + */ public function credits_total() { return isset($this->data->credits) ? $this->data->credits : 0; } - public function payment() + public function payment(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Payment::class)->withTrashed(); } - public function fee_invoice() + public function fee_invoice(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Invoice::class, 'fee_invoice_id', 'id')->withTrashed(); } diff --git a/app/Models/PurchaseOrder.php b/app/Models/PurchaseOrder.php index 917a1969e8..a3a97f65b0 100644 --- a/app/Models/PurchaseOrder.php +++ b/app/Models/PurchaseOrder.php @@ -370,4 +370,42 @@ class PurchaseOrder extends BaseModel { return ctrans('texts.purchase_order'); } + + public function typeIdString($id): string + { + $type = ''; + match($id) { + '1' => $type = ctrans('texts.product'), + '2' => $type = ctrans('texts.service'), + '3' => $type = ctrans('texts.gateway_fees'), + '4' => $type = ctrans('texts.gateway_fees'), + '5' => $type = ctrans('texts.late_fees'), + '6' => $type = ctrans('texts.expense'), + default => $type = ctrans('texts.product'), + }; + + return $type; + + } + + public function taxTypeString($id): string + { + $tax_type = ''; + + match(intval($id)){ + Product::PRODUCT_TYPE_PHYSICAL => $tax_type = ctrans('texts.physical_goods'), + Product::PRODUCT_TYPE_SERVICE => $tax_type = ctrans('texts.services'), + Product::PRODUCT_TYPE_DIGITAL => $tax_type = ctrans('texts.digital_products'), + Product::PRODUCT_TYPE_SHIPPING => $tax_type = ctrans('texts.shipping'), + Product::PRODUCT_TYPE_EXEMPT => $tax_type = ctrans('texts.tax_exempt'), + Product::PRODUCT_TYPE_REDUCED_TAX => $tax_type = ctrans('texts.reduced_tax'), + Product::PRODUCT_TYPE_OVERRIDE_TAX => $tax_type = ctrans('texts.override_tax'), + Product::PRODUCT_TYPE_ZERO_RATED => $tax_type = ctrans('texts.zero_rated'), + Product::PRODUCT_TYPE_REVERSE_TAX => $tax_type = ctrans('texts.reverse_tax'), + default => $tax_type = ctrans('texts.physical_goods'), + }; + + return $tax_type; + } + } From 01cc61b586c4c34cdd002f8d57a03ed237b0fc3b Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 15:07:52 +1000 Subject: [PATCH 16/33] Updated static analysis --- .../Invoice/InvoiceItemSumInclusive.php | 4 +- app/Helpers/Mail/GmailTransport.php | 4 +- .../ClientPortal/NinjaPlanController.php | 4 +- app/Http/Livewire/BillingPortalPurchasev2.php | 2 +- app/Http/Middleware/ContactKeyLogin.php | 4 +- app/Http/Middleware/ContactRegister.php | 3 +- .../Requests/ClientPortal/RegisterRequest.php | 5 +- .../Payments/PaymentWebhookRequest.php | 1 - .../StoreRecurringInvoiceRequest.php | 7 ++- .../UpdateRecurringInvoiceRequest.php | 10 +++- .../StoreRecurringQuoteRequest.php | 13 ++++- .../Documents/ShowDocumentRequest.php | 3 ++ .../Ninja/CanStoreClientsRule.php | 2 +- .../ValidationRules/ValidUserForCompany.php | 5 +- app/Import/Providers/BaseImport.php | 2 +- app/Import/Providers/Wave.php | 4 +- app/Import/Transformer/BaseTransformer.php | 52 +++++++++---------- .../Transformer/Zoho/InvoiceTransformer.php | 4 +- app/Models/Company.php | 1 + 19 files changed, 81 insertions(+), 49 deletions(-) diff --git a/app/Helpers/Invoice/InvoiceItemSumInclusive.php b/app/Helpers/Invoice/InvoiceItemSumInclusive.php index 9e792c0d71..238f486365 100644 --- a/app/Helpers/Invoice/InvoiceItemSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceItemSumInclusive.php @@ -226,8 +226,10 @@ class InvoiceItemSumInclusive $amount = $this->item->line_total - ($this->item->line_total * ($this->invoice->discount / 100)); + /** @var float $item_tax_rate1_total */ $item_tax_rate1_total = $this->calcInclusiveLineTax($this->item->tax_rate1, $amount); - + + /** @var float $item_tax */ $item_tax += $this->formatValue($item_tax_rate1_total, $this->currency->precision); if (strlen($this->item->tax_name1) > 1) { diff --git a/app/Helpers/Mail/GmailTransport.php b/app/Helpers/Mail/GmailTransport.php index 0a7f582445..1538edcfde 100644 --- a/app/Helpers/Mail/GmailTransport.php +++ b/app/Helpers/Mail/GmailTransport.php @@ -34,7 +34,7 @@ class GmailTransport extends AbstractTransport $message = MessageConverter::toEmail($message->getOriginalMessage()); - /** @phpstan-ignore-next-line */ + /** @phpstan-ignore-next-line **/ $token = $message->getHeaders()->get('gmailtoken')->getValue(); $message->getHeaders()->remove('gmailtoken'); @@ -55,7 +55,7 @@ class GmailTransport extends AbstractTransport $bcc_list = 'Bcc: '; - /** @phpstan-ignore-next-line */ + /** @phpstan-ignore-next-line **/ foreach ($bccs->getAddresses() as $address) { $bcc_list .= $address->getAddress() .','; } diff --git a/app/Http/Controllers/ClientPortal/NinjaPlanController.php b/app/Http/Controllers/ClientPortal/NinjaPlanController.php index f0346d2371..b57b2f0524 100644 --- a/app/Http/Controllers/ClientPortal/NinjaPlanController.php +++ b/app/Http/Controllers/ClientPortal/NinjaPlanController.php @@ -157,6 +157,8 @@ class NinjaPlanController extends Controller //create recurring invoice $subscription_repo = new SubscriptionRepository(); + + /** @var \App\Models\Subscription $subscription **/ $subscription = Subscription::find(6); $recurring_invoice = RecurringInvoiceFactory::create($subscription->company_id, $subscription->user_id); @@ -215,7 +217,7 @@ class NinjaPlanController extends Controller $data['late_invoice'] = false; if (MultiDB::findAndSetDbByAccountKey(Auth::guard('contact')->user()->client->custom_value2)) { - $account = Account::where('key', Auth::guard('contact')->user()->client->custom_value2)->first(); + $account = Account::query()->where('key', Auth::guard('contact')->user()->client->custom_value2)->first(); if ($account) { //offer the option to have a free trial diff --git a/app/Http/Livewire/BillingPortalPurchasev2.php b/app/Http/Livewire/BillingPortalPurchasev2.php index b4fbbdd255..1a6c1a8ba1 100644 --- a/app/Http/Livewire/BillingPortalPurchasev2.php +++ b/app/Http/Livewire/BillingPortalPurchasev2.php @@ -53,7 +53,7 @@ class BillingPortalPurchasev2 extends Component /** * Instance of subscription. * - * @var Subscription + * @var \App\Models\Subscription */ public $subscription; diff --git a/app/Http/Middleware/ContactKeyLogin.php b/app/Http/Middleware/ContactKeyLogin.php index e49306665e..7867e572c7 100644 --- a/app/Http/Middleware/ContactKeyLogin.php +++ b/app/Http/Middleware/ContactKeyLogin.php @@ -121,7 +121,7 @@ class ContactKeyLogin } } } elseif ($request->has('client_hash')) { - if ($client = Client::where('client_hash', $request->input('client_hash'))->first()) { + if ($client = Client::query()->where('client_hash', $request->input('client_hash'))->first()) { $primary_contact = $client->primary_contact()->first(); if (empty($primary_contact->email)) { @@ -134,7 +134,7 @@ class ContactKeyLogin return redirect($this->setRedirectPath()); } } elseif ($request->segment(3)) { - if ($client_contact = ClientContact::with('company')->where('contact_key', $request->segment(3))->first()) { + if ($client_contact = ClientContact::query()->with('company')->where('contact_key', $request->segment(3))->first()) { if ($client_contact->company->settings->enable_client_portal_password) { return redirect()->route('client.login', ['company_key' => $client_contact->company->company_key]); } diff --git a/app/Http/Middleware/ContactRegister.php b/app/Http/Middleware/ContactRegister.php index 3263f878ee..a0356d6bbf 100644 --- a/app/Http/Middleware/ContactRegister.php +++ b/app/Http/Middleware/ContactRegister.php @@ -65,7 +65,7 @@ class ContactRegister // For self-hosted platforms with multiple companies, resolving is done using company key // if it doesn't resolve using a domain. - if ($request->company_key && Ninja::isSelfHost() && $company = Company::where('company_key', $request->company_key)->first()) { + if ($request->company_key && Ninja::isSelfHost() && $company = Company::query()->where('company_key', $request->company_key)->first()) { if (! (bool) $company->client_can_register) { abort(400, 'Registration disabled'); } @@ -79,6 +79,7 @@ class ContactRegister // As a fallback for self-hosted, it will use default company in the system // if key isn't provided in the url. if (! $request->route()->parameter('company_key') && Ninja::isSelfHost()) { + /** @var \App\Models\Company $company */ $company = Account::first()->default_company; if (! $company->client_can_register) { diff --git a/app/Http/Requests/ClientPortal/RegisterRequest.php b/app/Http/Requests/ClientPortal/RegisterRequest.php index b1e4763075..b395d54f98 100644 --- a/app/Http/Requests/ClientPortal/RegisterRequest.php +++ b/app/Http/Requests/ClientPortal/RegisterRequest.php @@ -66,14 +66,15 @@ class RegisterRequest extends FormRequest { //this should be all we need, the rest SHOULD be redundant because of our Middleware if ($this->key) { - return Company::where('company_key', $this->key)->first(); + return Company::query()->where('company_key', $this->key)->first(); } if ($this->company_key) { - return Company::where('company_key', $this->company_key)->firstOrFail(); + return Company::query()->where('company_key', $this->company_key)->firstOrFail(); } if (! $this->route()->parameter('company_key') && Ninja::isSelfHost()) { + /** @var \App\Models\Company $company */ $company = Account::first()->default_company; if (! $company->client_can_register) { diff --git a/app/Http/Requests/Payments/PaymentWebhookRequest.php b/app/Http/Requests/Payments/PaymentWebhookRequest.php index 5255ef6f2a..8714f7ba80 100644 --- a/app/Http/Requests/Payments/PaymentWebhookRequest.php +++ b/app/Http/Requests/Payments/PaymentWebhookRequest.php @@ -39,7 +39,6 @@ class PaymentWebhookRequest extends Request /** * Resolve company gateway. * - * @param mixed $id * @return null|\App\Models\CompanyGateway */ public function getCompanyGateway() diff --git a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php index 307ab9cffe..aa8c8f406d 100644 --- a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php @@ -31,7 +31,11 @@ class StoreRecurringInvoiceRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', RecurringInvoice::class); + + /** @var \App\Models\User auth()->user() */ + $user = auth()->user(); + + return $user->can('create', RecurringInvoice::class); } public function rules() @@ -137,6 +141,7 @@ class StoreRecurringInvoiceRequest extends Request if (isset($input['auto_bill'])) { $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); } else { + /** @var \App\Models\Client $client */ if (array_key_exists('client_id', $input) && $client = Client::find($input['client_id'])) { $input['auto_bill'] = $client->getSetting('auto_bill'); $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); diff --git a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php index bbfa22bc0c..bbff843b22 100644 --- a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php @@ -31,11 +31,17 @@ class UpdateRecurringInvoiceRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('edit', $this->recurring_invoice); + /** @var \App\Models\User auth()->user() */ + $user = auth()->user(); + + return $user->can('edit', $this->recurring_invoice); } public function rules() { + /** @var \App\Models\User auth()->user() */ + $user = auth()->user(); + $rules = []; if ($this->file('documents') && is_array($this->file('documents'))) { @@ -51,7 +57,7 @@ class UpdateRecurringInvoiceRequest extends Request } if ($this->number) { - $rules['number'] = Rule::unique('recurring_invoices')->where('company_id', auth()->user()->company()->id)->ignore($this->recurring_invoice->id); + $rules['number'] = Rule::unique('recurring_invoices')->where('company_id', $user->company()->id)->ignore($this->recurring_invoice->id); } $rules['project_id'] = ['bail', 'sometimes', new ValidProjectForClient($this->all())]; diff --git a/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php index 396341b9fc..75eec29655 100644 --- a/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php @@ -30,11 +30,19 @@ class StoreRecurringQuoteRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', RecurringQuote::class); + + /** @var \App\Models\User auth()->user() */ + $user = auth()->user(); + + return $user->can('create', RecurringQuote::class); } public function rules() { + + /** @var \App\Models\User auth()->user() */ + $user = auth()->user(); + $rules = []; if ($this->file('documents') && is_array($this->file('documents'))) { @@ -49,7 +57,7 @@ class StoreRecurringQuoteRequest extends Request $rules['file'] = $this->file_validation; } - $rules['client_id'] = 'required|exists:clients,id,company_id,'.auth()->user()->company()->id; + $rules['client_id'] = 'required|exists:clients,id,company_id,'.$user->company()->id; $rules['invitations.*.client_contact_id'] = 'distinct'; @@ -71,6 +79,7 @@ class StoreRecurringQuoteRequest extends Request $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); } else { if ($client = Client::find($input['client_id'])) { + /** @var \App\Models\Client $client */ $input['auto_bill'] = $client->getSetting('auto_bill'); $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); } diff --git a/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php b/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php index 83e3357e1d..691cfe1d05 100644 --- a/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php +++ b/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php @@ -26,6 +26,9 @@ class ShowDocumentRequest extends FormRequest */ public function authorize() { + + /** @var \App\Models\VendorContact auth()->guard('vendor')->user() */ + return auth()->guard('vendor')->user()->client_id == $this->document->documentable_id || $this->document->company_id == auth()->guard('vendor')->user()->company_id; } diff --git a/app/Http/ValidationRules/Ninja/CanStoreClientsRule.php b/app/Http/ValidationRules/Ninja/CanStoreClientsRule.php index 6c1f49afb6..8bd700fefe 100644 --- a/app/Http/ValidationRules/Ninja/CanStoreClientsRule.php +++ b/app/Http/ValidationRules/Ninja/CanStoreClientsRule.php @@ -21,7 +21,7 @@ class CanStoreClientsRule implements Rule { public $company_id; - public $company; + public \App\Models\Company $company; public function __construct($company_id) { diff --git a/app/Http/ValidationRules/ValidUserForCompany.php b/app/Http/ValidationRules/ValidUserForCompany.php index 3a724c78ec..8a60cd2751 100644 --- a/app/Http/ValidationRules/ValidUserForCompany.php +++ b/app/Http/ValidationRules/ValidUserForCompany.php @@ -26,7 +26,10 @@ class ValidUserForCompany implements Rule */ public function passes($attribute, $value) { - return MultiDB::checkUserAndCompanyCoExist($value, auth()->user()->company()->company_key, auth()->user()->company()->id); + /** @var \App\Models\User auth()->user() */ + $user = auth()->user(); + + return MultiDB::checkUserAndCompanyCoExist($value, $user->company()->company_key); } /** diff --git a/app/Import/Providers/BaseImport.php b/app/Import/Providers/BaseImport.php index 988c85b520..04ace061da 100644 --- a/app/Import/Providers/BaseImport.php +++ b/app/Import/Providers/BaseImport.php @@ -95,7 +95,7 @@ class BaseImport ini_set('auto_detect_line_endings', '1'); } - /** @var strin $base64_encoded_csv */ + /** @var string $base64_encoded_csv */ $base64_encoded_csv = Cache::pull($this->hash.'-'.$entity_type); if (empty($base64_encoded_csv)) { diff --git a/app/Import/Providers/Wave.php b/app/Import/Providers/Wave.php index 9543c704a2..4b4c10adc1 100644 --- a/app/Import/Providers/Wave.php +++ b/app/Import/Providers/Wave.php @@ -189,7 +189,7 @@ class Wave extends BaseImport implements ImportInterface $this->transformer = new ExpenseTransformer($this->company); - $expense_count = $this->ingestExpenses($data, $entity_type); + $expense_count = $this->ingestExpenses($data); $this->entity_count['expenses'] = $expense_count; } @@ -200,7 +200,7 @@ class Wave extends BaseImport implements ImportInterface private function groupExpenses($csvData) { - $grouped_expense = []; + $grouped = []; $key = 'Transaction ID'; foreach ($csvData as $expense) { diff --git a/app/Import/Transformer/BaseTransformer.php b/app/Import/Transformer/BaseTransformer.php index ddc190b029..a979a85082 100644 --- a/app/Import/Transformer/BaseTransformer.php +++ b/app/Import/Transformer/BaseTransformer.php @@ -176,7 +176,7 @@ class BaseTransformer public function getClient($client_name, $client_email) { if (! empty($client_name)) { - $client_id_search = Client::where('company_id', $this->company->id) + $client_id_search = Client::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->where('id_number', $client_name); @@ -184,7 +184,7 @@ class BaseTransformer return $client_id_search->first()->id; } - $client_name_search = Client::where('company_id', $this->company->id) + $client_name_search = Client::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $client_name)), @@ -195,7 +195,7 @@ class BaseTransformer } } if (! empty($client_email)) { - $contacts = ClientContact::whereHas('client', function ($query) { + $contacts = ClientContact::query()->whereHas('client', function ($query) { $query->where('is_deleted', false); }) ->where('company_id', $this->company->id) @@ -238,7 +238,7 @@ class BaseTransformer */ public function hasClient($name) { - return Client::where('company_id', $this->company->id) + return Client::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), @@ -248,7 +248,7 @@ class BaseTransformer public function hasClientIdNumber($id_number) { - return Client::where('company_id', $this->company->id) + return Client::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->where('id_number', trim($id_number)) ->exists(); @@ -262,7 +262,7 @@ class BaseTransformer */ public function hasVendor($name) { - return Vendor::where('company_id', $this->company->id) + return Vendor::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), @@ -277,7 +277,7 @@ class BaseTransformer */ public function hasProject($name) { - return Project::where('company_id', $this->company->id) + return Project::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), @@ -292,7 +292,7 @@ class BaseTransformer */ public function hasProduct($key) { - return Product::where('company_id', $this->company->id) + return Product::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`product_key`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $key)), @@ -341,7 +341,7 @@ class BaseTransformer */ public function getClientId($name) { - $client = Client::where('company_id', $this->company->id) + $client = Client::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), @@ -358,7 +358,7 @@ class BaseTransformer */ public function getProduct($key) { - $product = Product::where('company_id', $this->company->id) + $product = Product::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`product_key`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $key)), @@ -375,7 +375,7 @@ class BaseTransformer */ public function getContact($email): ?ClientContact { - $contact = ClientContact::where('company_id', $this->company->id) + $contact = ClientContact::query()->where('company_id', $this->company->id) ->whereRaw("LOWER(REPLACE(`email`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $email)), ]) @@ -400,7 +400,7 @@ class BaseTransformer return $this->getCountryIdBy2($name); } - $country = Country::whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ + $country = Country::query()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), ])->first(); @@ -414,8 +414,8 @@ class BaseTransformer */ public function getCountryIdBy2($name) { - return Country::where('iso_3166_2', $name)->exists() - ? Country::where('iso_3166_2', $name)->first()->id + return Country::query()->where('iso_3166_2', $name)->exists() + ? Country::query()->where('iso_3166_2', $name)->first()->id : null; } @@ -428,7 +428,7 @@ class BaseTransformer { $name = strtolower(trim($name)); - $tax_rate = TaxRate::where('company_id', $this->company->id) + $tax_rate = TaxRate::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), @@ -447,7 +447,7 @@ class BaseTransformer { $name = strtolower(trim($name)); - $tax_rate = TaxRate::where('company_id', $this->company->id) + $tax_rate = TaxRate::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), @@ -495,7 +495,7 @@ class BaseTransformer */ public function getInvoiceId($invoice_number) { - $invoice = Invoice::where('company_id', $this->company->id) + $invoice = Invoice::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $invoice_number)), @@ -512,7 +512,7 @@ class BaseTransformer */ public function hasInvoice($invoice_number) { - return Invoice::where('company_id', $this->company->id) + return Invoice::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $invoice_number)), @@ -528,7 +528,7 @@ class BaseTransformer */ public function hasRecurringInvoice($invoice_number) { - return RecurringInvoice::where('company_id', $this->company->id) + return RecurringInvoice::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $invoice_number)), @@ -541,7 +541,7 @@ class BaseTransformer */ public function hasExpense($expense_number) { - return Expense::where('company_id', $this->company->id) + return Expense::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $expense_number)), @@ -556,7 +556,7 @@ class BaseTransformer */ public function hasQuote($quote_number) { - return Quote::where('company_id', $this->company->id) + return Quote::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $quote_number)), @@ -571,7 +571,7 @@ class BaseTransformer */ public function getInvoiceClientId($invoice_number) { - $invoice = Invoice::where('company_id', $this->company->id) + $invoice = Invoice::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`number`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $invoice_number)), @@ -588,7 +588,7 @@ class BaseTransformer */ public function getVendorId($name) { - $vendor = Vendor::where('company_id', $this->company->id) + $vendor = Vendor::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), @@ -626,7 +626,7 @@ class BaseTransformer { /** @var \App\Models\ExpenseCategory $ec */ - $ec = ExpenseCategory::where('company_id', $this->company->id) + $ec = ExpenseCategory::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), @@ -669,7 +669,7 @@ class BaseTransformer */ public function getProjectId($name, $clientId = null) { - $project = Project::where('company_id', $this->company->id) + $project = Project::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), @@ -700,7 +700,7 @@ class BaseTransformer */ public function getPaymentTypeId($name) { - $pt = PaymentType::whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ + $pt = PaymentType::query()->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $name)), ])->first(); diff --git a/app/Import/Transformer/Zoho/InvoiceTransformer.php b/app/Import/Transformer/Zoho/InvoiceTransformer.php index 2c13bce53c..faae4fffa2 100644 --- a/app/Import/Transformer/Zoho/InvoiceTransformer.php +++ b/app/Import/Transformer/Zoho/InvoiceTransformer.php @@ -102,7 +102,7 @@ class InvoiceTransformer extends BaseTransformer $client_name = $this->getString($invoice_data, 'Customer Name'); if(strlen($client_name) >= 2) { - $client_name_search = \App\Models\Client::where('company_id', $this->company->id) + $client_name_search = \App\Models\Client::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->whereRaw("LOWER(REPLACE(`name`, ' ' ,'')) = ?", [ strtolower(str_replace(' ', '', $client_name)), @@ -115,7 +115,7 @@ class InvoiceTransformer extends BaseTransformer $customer_id = $this->getString($invoice_data, 'Customer ID'); - $client_id_search = \App\Models\Client::where('company_id', $this->company->id) + $client_id_search = \App\Models\Client::query()->where('company_id', $this->company->id) ->where('is_deleted', false) ->where('id_number', trim($customer_id)); diff --git a/app/Models/Company.php b/app/Models/Company.php index f1fbea97fd..932a3899c9 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -200,6 +200,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; * @property-read int|null $vendors_count * @property-read \Illuminate\Database\Eloquent\Collection $webhooks * @method static \Illuminate\Database\Eloquent\Builder|Company where($query) + * @method static \Illuminate\Database\Eloquent\Builder|Company find($query) * @property-read int|null $webhooks_count * @property int $calculate_taxes * @property mixed $tax_data From cd7d78d20bbfc346f3c19924af2e9eb663d83840 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 15:30:34 +1000 Subject: [PATCH 17/33] Updated static analysis --- .../Documents/ShowDocumentRequest.php | 3 +-- app/Jobs/Bank/MatchBankTransactions.php | 1 + app/Jobs/Company/CompanyExport.php | 6 +++--- app/Jobs/Company/CompanyImport.php | 5 +++-- app/Jobs/Credit/ZipCredits.php | 3 --- app/Jobs/Cron/AutoBillCron.php | 12 ++++++++---- app/Jobs/Cron/SendCompanyRecurring.php | 14 ++------------ app/Jobs/Entity/CreateEntityPdf.php | 13 +++++++------ app/Jobs/Inventory/AdjustProductInventory.php | 6 +++--- app/Jobs/Invitation/MarkOpened.php | 2 +- app/Jobs/Invoice/CreateUbl.php | 1 + app/Jobs/Invoice/InvoiceWorkflowSettings.php | 6 +----- app/Jobs/Mail/NinjaMailerJob.php | 2 +- app/Jobs/PostMark/ProcessPostmarkWebhook.php | 10 ++-------- app/Jobs/Product/UpdateOrCreateProduct.php | 8 +------- app/Jobs/User/UserEmailChanged.php | 17 ++++------------- app/Jobs/User/VerifyPhone.php | 2 +- app/Jobs/Util/Import.php | 11 ++++++----- app/Models/Company.php | 5 ++++- app/Models/TaxRate.php | 1 + 20 files changed, 51 insertions(+), 77 deletions(-) diff --git a/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php b/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php index 691cfe1d05..dd1202d22a 100644 --- a/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php +++ b/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php @@ -28,8 +28,7 @@ class ShowDocumentRequest extends FormRequest { /** @var \App\Models\VendorContact auth()->guard('vendor')->user() */ - - return auth()->guard('vendor')->user()->client_id == $this->document->documentable_id + return auth()->guard('vendor')->user()->vendor_id == $this->document->documentable_id || $this->document->company_id == auth()->guard('vendor')->user()->company_id; } diff --git a/app/Jobs/Bank/MatchBankTransactions.php b/app/Jobs/Bank/MatchBankTransactions.php index c4084047df..7b0c9abe22 100644 --- a/app/Jobs/Bank/MatchBankTransactions.php +++ b/app/Jobs/Bank/MatchBankTransactions.php @@ -47,6 +47,7 @@ class MatchBankTransactions implements ShouldQueue private array $input; + /** @var \App\Models\Company */ protected ?Company $company; public Invoice $invoice; diff --git a/app/Jobs/Company/CompanyExport.php b/app/Jobs/Company/CompanyExport.php index 0cbb91f9a5..0a496b4c9f 100644 --- a/app/Jobs/Company/CompanyExport.php +++ b/app/Jobs/Company/CompanyExport.php @@ -48,9 +48,9 @@ class CompanyExport implements ShouldQueue /** * Create a new job instance. * - * @param Company $company - * @param User $user - * @param string $custom_token_name + * @param \App\Models\Company $company + * @param \App\Models\User $user + * @param string $hash */ public function __construct(public Company $company, private User $user, public string $hash) { diff --git a/app/Jobs/Company/CompanyImport.php b/app/Jobs/Company/CompanyImport.php index 7ec07abc61..25406a2660 100644 --- a/app/Jobs/Company/CompanyImport.php +++ b/app/Jobs/Company/CompanyImport.php @@ -244,7 +244,7 @@ class CompanyImport implements ShouldQueue { MultiDB::setDb($this->company->db); - $this->company = Company::where('company_key', $this->company->company_key)->firstOrFail(); + $this->company = Company::query()->where('company_key', $this->company->company_key)->firstOrFail(); $this->account = $this->company->account; $this->company_owner = $this->company->owner(); @@ -591,6 +591,7 @@ class CompanyImport implements ShouldQueue unset($obj_array['id']); unset($obj_array['tax_rate_id']); + /** @var \App\Models\TaxRate $new_obj */ $new_obj = TaxRate::firstOrNew( ['name' => $obj->name, 'company_id' => $this->company->id, 'rate' => $obj->rate], $obj_array, @@ -1427,7 +1428,7 @@ class CompanyImport implements ShouldQueue if ($class == 'App\Models\Subscription') { $obj_array['product_ids'] = $this->recordProductIds($obj_array['product_ids']); $obj_array['recurring_product_ids'] = $this->recordProductIds($obj_array['recurring_product_ids']); - $obj_array['webhook_configuration'] = json_encode($obj_array['webhook_configuration']); + $obj_array['webhook_configuration'] = \json_encode($obj_array['webhook_configuration']); } $new_obj = $class::firstOrNew( diff --git a/app/Jobs/Credit/ZipCredits.php b/app/Jobs/Credit/ZipCredits.php index b649d6f7ee..3b648bd7a2 100644 --- a/app/Jobs/Credit/ZipCredits.php +++ b/app/Jobs/Credit/ZipCredits.php @@ -62,9 +62,6 @@ class ZipCredits implements ShouldQueue * Execute the job. * * @return void - * @throws \ZipStream\Exception\FileNotFoundException - * @throws \ZipStream\Exception\FileNotReadableException - * @throws \ZipStream\Exception\OverflowException */ public function handle() { diff --git a/app/Jobs/Cron/AutoBillCron.php b/app/Jobs/Cron/AutoBillCron.php index f0e4343964..cf2c5f987f 100644 --- a/app/Jobs/Cron/AutoBillCron.php +++ b/app/Jobs/Cron/AutoBillCron.php @@ -49,7 +49,8 @@ class AutoBillCron Auth::logout(); if (! config('ninja.db.multi_db_enabled')) { - $auto_bill_partial_invoices = Invoice::whereDate('partial_due_date', '<=', now()) + $auto_bill_partial_invoices = Invoice::query() + ->whereDate('partial_due_date', '<=', now()) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('auto_bill_enabled', true) ->where('auto_bill_tries', '<', 3) @@ -70,7 +71,8 @@ class AutoBillCron sleep(2); }); - $auto_bill_invoices = Invoice::whereDate('due_date', '<=', now()) + $auto_bill_invoices = Invoice::query() + ->whereDate('due_date', '<=', now()) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('auto_bill_enabled', true) ->where('auto_bill_tries', '<', 3) @@ -95,7 +97,8 @@ class AutoBillCron foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); - $auto_bill_partial_invoices = Invoice::whereDate('partial_due_date', '<=', now()) + $auto_bill_partial_invoices = Invoice::query() + ->whereDate('partial_due_date', '<=', now()) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('auto_bill_enabled', true) ->where('auto_bill_tries', '<', 3) @@ -116,7 +119,8 @@ class AutoBillCron sleep(2); }); - $auto_bill_invoices = Invoice::whereDate('due_date', '<=', now()) + $auto_bill_invoices = Invoice::query() + ->whereDate('due_date', '<=', now()) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('auto_bill_enabled', true) ->where('auto_bill_tries', '<', 3) diff --git a/app/Jobs/Cron/SendCompanyRecurring.php b/app/Jobs/Cron/SendCompanyRecurring.php index 6b1d31e7da..85dd0bed19 100644 --- a/app/Jobs/Cron/SendCompanyRecurring.php +++ b/app/Jobs/Cron/SendCompanyRecurring.php @@ -25,21 +25,11 @@ class SendCompanyRecurring public $tries = 1; - /** - * Create a new job instance. - * - * @return void - */ - + /** @var \App\Models\Company $company */ public $company; - public $db; - - public function __construct($company_id, $db) + public function __construct(private int $company_id, private string $db) { - $this->company_id = $company_id; - - $this->db = $db; } /** diff --git a/app/Jobs/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php index fe25cd4103..fa6337e147 100644 --- a/app/Jobs/Entity/CreateEntityPdf.php +++ b/app/Jobs/Entity/CreateEntityPdf.php @@ -47,19 +47,19 @@ class CreateEntityPdf implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, NumberFormatter, MakesInvoiceHtml, PdfMaker, MakesHash, PageNumbering; - public $entity; + public \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\RecurringInvoice $entity; - public $company; + public \App\Models\Company $company; - public $contact; + public \App\Models\ClientContact$contact; private $disk; - public $invitation; + public \App\Models\InvoiceInvitation | \App\Models\QuoteInvitation | \App\Models\CreditInvitation | \App\Models\RecurringInvoiceInvitation $invitation; - public $entity_string = ''; + public string $entity_string = ''; - public $client; + public \App\Models\Client $client; public $deleteWhenMissingModels = true; @@ -135,6 +135,7 @@ class CreateEntityPdf implements ShouldQueue $entity_design_id = $this->entity->design_id ? $this->entity->design_id : $this->decodePrimaryKey($this->client->getSetting($entity_design_id)); + /** @var \App\Models\Design $design */ $design = Design::withTrashed()->find($entity_design_id); /* Catch all in case migration doesn't pass back a valid design */ diff --git a/app/Jobs/Inventory/AdjustProductInventory.php b/app/Jobs/Inventory/AdjustProductInventory.php index 8463a10ad7..4b5ed18464 100644 --- a/app/Jobs/Inventory/AdjustProductInventory.php +++ b/app/Jobs/Inventory/AdjustProductInventory.php @@ -71,7 +71,7 @@ class AdjustProductInventory implements ShouldQueue collect($this->invoice->line_items)->filter(function ($item) { return $item->type_id == '1'; })->each(function ($i) { - $p = Product::where('product_key', $i->product_key)->where('company_id', $this->company->id)->first(); + $p = Product::query()->where('product_key', $i->product_key)->where('company_id', $this->company->id)->first(); if ($p) { $p->in_stock_quantity += $i->quantity; @@ -88,7 +88,7 @@ class AdjustProductInventory implements ShouldQueue collect($this->invoice->line_items)->filter(function ($item) { return $item->type_id == '1'; })->each(function ($i) { - $p = Product::where('product_key', $i->product_key)->where('company_id', $this->company->id)->first(); + $p = Product::query()->where('product_key', $i->product_key)->where('company_id', $this->company->id)->first(); if ($p) { $p->in_stock_quantity -= $i->quantity; @@ -109,7 +109,7 @@ class AdjustProductInventory implements ShouldQueue collect($this->invoice->line_items)->filter(function ($item) { return $item->type_id == '1'; })->each(function ($i) { - $p = Product::where('product_key', $i->product_key)->where('company_id', $this->company->id)->first(); + $p = Product::query()->where('product_key', $i->product_key)->where('company_id', $this->company->id)->first(); if ($p) { $p->in_stock_quantity -= $i->quantity; diff --git a/app/Jobs/Invitation/MarkOpened.php b/app/Jobs/Invitation/MarkOpened.php index 8901430562..6c9b903a8e 100644 --- a/app/Jobs/Invitation/MarkOpened.php +++ b/app/Jobs/Invitation/MarkOpened.php @@ -45,7 +45,7 @@ class MarkOpened implements ShouldQueue * Execute the job. * * - * @return false + * @return void */ public function handle() { diff --git a/app/Jobs/Invoice/CreateUbl.php b/app/Jobs/Invoice/CreateUbl.php index 4417265835..369b1563ff 100644 --- a/app/Jobs/Invoice/CreateUbl.php +++ b/app/Jobs/Invoice/CreateUbl.php @@ -197,6 +197,7 @@ class CreateUbl implements ShouldQueue if ($this->invoice->discount != 0) { if ($this->invoice->is_amount_discount) { + /** @var float $invoice_total */ if ($invoice_total + $this->invoice->discount != 0) { $total -= $invoice_total ? ($total / ($invoice_total + $this->invoice->discount) * $this->invoice->discount) : 0; } diff --git a/app/Jobs/Invoice/InvoiceWorkflowSettings.php b/app/Jobs/Invoice/InvoiceWorkflowSettings.php index adb446fb4b..615b43ad92 100644 --- a/app/Jobs/Invoice/InvoiceWorkflowSettings.php +++ b/app/Jobs/Invoice/InvoiceWorkflowSettings.php @@ -25,8 +25,6 @@ class InvoiceWorkflowSettings implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - public $invoice; - public $client; private $base_repository; @@ -35,11 +33,9 @@ class InvoiceWorkflowSettings implements ShouldQueue * Create a new job instance. * * @param Invoice $invoice - * @param Client|null $client */ - public function __construct(Invoice $invoice) + public function __construct(public Invoice $invoice) { - $this->invoice = $invoice; $this->base_repository = new BaseRepository(); } diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php index 0e81d544f9..9d82b6857a 100644 --- a/app/Jobs/Mail/NinjaMailerJob.php +++ b/app/Jobs/Mail/NinjaMailerJob.php @@ -51,7 +51,7 @@ class NinjaMailerJob implements ShouldQueue public $override; - /* @var Company $company*/ + /* @var \App\Models\Company $company*/ public ?Company $company; private $mailer; diff --git a/app/Jobs/PostMark/ProcessPostmarkWebhook.php b/app/Jobs/PostMark/ProcessPostmarkWebhook.php index c2497a3b56..d99455ab32 100644 --- a/app/Jobs/PostMark/ProcessPostmarkWebhook.php +++ b/app/Jobs/PostMark/ProcessPostmarkWebhook.php @@ -39,20 +39,14 @@ class ProcessPostmarkWebhook implements ShouldQueue public $tries = 1; - private array $request; - public $invitation; + /** * Create a new job instance. * - * @param Payment $payment - * @param $email_builder - * @param $contact - * @param $company */ - public function __construct(array $request) + public function __construct(private array $request) { - $this->request = $request; } /** diff --git a/app/Jobs/Product/UpdateOrCreateProduct.php b/app/Jobs/Product/UpdateOrCreateProduct.php index 7405ed4ee1..bc9b5017d9 100644 --- a/app/Jobs/Product/UpdateOrCreateProduct.php +++ b/app/Jobs/Product/UpdateOrCreateProduct.php @@ -78,6 +78,7 @@ class UpdateOrCreateProduct implements ShouldQueue return $item->type_id == 1; }); + /** @var \App\DataMapper\InvoiceItem $item */ foreach ($updateable_products as $item) { if (empty($item->product_key)) { continue; @@ -106,13 +107,6 @@ class UpdateOrCreateProduct implements ShouldQueue $product->quantity = isset($item->quantity) ? $item->quantity : 0; } - // $product->tax_name1 = isset($item->tax_name1) ? $item->tax_name1 : ''; - // $product->tax_rate1 = isset($item->tax_rate1) ? $item->tax_rate1 : 0; - // $product->tax_name2 = isset($item->tax_name2) ? $item->tax_name2 : ''; - // $product->tax_rate2 = isset($item->tax_rate2) ? $item->tax_rate2 : 0; - // $product->tax_name3 = isset($item->tax_name3) ? $item->tax_name3 : ''; - // $product->tax_rate3 = isset($item->tax_rate3) ? $item->tax_rate3 : 0; - if (isset($item->custom_value1) && strlen($item->custom_value1) >=1) { $product->custom_value1 = $item->custom_value1; } diff --git a/app/Jobs/User/UserEmailChanged.php b/app/Jobs/User/UserEmailChanged.php index b400684f05..c397f1ae65 100644 --- a/app/Jobs/User/UserEmailChanged.php +++ b/app/Jobs/User/UserEmailChanged.php @@ -30,26 +30,17 @@ class UserEmailChanged implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - protected $new_user; - - protected $old_user; - - protected $company; - public $settings; /** * Create a new job instance. * - * @param string $new_email - * @param string $old_email - * @param Company $company + * @param \App\Models\User $new_user + * @param \App\Models\User $old_user + * @param \App\Models\Company $company */ - public function __construct(User $new_user, $old_user, Company $company) + public function __construct(protected User $new_user, protected User $old_user, protected Company $company) { - $this->new_user = $new_user; - $this->old_user = $old_user; - $this->company = $company; $this->settings = $this->company->settings; } diff --git a/app/Jobs/User/VerifyPhone.php b/app/Jobs/User/VerifyPhone.php index e28c77afb4..afeb33566d 100644 --- a/app/Jobs/User/VerifyPhone.php +++ b/app/Jobs/User/VerifyPhone.php @@ -37,7 +37,7 @@ class VerifyPhone implements ShouldQueue /** * Execute the job. * - * @return User|null + * @return void */ public function handle() : void { diff --git a/app/Jobs/Util/Import.php b/app/Jobs/Util/Import.php index d35b50cb70..bd6eaa1c89 100644 --- a/app/Jobs/Util/Import.php +++ b/app/Jobs/Util/Import.php @@ -173,10 +173,11 @@ class Import implements ShouldQueue /** * Create a new job instance. * - * @param array $data + * @param string $file_path * @param Company $company * @param User $user * @param array $resources + * @param bool $silent_migration */ public function __construct(string $file_path, Company $company, User $user, array $resources = [], $silent_migration = false) { @@ -195,7 +196,6 @@ class Import implements ShouldQueue /** * Execute the job. * - * @return bool */ public function handle() { @@ -302,7 +302,7 @@ class Import implements ShouldQueue // 10/02/21 foreach ($client->payments as $payment) { - $credit_total_applied += $payment->paymentables()->where('paymentable_type', App\Models\Credit::class)->get()->sum(\DB::raw('amount')); + $credit_total_applied += $payment->paymentables()->where('paymentable_type', \App\Models\Credit::class)->get()->sum(\DB::raw('amount')); } if ($credit_total_applied < 0) { @@ -319,7 +319,7 @@ class Import implements ShouldQueue private function setInitialCompanyLedgerBalances() { - Client::where('company_id', $this->company->id)->cursor()->each(function ($client) { + Client::query()->where('company_id', $this->company->id)->cursor()->each(function ($client) { $invoice_balances = $client->invoices->where('is_deleted', false)->where('status_id', '>', 1)->sum('balance'); $company_ledger = CompanyLedgerFactory::create($client->company_id, $client->user_id); @@ -954,6 +954,7 @@ class Import implements ShouldQueue $modified['vendor_id'] = $this->transformId('vendors', $resource['vendor_id']); } + /** @var \App\Models\Expense $expense */ $expense = RecurringExpense::create($modified); if (array_key_exists('created_at', $modified)) { @@ -1622,7 +1623,7 @@ class Import implements ShouldQueue $modified['gateway_key'] = 'd14dd26a37cecc30fdd65700bfb55b23'; } - + /** @var \App\Models\CompanyGateway $company_gateway */ $company_gateway = CompanyGateway::create($modified); $key = "company_gateways_{$resource['id']}"; diff --git a/app/Models/Company.php b/app/Models/Company.php index 932a3899c9..591563d46a 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -451,6 +451,9 @@ class Company extends BaseModel return $this->hasMany(ClientContact::class)->withTrashed(); } + /** + * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough + */ public function users(): \Illuminate\Database\Eloquent\Relations\HasManyThrough { return $this->hasManyThrough(User::class, CompanyUser::class, 'company_id', 'id', 'id', 'user_id')->withTrashed(); @@ -510,7 +513,7 @@ class Company extends BaseModel return $this->hasMany(Vendor::class)->withTrashed(); } - public function all_activities() :HasMany + public function all_activities() :\Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Activity::class); } diff --git a/app/Models/TaxRate.php b/app/Models/TaxRate.php index 6caab9a185..9ae870fcf5 100644 --- a/app/Models/TaxRate.php +++ b/app/Models/TaxRate.php @@ -48,6 +48,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @method static \Illuminate\Database\Eloquent\Builder|TaxRate whereUserId($value) * @method static \Illuminate\Database\Eloquent\Builder|TaxRate withTrashed() * @method static \Illuminate\Database\Eloquent\Builder|TaxRate withoutTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|TaxRate firstOrNew() * @mixin \Eloquent */ class TaxRate extends BaseModel From b4a682df52b3a73fa8158e0bfbe5ad19f56539cf Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 15:33:40 +1000 Subject: [PATCH 18/33] Updated static analysis --- app/Jobs/Util/VersionCheck.php | 4 ++-- app/Jobs/Util/WebhookSingle.php | 3 +-- app/Jobs/Vendor/CreatePurchaseOrderPdf.php | 1 + 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/Jobs/Util/VersionCheck.php b/app/Jobs/Util/VersionCheck.php index 6d40a3e717..fe4cf70160 100644 --- a/app/Jobs/Util/VersionCheck.php +++ b/app/Jobs/Util/VersionCheck.php @@ -38,13 +38,13 @@ class VersionCheck implements ShouldQueue $version_file = trim(@file_get_contents(config('ninja.version_url'))); if (Ninja::isSelfHost() && $version_file) { - /** @var \App\Models\Account $account **/ - Account::whereNotNull('id')->update(['latest_version' => $version_file]); + Account::query()->whereNotNull('id')->update(['latest_version' => $version_file]); } if (Ninja::isSelfHost()) { nlog("latest version = {$version_file}"); + /** @var \App\Models\Account $account **/ $account = Account::first(); if (! $account) { diff --git a/app/Jobs/Util/WebhookSingle.php b/app/Jobs/Util/WebhookSingle.php index 26f79e9922..c30fef90e5 100644 --- a/app/Jobs/Util/WebhookSingle.php +++ b/app/Jobs/Util/WebhookSingle.php @@ -71,13 +71,12 @@ class WebhookSingle implements ShouldQueue /** * Execute the job. * - * @return bool */ public function handle() { MultiDB::setDb($this->db); - $subscription = Webhook::with('company')->find($this->subscription_id); + $subscription = Webhook::query()->with('company')->find($this->subscription_id); if ($subscription) { // nlog("firing event ID {$subscription->event_id} company_id {$subscription->company_id}"); diff --git a/app/Jobs/Vendor/CreatePurchaseOrderPdf.php b/app/Jobs/Vendor/CreatePurchaseOrderPdf.php index 607f78d0b9..fe6029aa20 100644 --- a/app/Jobs/Vendor/CreatePurchaseOrderPdf.php +++ b/app/Jobs/Vendor/CreatePurchaseOrderPdf.php @@ -124,6 +124,7 @@ class CreatePurchaseOrderPdf implements ShouldQueue /* Catch all in case migration doesn't pass back a valid design */ if (!$design) { + /** @var \App\Models\Design $design */ $design = Design::find(2); } From b97de29f748abfa06a84050f372e2a6bb136b93a Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 15:37:30 +1000 Subject: [PATCH 19/33] Updated static analysis --- .../RecurringInvoice/StoreRecurringInvoiceRequest.php | 4 ++-- .../ValidationRules/Ninja/CanStoreClientsRule.php | 11 ++++++----- app/Jobs/Bank/MatchBankTransactions.php | 2 +- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php index aa8c8f406d..37b0cbc99c 100644 --- a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php @@ -141,8 +141,8 @@ class StoreRecurringInvoiceRequest extends Request if (isset($input['auto_bill'])) { $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); } else { - /** @var \App\Models\Client $client */ - if (array_key_exists('client_id', $input) && $client = Client::find($input['client_id'])) { + if (array_key_exists('client_id', $input) && $client = Client::query()->find($input['client_id'])) { + /** @var \App\Models\Client $client */ $input['auto_bill'] = $client->getSetting('auto_bill'); $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); } diff --git a/app/Http/ValidationRules/Ninja/CanStoreClientsRule.php b/app/Http/ValidationRules/Ninja/CanStoreClientsRule.php index 8bd700fefe..99e726254e 100644 --- a/app/Http/ValidationRules/Ninja/CanStoreClientsRule.php +++ b/app/Http/ValidationRules/Ninja/CanStoreClientsRule.php @@ -19,13 +19,14 @@ use Illuminate\Contracts\Validation\Rule; */ class CanStoreClientsRule implements Rule { - public $company_id; - public \App\Models\Company $company; + /** + * @var \App\Models\Company $company + */ + public Company $company; - public function __construct($company_id) + public function __construct(public int $company_id) { - $this->company_id = $company_id; } /** @@ -35,7 +36,7 @@ class CanStoreClientsRule implements Rule */ public function passes($attribute, $value) { - $this->company = Company::find($this->company_id); + $this->company = Company::query()->find($this->company_id); return $this->company->clients()->count() < $this->company->account->hosted_client_count; } diff --git a/app/Jobs/Bank/MatchBankTransactions.php b/app/Jobs/Bank/MatchBankTransactions.php index 7b0c9abe22..278c5f5838 100644 --- a/app/Jobs/Bank/MatchBankTransactions.php +++ b/app/Jobs/Bank/MatchBankTransactions.php @@ -84,7 +84,7 @@ class MatchBankTransactions implements ShouldQueue { MultiDB::setDb($this->db); - $this->company = Company::find($this->company_id); + $this->company = Company::query()->find($this->company_id); if ($this->company->account->bank_integration_account_id) { $yodlee = new Yodlee($this->company->account->bank_integration_account_id); From 0c683f040372359b8669cae97de76f94aa158564 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 17:02:02 +1000 Subject: [PATCH 20/33] fixes for tests --- app/Jobs/Entity/CreateEntityPdf.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Jobs/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php index fa6337e147..abb6324651 100644 --- a/app/Jobs/Entity/CreateEntityPdf.php +++ b/app/Jobs/Entity/CreateEntityPdf.php @@ -47,7 +47,7 @@ class CreateEntityPdf implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, NumberFormatter, MakesInvoiceHtml, PdfMaker, MakesHash, PageNumbering; - public \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\RecurringInvoice $entity; + public \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\RecurringInvoice | null $entity; public \App\Models\Company $company; From 87b2be8572629f9dda107ffa63753fdd5262a097 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 18:29:07 +1000 Subject: [PATCH 21/33] Roll back static analysis for socialite --- app/Helpers/Invoice/InvoiceItemSumInclusive.php | 2 +- app/Helpers/Mail/GmailTransport.php | 1 - app/Helpers/Mail/Office365MailTransport.php | 4 ++++ app/Jobs/Bank/MatchBankTransactions.php | 5 +++-- app/Jobs/Company/CompanyExport.php | 2 +- app/Utils/Traits/NumberFormatter.php | 10 ++++++++-- phpstan.neon | 3 ++- 7 files changed, 19 insertions(+), 8 deletions(-) diff --git a/app/Helpers/Invoice/InvoiceItemSumInclusive.php b/app/Helpers/Invoice/InvoiceItemSumInclusive.php index 238f486365..b2a4b40337 100644 --- a/app/Helpers/Invoice/InvoiceItemSumInclusive.php +++ b/app/Helpers/Invoice/InvoiceItemSumInclusive.php @@ -94,7 +94,7 @@ class InvoiceItemSumInclusive protected RecurringInvoice | Invoice | Quote | Credit | PurchaseOrder | RecurringQuote $invoice; - private $currency; + private \App\Models\Currency $currency; private $total_taxes; diff --git a/app/Helpers/Mail/GmailTransport.php b/app/Helpers/Mail/GmailTransport.php index 1538edcfde..1a787113af 100644 --- a/app/Helpers/Mail/GmailTransport.php +++ b/app/Helpers/Mail/GmailTransport.php @@ -33,7 +33,6 @@ class GmailTransport extends AbstractTransport nlog("In Do Send"); $message = MessageConverter::toEmail($message->getOriginalMessage()); - /** @phpstan-ignore-next-line **/ $token = $message->getHeaders()->get('gmailtoken')->getValue(); $message->getHeaders()->remove('gmailtoken'); diff --git a/app/Helpers/Mail/Office365MailTransport.php b/app/Helpers/Mail/Office365MailTransport.php index 246ebb0250..6a94139a76 100644 --- a/app/Helpers/Mail/Office365MailTransport.php +++ b/app/Helpers/Mail/Office365MailTransport.php @@ -28,6 +28,8 @@ class Office365MailTransport extends AbstractTransport $symfony_message = MessageConverter::toEmail($message->getOriginalMessage()); $graph = new Graph(); + + /** @phpstan-ignore-next-line **/ $token = $symfony_message->getHeaders()->get('gmailtoken')->getValue(); $symfony_message->getHeaders()->remove('gmailtoken'); @@ -38,6 +40,8 @@ class Office365MailTransport extends AbstractTransport $bcc_list = ''; if ($bccs) { + + /** @phpstan-ignore-next-line **/ foreach ($bccs->getAddresses() as $address) { $bcc_list .= 'Bcc: "'.$address->getAddress().'" <'.$address->getAddress().'>\r\n'; } diff --git a/app/Jobs/Bank/MatchBankTransactions.php b/app/Jobs/Bank/MatchBankTransactions.php index 278c5f5838..164dede3a0 100644 --- a/app/Jobs/Bank/MatchBankTransactions.php +++ b/app/Jobs/Bank/MatchBankTransactions.php @@ -52,6 +52,7 @@ class MatchBankTransactions implements ShouldQueue public Invoice $invoice; + /** @var \App\Models\BankTransaction $bt */ private ?BankTransaction $bt; private $categories; @@ -194,7 +195,7 @@ class MatchBankTransactions implements ShouldQueue private function linkPayment($input) { - $this->bt = BankTransaction::find($input['id']); + $this->bt = BankTransaction::query()->withTrashed()->find($input['id']); if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) { return $this; @@ -244,7 +245,7 @@ class MatchBankTransactions implements ShouldQueue private function matchExpense($input) :self { //if there is a category id, pull it from Yodlee and insert - or just reuse!! - $this->bt = BankTransaction::find($input['id']); + $this->bt = BankTransaction::query()->withTrashed()->find($input['id']); if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) { return $this; diff --git a/app/Jobs/Company/CompanyExport.php b/app/Jobs/Company/CompanyExport.php index 0a496b4c9f..1a3bfc43b2 100644 --- a/app/Jobs/Company/CompanyExport.php +++ b/app/Jobs/Company/CompanyExport.php @@ -65,7 +65,7 @@ class CompanyExport implements ShouldQueue { MultiDB::setDb($this->company->db); - $this->company = Company::where('company_key', $this->company->company_key)->first(); + $this->company = Company::query()->where('company_key', $this->company->company_key)->first(); set_time_limit(0); diff --git a/app/Utils/Traits/NumberFormatter.php b/app/Utils/Traits/NumberFormatter.php index 96684e0365..e2ea72649e 100644 --- a/app/Utils/Traits/NumberFormatter.php +++ b/app/Utils/Traits/NumberFormatter.php @@ -16,7 +16,14 @@ namespace App\Utils\Traits; */ trait NumberFormatter { - private function formatValue($value, $precision) : string + /** + * Undocumented function + * + * @param float $value + * @param int $precision + * @return string|float + */ + private function formatValue($value, $precision) { /* 08-01-2022 allow increased precision means we need to transform from scientific notation to a regular string */ @@ -27,7 +34,6 @@ trait NumberFormatter * Parse a float value that may be delimited with either a comma or decimal point. * * @param string $value The value - * * @return float Consumable float value */ private function parseFloat($value) : float diff --git a/phpstan.neon b/phpstan.neon index 476dbfada6..670c37f467 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -20,4 +20,5 @@ parameters: - '#Call to an undefined method [a-zA-Z0-9\\_]+::entityFilter\(\)#' - '#Call to an undefined method [a-zA-Z0-9\\_]+::exclude\(\)#' - '#Array has 2 duplicate keys with value#' - - '#Undefined method#' \ No newline at end of file + - '#Undefined method#' + - '#makeHidden#' \ No newline at end of file From b332e637b54e8fb92704e1cf4cc22b52a889cdd5 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 18:36:04 +1000 Subject: [PATCH 22/33] Updates for static analysis --- app/Utils/Helpers.php | 12 +++++----- app/Utils/TemplateEngine.php | 45 ++++++++++++++++++++---------------- phpstan.neon | 3 ++- 3 files changed, 33 insertions(+), 27 deletions(-) diff --git a/app/Utils/Helpers.php b/app/Utils/Helpers.php index 912cc47f71..0debc7da42 100644 --- a/app/Utils/Helpers.php +++ b/app/Utils/Helpers.php @@ -177,27 +177,27 @@ class Helpers 'literal' => [ ':MONTH_BEFORE' => \sprintf( '%s %s %s', - $currentDateTime->copy()->subMonth(1)->translatedFormat($entity->date_format()), + $currentDateTime->copy()->subMonth()->translatedFormat($entity->date_format()), ctrans('texts.to'), - $currentDateTime->copy()->subDay(1)->translatedFormat($entity->date_format()), + $currentDateTime->copy()->subDay()->translatedFormat($entity->date_format()), ), ':YEAR_BEFORE' => \sprintf( '%s %s %s', - $currentDateTime->copy()->subYear(1)->translatedFormat($entity->date_format()), + $currentDateTime->copy()->subYear()->translatedFormat($entity->date_format()), ctrans('texts.to'), - $currentDateTime->copy()->subDay(1)->translatedFormat($entity->date_format()), + $currentDateTime->copy()->subDay()->translatedFormat($entity->date_format()), ), ':MONTH_AFTER' => \sprintf( '%s %s %s', $currentDateTime->translatedFormat($entity->date_format()), ctrans('texts.to'), - $currentDateTime->copy()->addMonth(1)->subDay(1)->translatedFormat($entity->date_format()), + $currentDateTime->copy()->addMonth()->subDay()->translatedFormat($entity->date_format()), ), ':YEAR_AFTER' => \sprintf( '%s %s %s', $currentDateTime->translatedFormat($entity->date_format()), ctrans('texts.to'), - $currentDateTime->copy()->addYear(1)->subDay(1)->translatedFormat($entity->date_format()), + $currentDateTime->copy()->addYear()->subDay()->translatedFormat($entity->date_format()), ), ':MONTHYEAR' => \sprintf( '%s %s', diff --git a/app/Utils/TemplateEngine.php b/app/Utils/TemplateEngine.php index 51fcb2dc1a..3cd5221d5d 100644 --- a/app/Utils/TemplateEngine.php +++ b/app/Utils/TemplateEngine.php @@ -12,27 +12,29 @@ namespace App\Utils; -use App\DataMapper\EmailTemplateDefaults; -use App\Mail\Engine\PaymentEmailEngine; -use App\Models\Client; -use App\Models\ClientContact; -use App\Models\Invoice; -use App\Models\InvoiceInvitation; -use App\Models\Payment; -use App\Models\PurchaseOrder; -use App\Models\PurchaseOrderInvitation; -use App\Models\Quote; -use App\Models\QuoteInvitation; -use App\Models\Vendor; -use App\Models\VendorContact; -use App\Services\PdfMaker\Designs\Utilities\DesignHelpers; -use App\Utils\Traits\MakesHash; -use App\Utils\Traits\MakesInvoiceHtml; -use App\Utils\Traits\MakesTemplateData; use DB; -use Illuminate\Support\Facades\App; +use App\Models\Quote; +use App\Models\Client; +use App\Models\Credit; +use App\Models\Vendor; +use App\Models\Invoice; +use App\Models\Payment; use Illuminate\Support\Str; +use App\Models\ClientContact; +use App\Models\PurchaseOrder; +use App\Models\VendorContact; +use App\Models\QuoteInvitation; +use App\Utils\Traits\MakesHash; +use App\Models\RecurringInvoice; +use App\Models\InvoiceInvitation; +use Illuminate\Support\Facades\App; +use App\Utils\Traits\MakesInvoiceHtml; +use App\Mail\Engine\PaymentEmailEngine; +use App\Models\PurchaseOrderInvitation; +use App\Utils\Traits\MakesTemplateData; +use App\DataMapper\EmailTemplateDefaults; use League\CommonMark\CommonMarkConverter; +use App\Services\PdfMaker\Designs\Utilities\DesignHelpers; class TemplateEngine { @@ -50,7 +52,7 @@ class TemplateEngine public $template; - /** @var \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\PurchaseOrder | null $entity_obj **/ + /** @var Invoice | Quote | Credit | PurchaseOrder | RecurringInvoice | null $entity_obj **/ private $entity_obj; /** @var \App\Models\Company | \App\Models\Client | null $settings_entity **/ @@ -340,6 +342,7 @@ class TemplateEngine 'client_contact_id' => $contact->id, ]); + /** @var \App\Models\Invoice $invoice */ $this->entity_obj->invoices()->attach($invoice->id, [ 'amount' => 10, ]); @@ -378,11 +381,13 @@ class TemplateEngine } if ($this->entity == 'purchaseOrder') { + /** @var \App\Models\Vendor $vendor **/ $vendor = Vendor::factory()->create([ 'user_id' => $user->id, 'company_id' => $user->company()->id, ]); + /** @var \App\Models\VendorContact $contact **/ $contact = VendorContact::factory()->create([ 'user_id' => $user->id, 'company_id' => $user->company()->id, @@ -391,13 +396,13 @@ class TemplateEngine 'send_email' => true, ]); - $this->entity_obj = PurchaseOrder::factory()->create([ 'user_id' => $user->id, 'company_id' => $user->company()->id, 'vendor_id' => $vendor->id, ]); + /** @var \App\Models\PurchaseOrderInvitation $invitation **/ $invitation = PurchaseOrderInvitation::factory()->create([ 'user_id' => $user->id, 'company_id' => $user->company()->id, diff --git a/phpstan.neon b/phpstan.neon index 670c37f467..7aec499ed7 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -21,4 +21,5 @@ parameters: - '#Call to an undefined method [a-zA-Z0-9\\_]+::exclude\(\)#' - '#Array has 2 duplicate keys with value#' - '#Undefined method#' - - '#makeHidden#' \ No newline at end of file + - '#makeHidden#' + - '#Socialite#' \ No newline at end of file From 9fffa2b32983a4774bf3d582a53d3358fbc7693c Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 18:38:12 +1000 Subject: [PATCH 23/33] Fixes for tests --- app/Jobs/Entity/CreateEntityPdf.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Jobs/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php index abb6324651..42d3ad18e0 100644 --- a/app/Jobs/Entity/CreateEntityPdf.php +++ b/app/Jobs/Entity/CreateEntityPdf.php @@ -55,7 +55,7 @@ class CreateEntityPdf implements ShouldQueue private $disk; - public \App\Models\InvoiceInvitation | \App\Models\QuoteInvitation | \App\Models\CreditInvitation | \App\Models\RecurringInvoiceInvitation $invitation; + public \App\Models\InvoiceInvitation | \App\Models\QuoteInvitation | \App\Models\CreditInvitation | \App\Models\RecurringInvoiceInvitation | null $invitation; public string $entity_string = ''; From 7cc2f3c6652ad0803ce8f874b8b6a2a0ab9405b8 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 18:57:25 +1000 Subject: [PATCH 24/33] Fixes for tests --- .../Controllers/PreviewPurchaseOrderController.php | 2 +- app/Jobs/Entity/CreateEntityPdf.php | 6 +++--- app/Models/User.php | 1 - app/Transformers/Contact/InvoiceTransformer.php | 10 +++++----- app/Transformers/CreditTransformer.php | 5 +++-- app/Transformers/UserTransformer.php | 1 + app/Utils/EmailStats.php | 1 + app/Utils/PhantomJS/Phantom.php | 3 ++- 8 files changed, 16 insertions(+), 13 deletions(-) diff --git a/app/Http/Controllers/PreviewPurchaseOrderController.php b/app/Http/Controllers/PreviewPurchaseOrderController.php index 74b73b5618..8ef2da0d51 100644 --- a/app/Http/Controllers/PreviewPurchaseOrderController.php +++ b/app/Http/Controllers/PreviewPurchaseOrderController.php @@ -181,7 +181,7 @@ class PreviewPurchaseOrderController extends BaseController DB::connection(config('database.default'))->beginTransaction(); if ($request->has('entity_id')) { - /** @var \Illuminate\Database\Eloquent\Builder|\App\Models\PurchaseOrder $entity_obj|\Illuminate\Database\Eloquent\SoftDeletes */ + /** @var \App\Models\PurchaseOrder|\Illuminate\Database\Eloquent\Builder $entity_obj **/ $entity_obj = $class::on(config('database.default')) ->with('vendor.company') ->where('id', $this->decodePrimaryKey($request->input('entity_id'))) diff --git a/app/Jobs/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php index 42d3ad18e0..fec14ca6df 100644 --- a/app/Jobs/Entity/CreateEntityPdf.php +++ b/app/Jobs/Entity/CreateEntityPdf.php @@ -49,9 +49,9 @@ class CreateEntityPdf implements ShouldQueue public \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\RecurringInvoice | null $entity; - public \App\Models\Company $company; + public \App\Models\Company | null $company; - public \App\Models\ClientContact$contact; + public \App\Models\ClientContact | null $contact; private $disk; @@ -59,7 +59,7 @@ class CreateEntityPdf implements ShouldQueue public string $entity_string = ''; - public \App\Models\Client $client; + public \App\Models\Client | null $client; public $deleteWhenMissingModels = true; diff --git a/app/Models/User.php b/app/Models/User.php index 7e1784d941..4e9a2864d6 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -83,7 +83,6 @@ use Illuminate\Foundation\Auth\User as Authenticatable; * @property-read \Illuminate\Database\Eloquent\Collection $tokens * @property-read int|null $tokens_count * @property \App\Models\CompanyToken $token - * @property int $company_id * @method static \Database\Factories\UserFactory factory($count = null, $state = []) * @method static \Illuminate\Database\Eloquent\Builder|User filter(\App\Filters\QueryFilters $filters) * @method static \Illuminate\Database\Eloquent\Builder|User newModelQuery() diff --git a/app/Transformers/Contact/InvoiceTransformer.php b/app/Transformers/Contact/InvoiceTransformer.php index 1739bf95b6..2c711acd7a 100644 --- a/app/Transformers/Contact/InvoiceTransformer.php +++ b/app/Transformers/Contact/InvoiceTransformer.php @@ -50,17 +50,17 @@ class InvoiceTransformer extends EntityTransformer 'tax_name3' => $invoice->tax_name3 ? $invoice->tax_name3 : '', 'tax_rate3' => (float) $invoice->tax_rate3, 'is_amount_discount' => (bool) ($invoice->is_amount_discount ?: false), - 'invoice_footer' => $invoice->invoice_footer ?: '', + 'invoice_footer' => $invoice->footer ?: '', 'partial' => (float) ($invoice->partial ?: 0.0), 'partial_due_date' => $invoice->partial_due_date ?: '', 'custom_value1' => (float) $invoice->custom_value1, 'custom_value2' => (float) $invoice->custom_value2, 'custom_value3' => (bool) $invoice->custom_value3, 'custom_value4' => (bool) $invoice->custom_value4, - 'has_tasks' => (bool) $invoice->has_tasks, - 'has_expenses' => (bool) $invoice->has_expenses, - 'custom_text_value1' => $invoice->custom_text_value1 ?: '', - 'custom_text_value2' => $invoice->custom_text_value2 ?: '', + // 'has_tasks' => (bool) $invoice->has_tasks, + // 'has_expenses' => (bool) $invoice->has_expenses, + // 'custom_text_value1' => $invoice->custom_text_value1 ?: '', + // 'custom_text_value2' => $invoice->custom_text_value2 ?: '', 'line_items' => $invoice->line_items, ]; } diff --git a/app/Transformers/CreditTransformer.php b/app/Transformers/CreditTransformer.php index 4846b56a33..53d4f2fc0e 100644 --- a/app/Transformers/CreditTransformer.php +++ b/app/Transformers/CreditTransformer.php @@ -11,12 +11,13 @@ namespace App\Transformers; -use App\Models\Activity; use App\Models\Backup; +use App\Models\Client; use App\Models\Credit; -use App\Models\CreditInvitation; +use App\Models\Activity; use App\Models\Document; use App\Utils\Traits\MakesHash; +use App\Models\CreditInvitation; use League\Fractal\Resource\Item; class CreditTransformer extends EntityTransformer diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php index dc4cfd85a3..8596bed1a6 100644 --- a/app/Transformers/UserTransformer.php +++ b/app/Transformers/UserTransformer.php @@ -98,6 +98,7 @@ class UserTransformer extends EntityTransformer { if (! $user->company_id && request()->header('X-API-TOKEN')) { $company_token = CompanyToken::where('token', request()->header('X-API-TOKEN'))->first(); + /** @var \App\Models\User $user */ $user->company_id = $company_token->company_id; } diff --git a/app/Utils/EmailStats.php b/app/Utils/EmailStats.php index ff55bb08b4..6af60ece2f 100644 --- a/app/Utils/EmailStats.php +++ b/app/Utils/EmailStats.php @@ -63,6 +63,7 @@ class EmailStats public static function clearCompanies($companies) { $companies->each(function ($company) { + /** @var \App\Models\Company $company */ self::clear($company->company_key); }); } diff --git a/app/Utils/PhantomJS/Phantom.php b/app/Utils/PhantomJS/Phantom.php index 7786c7194b..8080f5c669 100644 --- a/app/Utils/PhantomJS/Phantom.php +++ b/app/Utils/PhantomJS/Phantom.php @@ -44,6 +44,7 @@ class Phantom public function generate($invitation, $return_pdf = false) { $entity = false; + $path = ''; if ($invitation instanceof InvoiceInvitation) { $entity = 'invoice'; @@ -106,7 +107,7 @@ class Phantom } if (! Storage::disk(config('filesystems.default'))->exists($path)) { - Storage::disk(config('filesystems.default'))->makeDirectory($path, 0775); + Storage::disk(config('filesystems.default'))->makeDirectory($path); } $instance = Storage::disk(config('filesystems.default'))->put($file_path, $pdf); From 54b64fe6ad36660a9eb1b2ba031f238c53f63d50 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 20:47:05 +1000 Subject: [PATCH 25/33] Add in custom fields for exports --- app/Export/CSV/BaseExport.php | 10 +++++++++- app/Http/Middleware/ContactRegister.php | 3 +-- app/Http/Requests/ClientPortal/RegisterRequest.php | 3 +-- app/Http/Requests/Shop/StoreShopClientRequest.php | 4 ++-- app/Http/ValidationRules/ValidRefundableInvoices.php | 1 - app/Models/Payment.php | 2 +- 6 files changed, 14 insertions(+), 9 deletions(-) diff --git a/app/Export/CSV/BaseExport.php b/app/Export/CSV/BaseExport.php index cbaab0aa2d..9e5944ddf7 100644 --- a/app/Export/CSV/BaseExport.php +++ b/app/Export/CSV/BaseExport.php @@ -94,7 +94,6 @@ class BaseExport "state" => "client.state", "postal_code" => "client.postal_code", "country" => "client.country_id", - "custom_value4" => "contact.custom_value4", "shipping_address1" => "client.shipping_address1", "shipping_address2" => "client.shipping_address2", "shipping_city" => "client.shipping_city", @@ -109,6 +108,15 @@ class BaseExport "first_name" => "contact.first_name", "last_name" => "contact.last_name", "email" => "contact.email", + 'custom_value1' => 'client.custom_value1', + 'custom_value2' => 'client.custom_value2', + 'custom_value3' => 'client.custom_value3', + 'custom_value4' => 'client.custom_value4', + "contact_custom_value1" => "contact.custom_value1", + "contact_custom_value2" => "contact.custom_value2", + "contact_custom_value3" => "contact.custom_value3", + "contact_custom_value4" => "contact.custom_value4", + ]; protected array $invoice_report_keys = [ diff --git a/app/Http/Middleware/ContactRegister.php b/app/Http/Middleware/ContactRegister.php index a0356d6bbf..fa3f625701 100644 --- a/app/Http/Middleware/ContactRegister.php +++ b/app/Http/Middleware/ContactRegister.php @@ -79,8 +79,7 @@ class ContactRegister // As a fallback for self-hosted, it will use default company in the system // if key isn't provided in the url. if (! $request->route()->parameter('company_key') && Ninja::isSelfHost()) { - /** @var \App\Models\Company $company */ - $company = Account::first()->default_company; + $company = Account::query()->first()->default_company; if (! $company->client_can_register) { abort(400, 'Registration disabled'); diff --git a/app/Http/Requests/ClientPortal/RegisterRequest.php b/app/Http/Requests/ClientPortal/RegisterRequest.php index b395d54f98..c2c5e8ecfc 100644 --- a/app/Http/Requests/ClientPortal/RegisterRequest.php +++ b/app/Http/Requests/ClientPortal/RegisterRequest.php @@ -74,8 +74,7 @@ class RegisterRequest extends FormRequest } if (! $this->route()->parameter('company_key') && Ninja::isSelfHost()) { - /** @var \App\Models\Company $company */ - $company = Account::first()->default_company; + $company = Account::query()->first()->default_company; if (! $company->client_can_register) { abort(403, 'This page is restricted'); diff --git a/app/Http/Requests/Shop/StoreShopClientRequest.php b/app/Http/Requests/Shop/StoreShopClientRequest.php index dfbae8e456..beffeeac2f 100644 --- a/app/Http/Requests/Shop/StoreShopClientRequest.php +++ b/app/Http/Requests/Shop/StoreShopClientRequest.php @@ -74,7 +74,7 @@ class StoreShopClientRequest extends Request public function prepareForValidation() { - $this->company = Company::where('company_key', request()->header('X-API-COMPANY-KEY'))->firstOrFail(); + $this->company = Company::query()->where('company_key', request()->header('X-API-COMPANY-KEY'))->firstOrFail(); $input = $this->all(); @@ -93,7 +93,7 @@ class StoreShopClientRequest extends Request //is no settings->currency_id is set then lets dive in and find either a group or company currency all the below may be redundant!! if (! property_exists($settings, 'currency_id') && isset($input['group_settings_id'])) { $input['group_settings_id'] = $this->decodePrimaryKey($input['group_settings_id']); - $group_settings = GroupSetting::find($input['group_settings_id']); + $group_settings = GroupSetting::query()->find($input['group_settings_id']); if ($group_settings && property_exists($group_settings->settings, 'currency_id') && isset($group_settings->settings->currency_id)) { $settings->currency_id = (string) $group_settings->settings->currency_id; diff --git a/app/Http/ValidationRules/ValidRefundableInvoices.php b/app/Http/ValidationRules/ValidRefundableInvoices.php index 6867b04b1e..7b4abfce5e 100644 --- a/app/Http/ValidationRules/ValidRefundableInvoices.php +++ b/app/Http/ValidationRules/ValidRefundableInvoices.php @@ -72,7 +72,6 @@ class ValidRefundableInvoices implements Rule foreach ($this->input['invoices'] as $val) { if ($val['invoice_id'] == $invoice->id) { - /** @var \App\Models\Paymentable $pivot_record */ $pivot_record = $payment->paymentables->where('paymentable_id', $invoice->id)->first(); if ($val['amount'] > ($pivot_record->amount - $pivot_record->refunded)) { diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 3fc2bd5cb4..79f4cfa5a8 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -89,7 +89,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property-read \Illuminate\Database\Eloquent\Collection $credits * @property-read \Illuminate\Database\Eloquent\Collection $documents * @property-read \Illuminate\Database\Eloquent\Collection $invoices - * @property \Illuminate\Database\Eloquent\Collection $paymentables + * @property \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection $paymentables * @mixin \Eloquent */ class Payment extends BaseModel From e21b6f3a5552725c8d80d8ca73a6ca68c03ab87d Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 23:00:19 +1000 Subject: [PATCH 26/33] Fixes for payment activities --- app/Http/Requests/Company/ShowCompanyRequest.php | 5 ++++- app/Listeners/Invoice/InvoicePaidActivity.php | 1 + app/Policies/CompanyPolicy.php | 3 ++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/app/Http/Requests/Company/ShowCompanyRequest.php b/app/Http/Requests/Company/ShowCompanyRequest.php index 1f14d823fd..1eb1845e20 100644 --- a/app/Http/Requests/Company/ShowCompanyRequest.php +++ b/app/Http/Requests/Company/ShowCompanyRequest.php @@ -22,6 +22,9 @@ class ShowCompanyRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('view', $this->company); + /** @var \App\Models\User $user */ + $user = auth()->user(); + + return $user->company()->id == $this->company->id; } } diff --git a/app/Listeners/Invoice/InvoicePaidActivity.php b/app/Listeners/Invoice/InvoicePaidActivity.php index 13cb70222b..2d340dfb08 100644 --- a/app/Listeners/Invoice/InvoicePaidActivity.php +++ b/app/Listeners/Invoice/InvoicePaidActivity.php @@ -47,6 +47,7 @@ class InvoicePaidActivity implements ShouldQueue $fields->user_id = $user_id; $fields->invoice_id = $event->invoice->id; + $fields->client_id = $event->invoice->client_id; $fields->company_id = $event->invoice->company_id; $fields->activity_type_id = Activity::PAID_INVOICE; $fields->payment_id = $event->payment->id; diff --git a/app/Policies/CompanyPolicy.php b/app/Policies/CompanyPolicy.php index 53a3406b35..3249fe8bb8 100644 --- a/app/Policies/CompanyPolicy.php +++ b/app/Policies/CompanyPolicy.php @@ -43,7 +43,8 @@ class CompanyPolicy extends EntityPolicy return ($user->isAdmin() && $entity->id == $user->companyId()) || ($user->hasPermission('view_'.strtolower(class_basename($entity))) && $entity->id == $user->companyId()) // || ($user->hasPermission('view_all') && $entity->id == $user->companyId()) - || $user->owns($entity); + || $user->owns($entity) + || $user->companyId() == $entity->id; } /** From 03530b967feabb875f43a12ad6007bac9c38c8b1 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 23:04:08 +1000 Subject: [PATCH 27/33] Fixes for refunded payment activities --- app/Listeners/Activity/PaymentRefundedActivity.php | 1 - 1 file changed, 1 deletion(-) diff --git a/app/Listeners/Activity/PaymentRefundedActivity.php b/app/Listeners/Activity/PaymentRefundedActivity.php index d880673190..7cf9ca4d1e 100644 --- a/app/Listeners/Activity/PaymentRefundedActivity.php +++ b/app/Listeners/Activity/PaymentRefundedActivity.php @@ -45,7 +45,6 @@ class PaymentRefundedActivity implements ShouldQueue $user_id = array_key_exists('user_id', $event->event_vars) ? $event->event_vars['user_id'] : $event->payment->user_id; - $fields->client_id = $event->payment->id; $fields->client_id = $event->payment->client_id; $fields->user_id = $user_id; $fields->company_id = $event->payment->company_id; From 875e8dbadb8fa210a9dd142b8128e4c7dbca1ed1 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 23:08:29 +1000 Subject: [PATCH 28/33] Updates for tests --- tests/Feature/BaseApiTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Feature/BaseApiTest.php b/tests/Feature/BaseApiTest.php index 75d4ae7f24..e1b889e3a8 100644 --- a/tests/Feature/BaseApiTest.php +++ b/tests/Feature/BaseApiTest.php @@ -428,7 +428,7 @@ class BaseApiTest extends TestCase 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->low_token, ])->get('/api/v1/companies/'.$this->company->hashed_id) - ->assertStatus(403); + ->assertStatus(200); } From 3a215b448aa15e29a079f5dc6687663dd88e38bd Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 7 Aug 2023 23:20:01 +1000 Subject: [PATCH 29/33] Fixes for tests --- tests/Feature/BaseApiTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Feature/BaseApiTest.php b/tests/Feature/BaseApiTest.php index e1b889e3a8..3fac9d506d 100644 --- a/tests/Feature/BaseApiTest.php +++ b/tests/Feature/BaseApiTest.php @@ -571,7 +571,7 @@ class BaseApiTest extends TestCase 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->low_token, ])->get('/api/v1/companies/'.$this->company->hashed_id) - ->assertStatus(403); + ->assertStatus(200); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), From a122c6f3cca9517ab8b968d1cc110849dfce322e Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 8 Aug 2023 07:23:03 +1000 Subject: [PATCH 30/33] Update form parameter value for approve quotes --- .../views/portal/ninja2020/quotes/includes/actions.blade.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/views/portal/ninja2020/quotes/includes/actions.blade.php b/resources/views/portal/ninja2020/quotes/includes/actions.blade.php index c709f8a5b4..7fd7d41c10 100644 --- a/resources/views/portal/ninja2020/quotes/includes/actions.blade.php +++ b/resources/views/portal/ninja2020/quotes/includes/actions.blade.php @@ -29,7 +29,7 @@ @yield('quote-not-approved-right-side')
- + From c005f8b4acda522caab39622fca81ba0a82679ef Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 8 Aug 2023 09:32:21 +1000 Subject: [PATCH 31/33] updates for disabling gatways in groups --- app/Http/Livewire/BillingPortalPurchasev2.php | 2 +- app/Services/Client/PaymentMethod.php | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/app/Http/Livewire/BillingPortalPurchasev2.php b/app/Http/Livewire/BillingPortalPurchasev2.php index 1a6c1a8ba1..cd70adc27f 100644 --- a/app/Http/Livewire/BillingPortalPurchasev2.php +++ b/app/Http/Livewire/BillingPortalPurchasev2.php @@ -424,7 +424,7 @@ class BillingPortalPurchasev2 extends Component $client_repo = new ClientRepository(new ClientContactRepository()); $data = [ 'name' => '', - 'group_id' => $this->encodePrimaryKey($this->subscription->group_id), + 'group_settings_id' => $this->subscription->group_id, 'contacts' => [ ['email' => $this->email], ], diff --git a/app/Services/Client/PaymentMethod.php b/app/Services/Client/PaymentMethod.php index 7f7d6c4933..4c7d4517d4 100644 --- a/app/Services/Client/PaymentMethod.php +++ b/app/Services/Client/PaymentMethod.php @@ -64,6 +64,9 @@ class PaymentMethod if ($company_gateways || $company_gateways == '0') { $transformed_ids = $this->transformKeys(explode(',', $company_gateways)); + if($company_gateways == '0') + $transformed_ids = []; + $this->gateways = $this->client ->company ->company_gateways @@ -93,6 +96,11 @@ class PaymentMethod if ($company_gateways || $company_gateways == '0') { $transformed_ids = $this->transformKeys(explode(',', $company_gateways)); + if($company_gateways == '0') { + $transformed_ids = []; + } + + $this->gateways = $this->client ->company ->company_gateways From 47b6f8e3ad9f5191ed205fb7a85b6ff37b9fcfcc Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 8 Aug 2023 17:14:04 +1000 Subject: [PATCH 32/33] Fixes for group settings --- app/Http/Livewire/BillingPortalPurchasev2.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Livewire/BillingPortalPurchasev2.php b/app/Http/Livewire/BillingPortalPurchasev2.php index 1a6c1a8ba1..eb024667c4 100644 --- a/app/Http/Livewire/BillingPortalPurchasev2.php +++ b/app/Http/Livewire/BillingPortalPurchasev2.php @@ -424,7 +424,7 @@ class BillingPortalPurchasev2 extends Component $client_repo = new ClientRepository(new ClientContactRepository()); $data = [ 'name' => '', - 'group_id' => $this->encodePrimaryKey($this->subscription->group_id), + 'group_settings_id' => $this->encodePrimaryKey($this->subscription->group_id), 'contacts' => [ ['email' => $this->email], ], From 53ddb61cdb9aa2eb4df65137807124210fed22ba Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 8 Aug 2023 17:56:08 +1000 Subject: [PATCH 33/33] v5.6.27 --- VERSION.txt | 2 +- config/ninja.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/VERSION.txt b/VERSION.txt index 879aebbd77..1c67831475 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -5.6.26 \ No newline at end of file +5.6.27 \ No newline at end of file diff --git a/config/ninja.php b/config/ninja.php index e50a4db220..9224ceb0f9 100644 --- a/config/ninja.php +++ b/config/ninja.php @@ -15,8 +15,8 @@ return [ 'require_https' => env('REQUIRE_HTTPS', true), 'app_url' => rtrim(env('APP_URL', ''), '/'), 'app_domain' => env('APP_DOMAIN', 'invoicing.co'), - 'app_version' => env('APP_VERSION','5.6.26'), - 'app_tag' => env('APP_TAG','5.6.26'), + 'app_version' => env('APP_VERSION','5.6.27'), + 'app_tag' => env('APP_TAG','5.6.27'), 'minimum_client_version' => '5.0.16', 'terms_version' => '1.0.1', 'api_secret' => env('API_SECRET', ''),