diff --git a/VERSION.txt b/VERSION.txt index 879aebbd77dd..030ab30ddf86 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -5.6.26 \ No newline at end of file +5.6.28 \ No newline at end of file diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php index a793a593bf40..4f522262d093 100644 --- a/app/Console/Commands/CheckData.php +++ b/app/Console/Commands/CheckData.php @@ -185,6 +185,9 @@ class CheckData extends Command if ($cu->company && $cu->user) { (new CreateCompanyToken($cu->company, $cu->user, 'System'))->handle(); } + else { + // $cu->forceDelete(); + } } }); } diff --git a/app/DataMapper/Tax/AU/Rule.php b/app/DataMapper/Tax/AU/Rule.php index aa11658ae194..d6536e1a7177 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/Export/CSV/BaseExport.php b/app/Export/CSV/BaseExport.php index cbaab0aa2d9c..9e5944ddf747 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/Export/CSV/ProductSalesExport.php b/app/Export/CSV/ProductSalesExport.php index 72017220d501..f47acfa4dcfe 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(); @@ -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/Export/CSV/RecurringInvoiceExport.php b/app/Export/CSV/RecurringInvoiceExport.php index 6df397c64855..330f29695c83 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/Filters/QueryFilters.php b/app/Filters/QueryFilters.php index 1f8f1ce4208c..e58f88c8c388 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/Helpers/Invoice/InvoiceItemSumInclusive.php b/app/Helpers/Invoice/InvoiceItemSumInclusive.php index 9e792c0d714e..b2a4b40337e6 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; @@ -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 4c74e0961d1e..1a787113af54 100644 --- a/app/Helpers/Mail/GmailTransport.php +++ b/app/Helpers/Mail/GmailTransport.php @@ -33,6 +33,7 @@ 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 +53,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/Helpers/Mail/Office365MailTransport.php b/app/Helpers/Mail/Office365MailTransport.php index 246ebb025069..6a94139a76cb 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/Helpers/Subscription/SubscriptionCalculator.php b/app/Helpers/Subscription/SubscriptionCalculator.php index 99049bab3993..2c5cd39988ee 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 b61390e34742..51222f5ab43e 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-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/ClientPortal/ApplePayDomainController.php b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php index c4b016c647e5..ed1e174a9529 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 1f4da5d02434..88024a39a3be 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 cb6764c6a84d..f67ae6042705 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 996b8c2209c7..b57b2f0524ac 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; } @@ -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); @@ -181,7 +183,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(); @@ -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/Controllers/ClientPortal/PaymentController.php b/app/Http/Controllers/ClientPortal/PaymentController.php index d696c083de43..841a61a105aa 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 83c541452f98..6d3eb9c0335a 100644 --- a/app/Http/Controllers/ClientPortal/QuoteController.php +++ b/app/Http/Controllers/ClientPortal/QuoteController.php @@ -95,8 +95,9 @@ class QuoteController extends Controller /** @var \App\Models\ClientContact $client_contact **/ $client_contact = auth()->user(); - $data['quotes'] = Quote::whereIn('id', $ids) - ->whereClientId($client_contact->client->id) + $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]) @@ -195,10 +198,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/app/Http/Controllers/CreditController.php b/app/Http/Controllers/CreditController.php index fb48ea46cbe8..e502f7ba2979 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 0d65af5d84f1..70d4b1e8a1b4 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/EmailController.php b/app/Http/Controllers/EmailController.php index 055cbfcffe64..cc60c74b1f94 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/Controllers/PreviewPurchaseOrderController.php b/app/Http/Controllers/PreviewPurchaseOrderController.php index bdc90f3f8d28..8ef2da0d514f 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(); @@ -181,6 +181,7 @@ class PreviewPurchaseOrderController extends BaseController DB::connection(config('database.default'))->beginTransaction(); if ($request->has('entity_id')) { + /** @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/Http/Controllers/TaskController.php b/app/Http/Controllers/TaskController.php index 5deec8f6652b..c664a7a16829 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/DocumentController.php b/app/Http/Controllers/VendorPortal/DocumentController.php index 537326b29c45..e622106904e4 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 589c7d53dd58..775758dc893d 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 96190431d68c..6ee0d7fefe84 100644 --- a/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php +++ b/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php @@ -19,13 +19,17 @@ 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) { 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 d7a2a581e43a..e9046d970ef8 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 715eab092f9e..9a7fae37b9ca 100644 --- a/app/Http/Livewire/BillingPortalPurchase.php +++ b/app/Http/Livewire/BillingPortalPurchase.php @@ -64,9 +64,9 @@ class BillingPortalPurchase extends Component /** * Instance of subscription. * - * @var Subscription + * @var \App\Models\Subscription $subscription */ - public $subscription; + public Subscription $subscription; /** * Instance of client contact. @@ -78,7 +78,6 @@ class BillingPortalPurchase extends Component /** * Rules for validating the form. * - * @var \string[][] */ protected $rules = [ 'email' => ['required', 'email'], @@ -156,7 +155,7 @@ class BillingPortalPurchase extends Component public $request_data; /** - * @var string + * @var float */ public $price; @@ -187,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 2e1272e5e896..cd70adc27ff5 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; @@ -122,7 +122,7 @@ class BillingPortalPurchasev2 extends Component /** * Instance of company. * - * @var Company + * @var \App\Models\Company */ public $company; @@ -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; @@ -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], ], @@ -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/Http/Livewire/InvoicesTable.php b/app/Http/Livewire/InvoicesTable.php index 9a84f50870a9..80b43cdd0059 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 e8f67863936e..565d08b0daeb 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 f8777538673a..4027c8698c40 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 7ef0b68ea0bd..b61af24d2944 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(); @@ -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/app/Http/Middleware/ClientPortalEnabled.php b/app/Http/Middleware/ClientPortalEnabled.php index 57b63d02cebd..c26e8ed64e24 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 1cecef46a1cd..c91dbb7133ad 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 b45f1c465ca6..7867e572c7f5 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)) { @@ -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 60e48d8771c0..fa3f62570171 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) { @@ -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'); } @@ -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,7 +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()) { - $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/Middleware/PasswordProtection.php b/app/Http/Middleware/PasswordProtection.php index 6789ede23c6a..4450ec321079 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 ae7e93ca1169..352d96560cbc 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 f06e5bca4ccc..4260f0dbf2c2 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/Chart/ShowChartRequest.php b/app/Http/Requests/Chart/ShowChartRequest.php index 39517cd29db2..8aa72afb3876 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() @@ -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]; } diff --git a/app/Http/Requests/ClientPortal/RegisterRequest.php b/app/Http/Requests/ClientPortal/RegisterRequest.php index b1e4763075cc..c2c5e8ecfcea 100644 --- a/app/Http/Requests/ClientPortal/RegisterRequest.php +++ b/app/Http/Requests/ClientPortal/RegisterRequest.php @@ -66,15 +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()) { - $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/ClientPortal/StoreDocumentRequest.php b/app/Http/Requests/ClientPortal/StoreDocumentRequest.php index a0d1b66af612..3e9faa1f32a4 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/ShowCompanyRequest.php b/app/Http/Requests/Company/ShowCompanyRequest.php index 1f14d823fd34..1eb1845e20d9 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/Http/Requests/Company/StoreCompanyRequest.php b/app/Http/Requests/Company/StoreCompanyRequest.php index b9219f000dd2..70e116d60eea 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/Credit/StoreCreditRequest.php b/app/Http/Requests/Credit/StoreCreditRequest.php index 8616ab177bc0..052617dc2b89 100644 --- a/app/Http/Requests/Credit/StoreCreditRequest.php +++ b/app/Http/Requests/Credit/StoreCreditRequest.php @@ -31,7 +31,10 @@ class StoreCreditRequest extends Request */ public function authorize() { - return auth()->user()->can('create', Credit::class); + /** @var \App\Models\User $user */ + $user = auth()->user(); + + return $user->can('create', Credit::class); } /** @@ -55,10 +58,13 @@ class StoreCreditRequest extends Request $rules['file'] = $this->file_validation; } - $rules['client_id'] = 'required|exists:clients,id,company_id,'.auth()->user()->company()->id; + /** @var \App\Models\User $user */ + $user = auth()->user(); + + $rules['client_id'] = 'required|exists:clients,id,company_id,'.$user->company()->id; // $rules['number'] = new UniqueCreditNumberRule($this->all()); - $rules['number'] = ['nullable', Rule::unique('credits')->where('company_id', auth()->user()->company()->id)]; + $rules['number'] = ['nullable', Rule::unique('credits')->where('company_id', $user->company()->id)]; $rules['discount'] = 'sometimes|numeric'; $rules['is_amount_discount'] = ['boolean']; $rules['tax_rate1'] = 'bail|sometimes|numeric'; @@ -67,7 +73,7 @@ class StoreCreditRequest extends Request $rules['tax_name1'] = 'bail|sometimes|string|nullable'; $rules['tax_name2'] = 'bail|sometimes|string|nullable'; $rules['tax_name3'] = 'bail|sometimes|string|nullable'; - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; if ($this->invoice_id) { $rules['invoice_id'] = new ValidInvoiceCreditRule(); diff --git a/app/Http/Requests/Credit/UpdateCreditRequest.php b/app/Http/Requests/Credit/UpdateCreditRequest.php index a397d41a8862..bc439b83a407 100644 --- a/app/Http/Requests/Credit/UpdateCreditRequest.php +++ b/app/Http/Requests/Credit/UpdateCreditRequest.php @@ -30,7 +30,10 @@ class UpdateCreditRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('edit', $this->credit); + /** @var \App\Models\User $user */ + $user = auth()->user(); + + return $user->can('edit', $this->credit); } /** @@ -40,6 +43,9 @@ class UpdateCreditRequest extends Request */ public function rules() { + /** @var \App\Models\User $user */ + $user = auth()->user(); + $rules = []; if ($this->file('documents') && is_array($this->file('documents'))) { @@ -55,7 +61,7 @@ class UpdateCreditRequest extends Request } if ($this->number) { - $rules['number'] = Rule::unique('credits')->where('company_id', auth()->user()->company()->id)->ignore($this->credit->id); + $rules['number'] = Rule::unique('credits')->where('company_id', $user->company()->id)->ignore($this->credit->id); } $rules['line_items'] = 'array'; @@ -67,7 +73,7 @@ class UpdateCreditRequest extends Request $rules['tax_name1'] = 'bail|sometimes|string|nullable'; $rules['tax_name2'] = 'bail|sometimes|string|nullable'; $rules['tax_name3'] = 'bail|sometimes|string|nullable'; - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; return $rules; } diff --git a/app/Http/Requests/Invoice/StoreInvoiceRequest.php b/app/Http/Requests/Invoice/StoreInvoiceRequest.php index 37ff17758412..10ab3a1765db 100644 --- a/app/Http/Requests/Invoice/StoreInvoiceRequest.php +++ b/app/Http/Requests/Invoice/StoreInvoiceRequest.php @@ -72,7 +72,7 @@ class StoreInvoiceRequest extends Request $rules['tax_name1'] = 'bail|sometimes|string|nullable'; $rules['tax_name2'] = 'bail|sometimes|string|nullable'; $rules['tax_name3'] = 'bail|sometimes|string|nullable'; - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; return $rules; } diff --git a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php index db055d17c4cf..859924029a44 100644 --- a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php +++ b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php @@ -40,6 +40,9 @@ class UpdateInvoiceRequest extends Request public function rules() { + /** @var \App\Models\User $user */ + $user = auth()->user(); + $rules = []; if ($this->file('documents') && is_array($this->file('documents'))) { @@ -57,7 +60,7 @@ class UpdateInvoiceRequest extends Request $rules['id'] = new LockedInvoiceRule($this->invoice); if ($this->number) { - $rules['number'] = Rule::unique('invoices')->where('company_id', auth()->user()->company()->id)->ignore($this->invoice->id); + $rules['number'] = Rule::unique('invoices')->where('company_id', $user->company()->id)->ignore($this->invoice->id); } $rules['is_amount_discount'] = ['boolean']; @@ -72,10 +75,7 @@ class UpdateInvoiceRequest extends Request $rules['tax_name2'] = 'bail|sometimes|string|nullable'; $rules['tax_name3'] = 'bail|sometimes|string|nullable'; $rules['status_id'] = 'bail|sometimes|not_in:5'; //do not allow cancelled invoices to be modfified. - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; - - // not needed. - // $rules['partial_due_date'] = 'bail|sometimes|required_unless:partial,0,null'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; return $rules; } diff --git a/app/Http/Requests/Payments/PaymentWebhookRequest.php b/app/Http/Requests/Payments/PaymentWebhookRequest.php index f2e00d40dec3..8714f7ba80ac 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() @@ -52,7 +51,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/PurchaseOrder/StorePurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php index 71d8fe32de99..e08db93727a5 100644 --- a/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php @@ -29,7 +29,10 @@ class StorePurchaseOrderRequest extends Request */ public function authorize() { - return auth()->user()->can('create', PurchaseOrder::class); + /** @var \App\Models\User $user */ + $user = auth()->user(); + + return $user->can('create', PurchaseOrder::class); } /** * Get the validation rules that apply to the request. @@ -38,11 +41,14 @@ class StorePurchaseOrderRequest extends Request */ public function rules() { + /** @var \App\Models\User $user */ + $user = auth()->user(); + $rules = []; - $rules['vendor_id'] = 'bail|required|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + $rules['vendor_id'] = 'bail|required|exists:vendors,id,company_id,'.$user->company()->id.',is_deleted,0'; - $rules['number'] = ['nullable', Rule::unique('purchase_orders')->where('company_id', auth()->user()->company()->id)]; + $rules['number'] = ['nullable', Rule::unique('purchase_orders')->where('company_id', $user->company()->id)]; $rules['discount'] = 'sometimes|numeric'; $rules['is_amount_discount'] = ['boolean']; $rules['line_items'] = 'array'; @@ -60,7 +66,7 @@ class StorePurchaseOrderRequest extends Request } $rules['status_id'] = 'nullable|integer|in:1,2,3,4,5'; - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; return $rules; } diff --git a/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php index f772944ddd53..d9cb293abb74 100644 --- a/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/UpdatePurchaseOrderRequest.php @@ -63,7 +63,7 @@ class UpdatePurchaseOrderRequest extends Request } $rules['status_id'] = 'sometimes|integer|in:1,2,3,4,5'; - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; return $rules; } diff --git a/app/Http/Requests/Quote/StoreQuoteRequest.php b/app/Http/Requests/Quote/StoreQuoteRequest.php index 39e03dc37e33..af0cb96d0c89 100644 --- a/app/Http/Requests/Quote/StoreQuoteRequest.php +++ b/app/Http/Requests/Quote/StoreQuoteRequest.php @@ -30,14 +30,20 @@ class StoreQuoteRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', Quote::class); + /** @var \App\Models\User $user */ + $user = auth()->user(); + + return $user->can('create', Quote::class); } public function rules() { + /** @var \App\Models\User $user */ + $user = auth()->user(); + $rules = []; - $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; if ($this->file('documents') && is_array($this->file('documents'))) { $rules['documents.*'] = $this->file_validation; @@ -51,11 +57,11 @@ class StoreQuoteRequest extends Request $rules['file'] = $this->file_validation; } - $rules['number'] = ['nullable', Rule::unique('quotes')->where('company_id', auth()->user()->company()->id)]; + $rules['number'] = ['nullable', Rule::unique('quotes')->where('company_id', $user->company()->id)]; $rules['discount'] = 'sometimes|numeric'; $rules['is_amount_discount'] = ['boolean']; - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; // $rules['number'] = new UniqueQuoteNumberRule($this->all()); $rules['line_items'] = 'array'; diff --git a/app/Http/Requests/Quote/UpdateQuoteRequest.php b/app/Http/Requests/Quote/UpdateQuoteRequest.php index b692e82663d4..7723ac31cb77 100644 --- a/app/Http/Requests/Quote/UpdateQuoteRequest.php +++ b/app/Http/Requests/Quote/UpdateQuoteRequest.php @@ -57,7 +57,7 @@ class UpdateQuoteRequest extends Request $rules['line_items'] = 'array'; $rules['discount'] = 'sometimes|numeric'; $rules['is_amount_discount'] = ['boolean']; - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; return $rules; } diff --git a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php index 307ab9cffe5f..1ad00da30ce2 100644 --- a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php @@ -31,11 +31,18 @@ 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() { + /** @var \App\Models\User $user */ + $user = auth()->user(); + $rules = []; if ($this->file('documents') && is_array($this->file('documents'))) { @@ -50,7 +57,7 @@ class StoreRecurringInvoiceRequest 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'; @@ -67,7 +74,7 @@ class StoreRecurringInvoiceRequest extends Request $rules['tax_name2'] = 'bail|sometimes|string|nullable'; $rules['tax_name3'] = 'bail|sometimes|string|nullable'; $rules['due_date_days'] = 'bail|sometimes|string'; - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; return $rules; } @@ -137,7 +144,8 @@ class StoreRecurringInvoiceRequest extends Request if (isset($input['auto_bill'])) { $input['auto_bill_enabled'] = $this->setAutoBillFlag($input['auto_bill']); } else { - 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/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php index 8b9795a78cbf..9a3eca4f0397 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())]; @@ -61,7 +67,7 @@ class UpdateRecurringInvoiceRequest extends Request $rules['tax_name1'] = 'bail|sometimes|string|nullable'; $rules['tax_name2'] = 'bail|sometimes|string|nullable'; $rules['tax_name3'] = 'bail|sometimes|string|nullable'; - $rules['exchange_rate'] = 'bail|sometimes|gt:0'; + $rules['exchange_rate'] = 'bail|sometimes|numeric'; return $rules; } @@ -126,7 +132,7 @@ class UpdateRecurringInvoiceRequest extends Request unset($input['documents']); } - if (array_key_exists('exchange_rate', $input) && (is_null($input['exchange_rate']) || $input['exchange_rate'] == 0)) { + if (array_key_exists('exchange_rate', $input) && (is_null($input['exchange_rate']) || $input['exchange_rate'] == 0) || !isset($input['exchange_rate'])) { $input['exchange_rate'] = 1; } @@ -138,11 +144,11 @@ 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 */ - private function setAutoBillFlag($auto_bill) + private function setAutoBillFlag($auto_bill): bool { if ($auto_bill == 'always' || $auto_bill == 'optout') { return true; diff --git a/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php index 396341b9fcd0..75eec296559f 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/Shop/StoreShopClientRequest.php b/app/Http/Requests/Shop/StoreShopClientRequest.php index dfbae8e45633..beffeeac2f1d 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/Requests/Statements/CreateStatementRequest.php b/app/Http/Requests/Statements/CreateStatementRequest.php index a2ac1204dabd..3406be9468e5 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/Requests/VendorPortal/Documents/ShowDocumentRequest.php b/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php index 83e3357e1d62..dd1202d22a14 100644 --- a/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php +++ b/app/Http/Requests/VendorPortal/Documents/ShowDocumentRequest.php @@ -26,7 +26,9 @@ class ShowDocumentRequest extends FormRequest */ public function authorize() { - return auth()->guard('vendor')->user()->client_id == $this->document->documentable_id + + /** @var \App\Models\VendorContact auth()->guard('vendor')->user() */ + 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/Http/ValidationRules/Credit/UniqueCreditNumberRule.php b/app/Http/ValidationRules/Credit/UniqueCreditNumberRule.php index b869613defaa..0c2062948801 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 fa289f5e489f..215367fae4c7 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/Ninja/CanStoreClientsRule.php b/app/Http/ValidationRules/Ninja/CanStoreClientsRule.php index 6c1f49afb650..99e726254e04 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 $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/Http/ValidationRules/Payment/ValidRefundableRequest.php b/app/Http/ValidationRules/Payment/ValidRefundableRequest.php index db2f8ad2e1c5..44e4c53ae364 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 c10867372714..48acdf6ffde0 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 5eb1ef2b64cc..e87e4b97d9ff 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 278ac2164364..98951c70c95f 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/Http/ValidationRules/ValidCreditsPresentRule.php b/app/Http/ValidationRules/ValidCreditsPresentRule.php index 5b662da16a45..00979435e38c 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 a83eba85c61e..93503c7a36e5 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 5c3d57334ad5..7b4abfce5e54 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/Http/ValidationRules/ValidUserForCompany.php b/app/Http/ValidationRules/ValidUserForCompany.php index 3a724c78ece2..8a60cd275165 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 04780c6fc2ea..04ace061da52 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 string $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/Import/Providers/Wave.php b/app/Import/Providers/Wave.php index 9543c704a2e9..4b4c10adc1bb 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 ddc190b029ed..a979a85082e8 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 2c13bce53c53..faae4fffa2ae 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/Jobs/Bank/MatchBankTransactions.php b/app/Jobs/Bank/MatchBankTransactions.php index bc3c0fc3a2d1..518926734c99 100644 --- a/app/Jobs/Bank/MatchBankTransactions.php +++ b/app/Jobs/Bank/MatchBankTransactions.php @@ -47,10 +47,12 @@ class MatchBankTransactions implements ShouldQueue private array $input; + /** @var \App\Models\Company */ protected ?Company $company; public Invoice $invoice; + /** @var \App\Models\BankTransaction $bt */ private ?BankTransaction $bt; private $categories; @@ -83,7 +85,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); @@ -113,7 +115,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 @@ -193,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; @@ -243,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; @@ -286,7 +288,7 @@ class MatchBankTransactions implements ShouldQueue $this->available_balance = $amount; \DB::connection(config('database.default'))->transaction(function () use ($invoices) { - $invoices->each(function ($invoice) use ($invoices) { + $invoices->each(function ($invoice) { $this->invoice = Invoice::withTrashed()->where('id', $invoice->id)->lockForUpdate()->first(); $_amount = false; @@ -398,7 +400,7 @@ class MatchBankTransactions implements ShouldQueue $category = $this->categories->firstWhere('highLevelCategoryId', $this->bt->category_id); - $ec = ExpenseCategory::where('company_id', $this->bt->company_id)->where('bank_category_id', $this->bt->category_id)->first(); + $ec = ExpenseCategory::query()->where('company_id', $this->bt->company_id)->where('bank_category_id', $this->bt->category_id)->first(); if ($ec) { return $ec->id; diff --git a/app/Jobs/Bank/ProcessBankTransactions.php b/app/Jobs/Bank/ProcessBankTransactions.php index aeb309c50e7c..c5af8fd49a02 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 b41b4ed2ef4d..1a3bfc43b22b 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) { @@ -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); @@ -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/Company/CompanyImport.php b/app/Jobs/Company/CompanyImport.php index 7ec07abc616a..c1962bec02b1 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(); @@ -280,7 +280,7 @@ class CompanyImport implements ShouldQueue 'errors' => [] ]; - $_company = Company::find($this->company->id); + $_company = Company::query()->find($this->company->id); $nmo = new NinjaMailerObject; $nmo->mailable = new ImportCompleted($_company, $data); @@ -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 b649d6f7ee85..3b648bd7a2c7 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 f0e4343964b1..cf2c5f987f5b 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 6b1d31e7dae4..85dd0bed19d8 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/Cron/UpdateCalculatedFields.php b/app/Jobs/Cron/UpdateCalculatedFields.php index 62ace5ac7d70..98371260b07f 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() @@ -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/Jobs/Document/ZipDocuments.php b/app/Jobs/Document/ZipDocuments.php index c713e778e599..393aeec3bb80 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/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php index 266437cd777f..6fdf3d7f309e 100644 --- a/app/Jobs/Entity/CreateEntityPdf.php +++ b/app/Jobs/Entity/CreateEntityPdf.php @@ -48,19 +48,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 | null $entity; - public $company; + public \App\Models\Company | null $company; - public $contact; + public \App\Models\ClientContact | null $contact; private $disk; - public $invitation; + public \App\Models\InvoiceInvitation | \App\Models\QuoteInvitation | \App\Models\CreditInvitation | \App\Models\RecurringInvoiceInvitation | null $invitation; - public $entity_string = ''; + public string $entity_string = ''; - public $client; + public \App\Models\Client | null $client; public $deleteWhenMissingModels = true; @@ -136,6 +136,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/Entity/CreateRawPdf.php b/app/Jobs/Entity/CreateRawPdf.php index e4297068d40d..faced3f35ace 100644 --- a/app/Jobs/Entity/CreateRawPdf.php +++ b/app/Jobs/Entity/CreateRawPdf.php @@ -123,11 +123,11 @@ class CreateRawPdf implements ShouldQueue $entity_design_id = $this->entity->design_id ? $this->entity->design_id : $this->decodePrimaryKey($this->entity->client->getSetting($entity_design_id)); - $design = Design::withTrashed()->find($entity_design_id); + $design = Design::query()->withTrashed()->find($entity_design_id); /* Catch all in case migration doesn't pass back a valid design */ if (! $design) { - $design = Design::find(2); + $design = Design::query()->find(2); } $html = new HtmlEngine($this->invitation); diff --git a/app/Jobs/Inventory/AdjustProductInventory.php b/app/Jobs/Inventory/AdjustProductInventory.php index 8463a10ad7cc..8ee86b0cbda2 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; @@ -131,7 +131,7 @@ class AdjustProductInventory implements ShouldQueue collect($this->old_invoice)->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 89014305625d..6c9b903a8e07 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 441726583507..369b1563ff83 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/InjectSignature.php b/app/Jobs/Invoice/InjectSignature.php index db67ea2b223e..b296b43e6f6c 100644 --- a/app/Jobs/Invoice/InjectSignature.php +++ b/app/Jobs/Invoice/InjectSignature.php @@ -12,37 +12,17 @@ use Illuminate\Foundation\Bus\Dispatchable; class InjectSignature implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - - /** - * @var \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\PurchaseOrder - */ - public $entity; - - /** - * @var string - */ - public $signature; - - public $contact_id; - - public $ip; - + /** * Create a new job instance. * - * @param $entity + * @param \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\PurchaseOrder $entity + * @param int $contact_id * @param string $signature + * @param string $ip */ - public function __construct($entity, $contact_id, string $signature, ?string $ip) + public function __construct(public \App\Models\Invoice | \App\Models\Quote | \App\Models\Credit | \App\Models\PurchaseOrder $entity, private int $contact_id, private string $signature, private ?string $ip) { - $this->entity = $entity; - - $this->contact_id = $contact_id; - - $this->signature = $signature; - - $this->ip = $ip; - } /** diff --git a/app/Jobs/Invoice/InvoiceWorkflowSettings.php b/app/Jobs/Invoice/InvoiceWorkflowSettings.php index adb446fb4b0d..615b43ad925f 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/Ledger/ClientLedgerBalanceUpdate.php b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php index d3293116a6c1..29d780bfabb8 100644 --- a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php +++ b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php @@ -43,16 +43,16 @@ class ClientLedgerBalanceUpdate implements ShouldQueue MultiDB::setDb($this->company->db); - CompanyLedger::where('balance', 0)->where('client_id', $this->client->id)->orderBy('updated_at', 'ASC')->cursor()->each(function ($company_ledger) { + CompanyLedger::query()->where('balance', 0)->where('client_id', $this->client->id)->orderBy('updated_at', 'ASC')->cursor()->each(function ($company_ledger) { if ($company_ledger->balance == 0) { - $last_record = CompanyLedger::where('client_id', $company_ledger->client_id) + $last_record = CompanyLedger::query()->where('client_id', $company_ledger->client_id) ->where('company_id', $company_ledger->company_id) ->where('balance', '!=', 0) ->orderBy('id', 'DESC') ->first(); if (! $last_record) { - $last_record = CompanyLedger::where('client_id', $company_ledger->client_id) + $last_record = CompanyLedger::query()->where('client_id', $company_ledger->client_id) ->where('company_id', $company_ledger->company_id) ->orderBy('id', 'DESC') ->first(); diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php index 0e81d544f9be..ee38fbb77181 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 | null **/ public ?Company $company; private $mailer; @@ -83,7 +83,7 @@ class NinjaMailerJob implements ShouldQueue MultiDB::setDb($this->nmo->company->db); /* Serializing models from other jobs wipes the primary key */ - $this->company = Company::where('company_key', $this->nmo->company->company_key)->first(); + $this->company = Company::query()->where('company_key', $this->nmo->company->company_key)->first(); /* If any pre conditions fail, we return early here */ if (!$this->company || $this->preFlightChecksFail()) { @@ -552,7 +552,7 @@ class NinjaMailerJob implements ShouldQueue * Logs any errors to the SystemLog * * @param string $errors - * @param App\Models\User | App\Models\Client | null $recipient_object + * @param \App\Models\User | \App\Models\Client | null $recipient_object * @return void */ private function logMailError($errors, $recipient_object) :void diff --git a/app/Jobs/Mail/PaymentFailedMailer.php b/app/Jobs/Mail/PaymentFailedMailer.php index 12f3bc6f02b5..461b1a01c695 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/Jobs/Mail/PaymentFailureMailer.php b/app/Jobs/Mail/PaymentFailureMailer.php index 336c8009c101..2a0e256db0b3 100644 --- a/app/Jobs/Mail/PaymentFailureMailer.php +++ b/app/Jobs/Mail/PaymentFailureMailer.php @@ -84,7 +84,14 @@ class PaymentFailureMailer implements ShouldQueue if (($key = array_search('mail', $methods)) !== false) { unset($methods[$key]); - $mail_obj = (new PaymentFailureObject($this->client, $this->error, $this->company, $this->amount, null))->build(); + $use_react_link = false; + + if(isset($company_user->react_settings->react_notification_link) && $company_user->react_settings->react_notification_link) { + $use_react_link = true; + } + + + $mail_obj = (new PaymentFailureObject($this->client, $this->error, $this->company, $this->amount, null, $use_react_link))->build(); $nmo = new NinjaMailerObject; $nmo->mailable = new NinjaMailer($mail_obj); diff --git a/app/Jobs/PostMark/ProcessPostmarkWebhook.php b/app/Jobs/PostMark/ProcessPostmarkWebhook.php index c2497a3b5677..d99455ab322e 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 7405ed4ee1c6..bc9b5017d990 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/RecurringInvoice/UpdateRecurring.php b/app/Jobs/RecurringInvoice/UpdateRecurring.php index ee0527bcab83..b52ea17f2c83 100644 --- a/app/Jobs/RecurringInvoice/UpdateRecurring.php +++ b/app/Jobs/RecurringInvoice/UpdateRecurring.php @@ -42,7 +42,7 @@ class UpdateRecurring implements ShouldQueue $this->user->setCompany($this->company); - RecurringInvoice::where('company_id', $this->company->id) + RecurringInvoice::query()->where('company_id', $this->company->id) ->whereIn('id', $this->ids) ->chunk(100, function ($recurring_invoices) { foreach ($recurring_invoices as $recurring_invoice) { diff --git a/app/Jobs/User/UserEmailChanged.php b/app/Jobs/User/UserEmailChanged.php index b400684f052b..c397f1ae65dd 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 e28c77afb420..afeb33566db0 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 0d2e837983ed..175074cf221a 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)) { @@ -1482,7 +1483,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 +1494,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 +1510,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']; @@ -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']}"; @@ -1653,8 +1654,8 @@ class Import implements ShouldQueue $modified['company_gateway_id'] = $this->transformId('company_gateways', $resource['company_gateway_id']); //$modified['user_id'] = $this->processUserId($resource); - - $cgt = ClientGatewayToken::Create($modified); + /** @var \App\Models\ClientGatewayToken $cgt **/ + $cgt = ClientGatewayToken::create($modified); $key = "client_gateway_tokens_{$resource['id']}"; @@ -1683,7 +1684,8 @@ class Import implements ShouldQueue $modified['company_id'] = $this->company->id; $modified['user_id'] = $this->processUserId($resource); - $task_status = TaskStatus::Create($modified); + /** @var \App\Models\TaskStatus $task_status **/ + $task_status = TaskStatus::create($modified); $key = "task_statuses_{$resource['id']}"; @@ -1711,7 +1713,8 @@ class Import implements ShouldQueue $modified['company_id'] = $this->company->id; $modified['user_id'] = $this->processUserId($resource); - $expense_category = ExpenseCategory::Create($modified); + /** @var \App\Models\ExpenseCategory $expense_category **/ + $expense_category = ExpenseCategory::create($modified); $old_user_key = array_key_exists('user_id', $resource) ?? $this->user->id; @@ -1756,7 +1759,8 @@ class Import implements ShouldQueue $modified['status_id'] = $this->transformId('task_statuses', $resource['status_id']); } - $task = Task::Create($modified); + /** @var \App\Models\Task $task **/ + $task = Task::create($modified); if (array_key_exists('created_at', $modified)) { $task->created_at = Carbon::parse($modified['created_at']); @@ -1766,8 +1770,6 @@ class Import implements ShouldQueue $task->updated_at = Carbon::parse($modified['updated_at']); } - - $task->save(['timestamps' => false]); $old_user_key = array_key_exists('user_id', $resource) ?? $this->user->id; @@ -1801,7 +1803,8 @@ class Import implements ShouldQueue $modified['client_id'] = $this->transformId('clients', $resource['client_id']); } - $project = Project::Create($modified); + /** @var \App\Models\Project $project **/ + $project = Project::create($modified); $key = "projects_{$resource['id']}"; @@ -1870,6 +1873,7 @@ try { $modified['updated_at'] = $modified['created_at']; + /** @var \App\Models\Activity $act **/ $act = Activity::make($modified); $act->save(['timestamps' => false]); @@ -1920,7 +1924,8 @@ nlog("could not import activity: {$e->getMessage()}"); $modified['vendor_id'] = $this->transformId('vendors', $resource['vendor_id']); } - $expense = Expense::Create($modified); + /** @var \App\Models\Expense $expense **/ + $expense = Expense::create($modified); if (array_key_exists('created_at', $modified)) { $expense->created_at = Carbon::parse($modified['created_at']); @@ -1930,8 +1935,6 @@ nlog("could not import activity: {$e->getMessage()}"); $expense->updated_at = Carbon::parse($modified['updated_at']); } - - $expense->save(['timestamps' => false]); $old_user_key = array_key_exists('user_id', $resource) ?? $this->user->id; diff --git a/app/Jobs/Util/ImportStripeCustomers.php b/app/Jobs/Util/ImportStripeCustomers.php index 3a8422cbddd9..17a1c22dfc55 100644 --- a/app/Jobs/Util/ImportStripeCustomers.php +++ b/app/Jobs/Util/ImportStripeCustomers.php @@ -44,13 +44,13 @@ class ImportStripeCustomers implements ShouldQueue /** * Execute the job. * - * @return bool */ public function handle() { MultiDB::setDb($this->company->db); - $cgs = CompanyGateway::where('company_id', $this->company->id) + $cgs = CompanyGateway::query() + ->where('company_id', $this->company->id) ->where('is_deleted', 0) ->whereIn('gateway_key', $this->stripe_keys) ->get(); diff --git a/app/Jobs/Util/ReminderJob.php b/app/Jobs/Util/ReminderJob.php index 27a0f0632577..6c0521bfe361 100644 --- a/app/Jobs/Util/ReminderJob.php +++ b/app/Jobs/Util/ReminderJob.php @@ -159,7 +159,7 @@ class ReminderJob implements ShouldQueue } } - private function addFeeToNewInvoice(Invoice $over_due_invoice, string $reminder_template, array $fees): void + private function addFeeToNewInvoice(Invoice $over_due_invoice, string $reminder_template, array $fees) { $amount = $fees[0]; diff --git a/app/Jobs/Util/StripeUpdatePaymentMethods.php b/app/Jobs/Util/StripeUpdatePaymentMethods.php index b693a1c4a181..57f99ce9d9bb 100644 --- a/app/Jobs/Util/StripeUpdatePaymentMethods.php +++ b/app/Jobs/Util/StripeUpdatePaymentMethods.php @@ -42,13 +42,13 @@ class StripeUpdatePaymentMethods implements ShouldQueue /** * Execute the job. * - * @return bool */ public function handle() { MultiDB::setDb($this->company->db); - $cgs = CompanyGateway::where('company_id', $this->company->id) + $cgs = CompanyGateway::query() + ->where('company_id', $this->company->id) ->whereIn('gateway_key', $this->stripe_keys) ->get(); diff --git a/app/Jobs/Util/UploadFile.php b/app/Jobs/Util/UploadFile.php index d8a77385222c..43417f3529a1 100644 --- a/app/Jobs/Util/UploadFile.php +++ b/app/Jobs/Util/UploadFile.php @@ -51,6 +51,8 @@ class UploadFile implements ShouldQueue public $entity; + public $disk; + public function __construct($file, $type, $user, $company, $entity, $disk = null, $is_public = false) { $this->file = $file; diff --git a/app/Jobs/Util/VersionCheck.php b/app/Jobs/Util/VersionCheck.php index 6d40a3e7172f..fe4cf701607b 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/WebhookHandler.php b/app/Jobs/Util/WebhookHandler.php index fd5f5d228fb7..2deaedca3bb3 100644 --- a/app/Jobs/Util/WebhookHandler.php +++ b/app/Jobs/Util/WebhookHandler.php @@ -43,7 +43,6 @@ class WebhookHandler implements ShouldQueue /** * Execute the job. * - * @return bool */ public function handle() { @@ -54,7 +53,8 @@ class WebhookHandler implements ShouldQueue return true; } - Webhook::where('company_id', $this->company->id) + Webhook::query() + ->where('company_id', $this->company->id) ->where('event_id', $this->event_id) ->cursor() ->each(function ($subscription) { diff --git a/app/Jobs/Util/WebhookSingle.php b/app/Jobs/Util/WebhookSingle.php index 26f79e992250..c30fef90e5ca 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 607f78d0b97a..fe6029aa2042 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); } diff --git a/app/Libraries/OAuth/OAuth.php b/app/Libraries/OAuth/OAuth.php index 59582bad187f..ba92d70106e8 100644 --- a/app/Libraries/OAuth/OAuth.php +++ b/app/Libraries/OAuth/OAuth.php @@ -39,8 +39,12 @@ class OAuth const SOCIAL_APPLE = 8; + public $provider_instance; + + public $provider_id; + /** - * @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) @@ -87,6 +91,8 @@ class OAuth return 'microsoft'; case self::SOCIAL_APPLE: return 'apple'; + default: + return 'google'; } } @@ -109,6 +115,8 @@ class OAuth return self::SOCIAL_MICROSOFT; case 'apple': return self::SOCIAL_APPLE; + default: + return self::SOCIAL_GOOGLE; } } diff --git a/app/Listeners/Activity/PaymentRefundedActivity.php b/app/Listeners/Activity/PaymentRefundedActivity.php index d88067319023..7cf9ca4d1e86 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; diff --git a/app/Listeners/Invoice/InvoicePaidActivity.php b/app/Listeners/Invoice/InvoicePaidActivity.php index 13cb70222beb..2d340dfb08df 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/Mail/Admin/AutoBillingFailureObject.php b/app/Mail/Admin/AutoBillingFailureObject.php index d72d62eceafa..a937aecf25b9 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/DownloadBackup.php b/app/Mail/DownloadBackup.php index ffc89d21d000..d3daecacdadd 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/Mail/Engine/InvoiceEmailEngine.php b/app/Mail/Engine/InvoiceEmailEngine.php index debd20eaa6e6..79826b3a0345 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/Mail/MigrationCompleted.php b/app/Mail/MigrationCompleted.php index 9b62fb6fbab7..5890eecc25b5 100644 --- a/app/Mail/MigrationCompleted.php +++ b/app/Mail/MigrationCompleted.php @@ -38,7 +38,7 @@ class MigrationCompleted extends Mailable public function build() { MultiDB::setDb($this->db); - $this->company = Company::find($this->company_id); + $this->company = Company::query()->find($this->company_id); App::forgetInstance('translator'); $t = app('translator'); diff --git a/app/Models/Account.php b/app/Models/Account.php index 8af6bc7e4023..595661a4f514 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 2772e0d146f2..29dd6eb4300f 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 05fe216aa825..09f5571565df 100644 --- a/app/Models/BaseModel.php +++ b/app/Models/BaseModel.php @@ -35,34 +35,37 @@ 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 + * @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) * @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) + * @method static \Illuminate\Database\Eloquent\Builder|BaseModel without($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/Client.php b/app/Models/Client.php index fd85ef504d90..570e497ebc2d 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 @@ -79,50 +79,35 @@ 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() + * @method static \Illuminate\Database\Eloquent\Builder|Client find() + * @method static \Illuminate\Database\Eloquent\Builder|Client select() * @property string $payment_balance * @property mixed $tax_data * @property int $is_tax_exempt @@ -248,7 +233,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'); } @@ -258,17 +243,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(); } @@ -292,17 +277,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'); } @@ -367,7 +352,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'); } @@ -552,8 +537,8 @@ class Client extends BaseModel implements HasLocalePreference foreach ($pms as $pm) { if ($pm['gateway_type_id'] == GatewayType::CREDIT_CARD) { - /**@var \App\Models\CompanyGateway $cg */ - $cg = CompanyGateway::find($pm['company_gateway_id']); + + $cg = CompanyGateway::query()->find($pm['company_gateway_id']); if ($cg && ! property_exists($cg->fees_and_limits, strval(GatewayType::CREDIT_CARD))) { $fees_and_limits = $cg->fees_and_limits; @@ -576,7 +561,7 @@ class Client extends BaseModel implements HasLocalePreference foreach ($pms as $pm) { if ($pm['gateway_type_id'] == GatewayType::BACS) { - $cg = CompanyGateway::find($pm['company_gateway_id']); + $cg = CompanyGateway::query()->find($pm['company_gateway_id']); if ($cg && ! property_exists($cg->fees_and_limits, GatewayType::BACS)) { $fees_and_limits = $cg->fees_and_limits; @@ -602,7 +587,7 @@ class Client extends BaseModel implements HasLocalePreference if ($this->currency()->code == 'USD' && in_array(GatewayType::BANK_TRANSFER, array_column($pms, 'gateway_type_id'))) { foreach ($pms as $pm) { if ($pm['gateway_type_id'] == GatewayType::BANK_TRANSFER) { - $cg = CompanyGateway::find($pm['company_gateway_id']); + $cg = CompanyGateway::query()->find($pm['company_gateway_id']); if ($cg && ! property_exists($cg->fees_and_limits, GatewayType::BANK_TRANSFER)) { $fees_and_limits = $cg->fees_and_limits; @@ -621,7 +606,7 @@ class Client extends BaseModel implements HasLocalePreference if ($this->currency()->code == 'EUR' && (in_array(GatewayType::BANK_TRANSFER, array_column($pms, 'gateway_type_id')) || in_array(GatewayType::SEPA, array_column($pms, 'gateway_type_id')))) { foreach ($pms as $pm) { if ($pm['gateway_type_id'] == GatewayType::SEPA) { - $cg = CompanyGateway::find($pm['company_gateway_id']); + $cg = CompanyGateway::query()->find($pm['company_gateway_id']); if ($cg && $cg->fees_and_limits->{GatewayType::SEPA}->is_enabled) { return $cg; @@ -633,7 +618,7 @@ class Client extends BaseModel implements HasLocalePreference if (in_array(GatewayType::DIRECT_DEBIT, array_column($pms, 'gateway_type_id'))) { foreach ($pms as $pm) { if ($pm['gateway_type_id'] == GatewayType::DIRECT_DEBIT) { - $cg = CompanyGateway::find($pm['company_gateway_id']); + $cg = CompanyGateway::query()->find($pm['company_gateway_id']); if ($cg && $cg->fees_and_limits->{GatewayType::DIRECT_DEBIT}->is_enabled) { return $cg; diff --git a/app/Models/ClientContact.php b/app/Models/ClientContact.php index 0116d611b474..0ff98447c367 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 2b6950048d23..fd5ed8795b7b 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/Company.php b/app/Models/Company.php index d9285075983e..5fb8a4477791 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -67,6 +67,10 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; * @property bool $is_large * @property int $enable_shop_api * @property string $default_auto_bill + * @property string $custom_value1 + * @property string $custom_value2 + * @property string $custom_value3 + * @property string $custom_value4 * @property bool $mark_expenses_invoiceable * @property bool $mark_expenses_paid * @property bool $invoice_expense_documents @@ -199,6 +203,8 @@ 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) + * @method static \Illuminate\Database\Eloquent\Builder|Company find($query) * @property-read int|null $webhooks_count * @property int $calculate_taxes * @property mixed $tax_data @@ -439,7 +445,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 +455,10 @@ class Company extends BaseModel return $this->hasMany(ClientContact::class)->withTrashed(); } - public function users() + /** + * @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(); } @@ -508,7 +517,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/CompanyGateway.php b/app/Models/CompanyGateway.php index aeaca5d2ce39..446d3022c8fe 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 @@ -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() @@ -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 @@ -167,17 +167,17 @@ class CompanyGateway extends BaseModel ->take(50); } - public function company() + public function company(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Company::class); } - public function client_gateway_tokens() + public function client_gateway_tokens(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(ClientGatewayToken::class); } - public function gateway() + public function gateway(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Gateway::class, 'gateway_key', 'key'); } @@ -190,8 +190,8 @@ class CompanyGateway extends BaseModel /* This is the public entry point into the payment superclass */ public function driver(Client $client = null) { -// $class = static::driver_class(); -$class = self::driver_class(); + // $class = static::driver_class(); + $class = self::driver_class(); if (!$class) { return false; diff --git a/app/Models/CompanyUser.php b/app/Models/CompanyUser.php index c07e2ed6a78a..ba3306808f37 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/Invoice.php b/app/Models/Invoice.php index 018d8722e85f..f9903591b1c8 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); }) @@ -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/Payment.php b/app/Models/Payment.php index 091cf5711018..79f4cfa5a87e 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 @@ -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|\Illuminate\Support\Collection $paymentables * @mixin \Eloquent */ class Payment extends BaseModel @@ -182,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(); @@ -232,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); } @@ -273,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); } @@ -459,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/Models/PaymentHash.php b/app/Models/PaymentHash.php index 019ac21ac33a..9905feddab65 100644 --- a/app/Models/PaymentHash.php +++ b/app/Models/PaymentHash.php @@ -18,7 +18,7 @@ use Illuminate\Database\Eloquent\Model; * * @property int $id * @property string $hash - * @property string $fee_total + * @property float $fee_total * @property int|null $fee_invoice_id * @property mixed $data * @property int|null $payment_id @@ -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/Project.php b/app/Models/Project.php index d25bd23630c6..c2d09f250a11 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/Models/PurchaseOrder.php b/app/Models/PurchaseOrder.php index e634636acda0..932d2ba9b935 100644 --- a/app/Models/PurchaseOrder.php +++ b/app/Models/PurchaseOrder.php @@ -50,12 +50,12 @@ use Illuminate\Support\Facades\Storage; * @property string|null $private_notes * @property string|null $terms * @property string|null $tax_name1 - * @property string $tax_rate1 + * @property float $tax_rate1 * @property string|null $tax_name2 - * @property string $tax_rate2 + * @property float $tax_rate2 * @property string|null $tax_name3 - * @property string $tax_rate3 - * @property string $total_taxes + * @property float $tax_rate3 + * @property float $total_taxes * @property int $uses_inclusive_taxes * @property string|null $reminder1_sent * @property string|null $reminder2_sent @@ -74,11 +74,11 @@ use Illuminate\Support\Facades\Storage; * @property int $custom_surcharge_tax2 * @property int $custom_surcharge_tax3 * @property int $custom_surcharge_tax4 - * @property string $exchange_rate - * @property string $balance + * @property float $exchange_rate + * @property float $balance * @property float|null $partial - * @property string $amount - * @property string $paid_to_date + * @property float $amount + * @property float $paid_to_date * @property string|null $partial_due_date * @property string|null $last_viewed * @property int|null $deleted_at @@ -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() @@ -122,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 @@ -378,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; + } + } diff --git a/app/Models/Quote.php b/app/Models/Quote.php index da496f7d63dd..38a3443460da 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/Subscription.php b/app/Models/Subscription.php index 3798a69433a8..59fb9e87ad94 100644 --- a/app/Models/Subscription.php +++ b/app/Models/Subscription.php @@ -47,8 +47,8 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property string|null $recurring_product_ids * @property string $name * @property int|null $group_id - * @property string $price - * @property string $promo_price + * @property float $price + * @property float $promo_price * @property int $registration_required * @property int $use_inventory_management * @property string|null $optional_product_ids @@ -57,7 +57,6 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property-read mixed $hashed_id * @property-read \App\Models\GroupSetting|null $group_settings * @property-read \App\Models\User $user - * @method static \Illuminate\Database\Eloquent\Builder|BaseModel company() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel exclude($columns) * @method static \Database\Factories\SubscriptionFactory factory($count = null, $state = []) * @method static \Illuminate\Database\Eloquent\Builder|Subscription filter(\App\Filters\QueryFilters $filters) @@ -68,6 +67,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @method static \Illuminate\Database\Eloquent\Builder|BaseModel scope() * @method static \Illuminate\Database\Eloquent\Builder|Subscription withTrashed() * @method static \Illuminate\Database\Eloquent\Builder|Subscription withoutTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Subscription with($value) * @mixin \Eloquent */ class Subscription extends BaseModel diff --git a/app/Models/TaxRate.php b/app/Models/TaxRate.php index 6caab9a18564..9ae870fcf508 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 diff --git a/app/Models/Traits/Excludable.php b/app/Models/Traits/Excludable.php index 272c5e7cc8c4..e31011793648 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(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 @@ -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 db2f87506444..4e9a2864d69b 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() @@ -280,7 +279,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/Models/Webhook.php b/app/Models/Webhook.php index 5a921eb1d8f2..22e87e833966 100644 --- a/app/Models/Webhook.php +++ b/app/Models/Webhook.php @@ -31,7 +31,6 @@ use Illuminate\Database\Eloquent\SoftDeletes; * @property-read \App\Models\Company|null $company * @property-read mixed $hashed_id * @property-read \App\Models\User|null $user - * @method static \Illuminate\Database\Eloquent\Builder|BaseModel company() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel exclude($columns) * @method static \Illuminate\Database\Eloquent\Builder|Webhook filter(\App\Filters\QueryFilters $filters) * @method static \Illuminate\Database\Eloquent\Builder|Webhook newModelQuery() diff --git a/app/Observers/CompanyGatewayObserver.php b/app/Observers/CompanyGatewayObserver.php index bc40e9fb0232..572c45af2ebd 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/PaymentDrivers/Authorize/AuthorizeTransaction.php b/app/PaymentDrivers/Authorize/AuthorizeTransaction.php index 7f4511a186a8..20f184a17fe2 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 65fcb33590fd..ca032fbedd81 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 632c8c36e137..43290710a70d 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -56,7 +56,11 @@ class BaseDriver extends AbstractPaymentDriver /* The Invitation */ public $invitation; - /* The client */ + /** + * The Client + * + * @var \App\Models\Client|null $client + */ public $client; /* Gateway capabilities */ @@ -279,7 +283,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 +396,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 +414,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 +526,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 +571,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 b9c2db92b3ca..a92ae417f7a6 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/CheckoutCom/CheckoutSetupWebhook.php b/app/PaymentDrivers/CheckoutCom/CheckoutSetupWebhook.php index f9dcc30dcacc..d35d07bd22ed 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/CheckoutComPaymentDriver.php b/app/PaymentDrivers/CheckoutComPaymentDriver.php index 7c65fadc8508..bfeee03569d9 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 9819a08b4fc8..2f1c5f6a0bff 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 94328a537e5c..48274891e818 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 4ea488618282..458b34d9e225 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 2a251a5b5822..c798c5c1e989 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 247c6988713d..cc263acfcf0d 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 bb2e9f6fef1e..cdae15876a2e 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/PaymentDrivers/Stripe/ACH.php b/app/PaymentDrivers/Stripe/ACH.php index b68d4e120ed8..d223fc9aa948 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/PaymentDrivers/Stripe/Jobs/PaymentIntentPartiallyFundedWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentPartiallyFundedWebhook.php index d30fa0695581..13e1afa3b380 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentPartiallyFundedWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentPartiallyFundedWebhook.php @@ -39,7 +39,7 @@ class PaymentIntentPartiallyFundedWebhook implements ShouldQueue { MultiDB::findAndSetDbByCompanyKey($this->company_key); - $company = Company::where('company_key', $this->company_key)->first(); + $company = Company::query()->where('company_key', $this->company_key)->first(); foreach ($this->stripe_request as $transaction) { $payment_intent = false; @@ -65,7 +65,7 @@ class PaymentIntentPartiallyFundedWebhook implements ShouldQueue nlog("paymentintent found but no payment"); } - $company_gateway = CompanyGateway::find($this->company_gateway_id); + $company_gateway = CompanyGateway::query()->find($this->company_gateway_id); $stripe_driver = $company_gateway->driver()->init(); $hash = isset($transaction['metadata']['payment_hash']) ? $transaction['metadata']['payment_hash'] : false; diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php index ed34fdf9402b..830ec346f6af 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php @@ -57,17 +57,15 @@ class PaymentIntentProcessingWebhook implements ShouldQueue { MultiDB::findAndSetDbByCompanyKey($this->company_key); - $company = Company::where('company_key', $this->company_key)->first(); + $company = Company::query()->where('company_key', $this->company_key)->first(); foreach ($this->stripe_request as $transaction) { if (array_key_exists('payment_intent', $transaction)) { - /** @var \App\Models\Payment $payment **/ $payment = Payment::query() ->where('company_id', $company->id) ->where('transaction_reference', $transaction['payment_intent']) ->first(); } else { - /** @var \App\Models\Payment $payment **/ $payment = Payment::query() ->where('company_id', $company->id) ->where('transaction_reference', $transaction['id']) @@ -97,8 +95,7 @@ class PaymentIntentProcessingWebhook implements ShouldQueue if ($this->payment_completed) { return; } - /** @var \App\Models\CompanyGateway $company_gateway **/ - $company_gateway = CompanyGateway::find($this->company_gateway_id); + $company_gateway = CompanyGateway::query()->find($this->company_gateway_id); $stripe_driver = $company_gateway->driver()->init(); $charge_id = false; @@ -126,10 +123,8 @@ class PaymentIntentProcessingWebhook implements ShouldQueue return; } - /** @var \App\Models\Company $company **/ - $company = Company::where('company_key', $this->company_key)->first(); + $company = Company::query()->where('company_key', $this->company_key)->first(); - /** @var \App\Models\Payment $payment **/ $payment = Payment::query() ->where('company_id', $company->id) ->where('transaction_reference', $charge['id']) @@ -189,7 +184,7 @@ class PaymentIntentProcessingWebhook implements ShouldQueue private function updateAchPayment($payment_hash, $client, $meta) { - $company_gateway = CompanyGateway::find($this->company_gateway_id); + $company_gateway = CompanyGateway::query()->find($this->company_gateway_id); $payment_method_type = $meta['gateway_type_id']; $driver = $company_gateway->driver($client)->init()->setPaymentMethod($payment_method_type); diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php index b476db2fea87..cea63f8d2b5b 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php @@ -56,7 +56,7 @@ class PaymentIntentWebhook implements ShouldQueue { MultiDB::findAndSetDbByCompanyKey($this->company_key); - $company = Company::where('company_key', $this->company_key)->first(); + $company = Company::query()->where('company_key', $this->company_key)->first(); foreach ($this->stripe_request as $transaction) { if (array_key_exists('payment_intent', $transaction)) { @@ -84,7 +84,7 @@ class PaymentIntentWebhook implements ShouldQueue return; } - $company_gateway = CompanyGateway::find($this->company_gateway_id); + $company_gateway = CompanyGateway::query()->find($this->company_gateway_id); $stripe_driver = $company_gateway->driver()->init(); $charge_id = false; @@ -196,7 +196,7 @@ class PaymentIntentWebhook implements ShouldQueue private function updateAchPayment($payment_hash, $client, $meta) { - $company_gateway = CompanyGateway::find($this->company_gateway_id); + $company_gateway = CompanyGateway::query()->find($this->company_gateway_id); $payment_method_type = $meta['gateway_type_id']; $driver = $company_gateway->driver($client)->init()->setPaymentMethod($payment_method_type); @@ -267,7 +267,7 @@ class PaymentIntentWebhook implements ShouldQueue private function updateCreditCardPayment($payment_hash, $client, $meta) { - $company_gateway = CompanyGateway::find($this->company_gateway_id); + $company_gateway = CompanyGateway::query()->find($this->company_gateway_id); $payment_method_type = $meta['gateway_type_id']; $driver = $company_gateway->driver($client)->init()->setPaymentMethod($payment_method_type); diff --git a/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php b/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php index a06daa855b50..8cbaaf95757c 100644 --- a/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php +++ b/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php @@ -90,7 +90,7 @@ class UpdatePaymentMethods ); foreach ($bank_methods->data as $method) { - $token = ClientGatewayToken::where([ + $token = ClientGatewayToken::query()->where([ 'gateway_customer_reference' => $customer->id, 'token' => $method->id, 'client_id' => $client->id, @@ -140,7 +140,7 @@ class UpdatePaymentMethods } foreach ($sources->data as $method) { - $token_exists = ClientGatewayToken::where([ + $token_exists = ClientGatewayToken::query()->where([ 'gateway_customer_reference' => $customer->id, 'token' => $method->id, 'client_id' => $client->id, @@ -176,7 +176,7 @@ class UpdatePaymentMethods private function addOrUpdateCard(PaymentMethod $method, $customer_reference, Client $client, $type_id) { - $token_exists = ClientGatewayToken::where([ + $token_exists = ClientGatewayToken::query()->where([ 'gateway_customer_reference' => $customer_reference, 'token' => $method->id, 'client_id' => $client->id, diff --git a/app/PaymentDrivers/StripePaymentDriver.php b/app/PaymentDrivers/StripePaymentDriver.php index 70c2f009730a..a80c09789dcd 100644 --- a/app/PaymentDrivers/StripePaymentDriver.php +++ b/app/PaymentDrivers/StripePaymentDriver.php @@ -501,7 +501,8 @@ class StripePaymentDriver extends BaseDriver $this->init(); - $client_gateway_token = ClientGatewayToken::whereClientId($this->client->id) + $client_gateway_token = ClientGatewayToken::query() + ->whereClientId($this->client->id) ->whereCompanyGatewayId($this->company_gateway->id) ->first(); @@ -890,9 +891,11 @@ class StripePaymentDriver extends BaseDriver return Account::all(); } - public function setClientFromCustomer($customer) + public function setClientFromCustomer($customer): self { - $this->client = ClientGatewayToken::where('gateway_customer_reference', $customer)->client; + $this->client = ClientGatewayToken::query()->where('gateway_customer_reference', $customer)->first()->client; + + return $this; } /** diff --git a/app/PaymentDrivers/WePay/ACH.php b/app/PaymentDrivers/WePay/ACH.php index 7143bda330a0..945924ffc341 100644 --- a/app/PaymentDrivers/WePay/ACH.php +++ b/app/PaymentDrivers/WePay/ACH.php @@ -201,7 +201,7 @@ class ACH public function paymentResponse($request) { - $token = ClientGatewayToken::find($this->decodePrimaryKey($request->input('source'))); + $token = ClientGatewayToken::query()->find($this->decodePrimaryKey($request->input('source'))); $token_meta = $token->meta; if (! property_exists($token_meta, 'state') || $token_meta->state != 'authorized') { diff --git a/app/Policies/CompanyPolicy.php b/app/Policies/CompanyPolicy.php index 53a3406b3555..3249fe8bb8f7 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; } /** diff --git a/app/Repositories/ActivityRepository.php b/app/Repositories/ActivityRepository.php index 129436d875e7..adafdfb2ca89 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/BankTransactionRepository.php b/app/Repositories/BankTransactionRepository.php index 4130e72333e0..e16ba4f0fd5d 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/BaseRepository.php b/app/Repositories/BaseRepository.php index 13df4b4d8435..b2c5aaad97d2 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 f5097e8f9adf..79d83c36be67 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 c7347da552b0..f3d4a4e6d481 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 40725e62020e..05b4dafc20aa 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 = []; @@ -136,7 +136,7 @@ class InvoiceMigrationRepository extends BaseRepository $state['finished_amount'] = $model->amount; - $model = $model->service()->applyNumber()->save(); + $model = $model->service()->applyNumber()->setReminder()->save(); if ($class->name == Invoice::class || $class->name == RecurringInvoice::class) { if (($state['finished_amount'] != $state['starting_amount']) && ($model->status_id != Invoice::STATUS_DRAFT)) { diff --git a/app/Repositories/Migration/PaymentMigrationRepository.php b/app/Repositories/Migration/PaymentMigrationRepository.php index 00bf928ae367..f8f6f686b799 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); @@ -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 4400e66155ef..f11a6f3cebd6 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) { @@ -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/Repositories/PurchaseOrderRepository.php b/app/Repositories/PurchaseOrderRepository.php index 321b4fa89891..71bd54a5b9e8 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 3d71199a55db..6a90b0c74d07 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 faf650ef2203..34a1f8e63642 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 ce870fe557f1..287d2d156a16 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(); @@ -137,7 +137,7 @@ class UserRepository extends BaseRepository $cu->forceDelete(); } - event(new UserWasDeleted($user, auth()->user(), $company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); + event(new UserWasDeleted($user, auth()->user(), auth()->user()->company(), Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); $user->delete(); @@ -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 df013e77cc29..30eb58943e1a 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 1fc3a77ba946..42b1027a8501 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 9daaacb6b161..f5dd8a9f9ab7 100644 --- a/app/Services/Bank/ProcessBankRules.php +++ b/app/Services/Bank/ProcessBankRules.php @@ -33,6 +33,9 @@ class ProcessBankRules extends AbstractService protected $invoices; + /** + * @param \App\Models\BankTransaction $bank_transaction + */ public function __construct(public BankTransaction $bank_transaction) { } @@ -48,14 +51,12 @@ 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(); $invoice = $this->invoices->first(function ($value, $key) { - /** @var \App\Models\Invoice $value */ return str_contains($this->bank_transaction->description, $value->number); }); @@ -153,7 +154,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 6e22782a298f..81cd527c615f 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) { @@ -166,7 +166,6 @@ class ClientService * * @param mixed $pdf The pdf blob * @param array $options The statement options array - * @return void */ private function emailStatement($pdf, array $options): void { diff --git a/app/Services/Client/Merge.php b/app/Services/Client/Merge.php index a2f830a1bb8a..6dc11c342c3f 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/Client/PaymentMethod.php b/app/Services/Client/PaymentMethod.php index 7f7d6c4933bc..aa535e916a4e 100644 --- a/app/Services/Client/PaymentMethod.php +++ b/app/Services/Client/PaymentMethod.php @@ -25,6 +25,7 @@ class PaymentMethod private $amount; + /** @var \Illuminate\Support\Collection $gateways **/ private $gateways; private $payment_methods; @@ -64,6 +65,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 @@ -75,7 +79,8 @@ class PaymentMethod return array_search($model->id, $transformed_ids); // this closure sorts for us }); } else { - $this->gateways = CompanyGateway::with('gateway') + $this->gateways = CompanyGateway::query() + ->with('gateway') ->where('company_id', $this->client->company_id) ->where('gateway_key', '!=', '54faab2ab6e3223dbe848b1686490baa') ->whereNull('deleted_at') @@ -93,6 +98,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 @@ -104,7 +114,8 @@ class PaymentMethod return array_search($model->id, $transformed_ids); // this closure sorts for us }); } else { - $this->gateways = CompanyGateway::with('gateway') + $this->gateways = CompanyGateway::query() + ->with('gateway') ->where('company_id', $this->client->company_id) ->where('gateway_key', '54faab2ab6e3223dbe848b1686490baa') ->whereNull('deleted_at') @@ -163,7 +174,7 @@ class PaymentMethod { foreach ($this->payment_methods as $key => $child_array) { foreach ($child_array as $gateway_id => $gateway_type_id) { - $gateway = CompanyGateway::find($gateway_id); + $gateway = CompanyGateway::query()->find($gateway_id); $fee_label = $gateway->calcGatewayFeeLabel($this->amount, $this->client, $gateway_type_id); diff --git a/app/Services/ClientPortal/InstantPayment.php b/app/Services/ClientPortal/InstantPayment.php index c9366ad83b46..909e4f003a3d 100644 --- a/app/Services/ClientPortal/InstantPayment.php +++ b/app/Services/ClientPortal/InstantPayment.php @@ -52,7 +52,7 @@ class InstantPayment $is_credit_payment = true; } - $gateway = CompanyGateway::find($this->request->input('company_gateway_id')); + $gateway = CompanyGateway::query()->find($this->request->input('company_gateway_id')); /** * find invoices @@ -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() @@ -100,7 +100,7 @@ class InstantPayment * Determine the payable amount and the max payable. ie either partial or invoice balance */ - $payable_amount = Number::roundValue(Number::parseFloat($payable_invoice['amount'], $client->currency()->precision)); + $payable_amount = Number::roundValue(Number::parseFloat($payable_invoice['amount']), $client->currency()->precision); $invoice_balance = Number::roundValue(($invoice->partial > 0 ? $invoice->partial : $invoice->balance), $client->currency()->precision); @@ -155,7 +155,7 @@ class InstantPayment return $payable_invoice['invoice_id'] == $inv->hashed_id; }); - $payable_amount = Number::roundValue(Number::parseFloat($payable_invoice['amount'], $client->currency()->precision)); + $payable_amount = Number::roundValue(Number::parseFloat($payable_invoice['amount']), $client->currency()->precision); $invoice_balance = Number::roundValue($invoice->balance, $client->currency()->precision); $payable_invoice['due_date'] = $this->formatDate($invoice->due_date, $invoice->client->date_format()); @@ -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; } @@ -273,7 +273,7 @@ class InstantPayment 'is_recurring' => $this->request->is_recurring, ]; - if ($is_credit_payment || $totals <= 0) { + if ($is_credit_payment) { return $this->processCreditPayment($this->request, $data); } diff --git a/app/Services/Credit/CreateInvitations.php b/app/Services/Credit/CreateInvitations.php index b00a177e2044..449a6ac6ff62 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() @@ -65,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/Credit/SendEmail.php b/app/Services/Credit/SendEmail.php index 1f01f6ba67f1..40ce3240f438 100644 --- a/app/Services/Credit/SendEmail.php +++ b/app/Services/Credit/SendEmail.php @@ -33,7 +33,6 @@ class SendEmail /** * Builds the correct template to send. - * @return void */ public function run() { diff --git a/app/Services/Email/EmailDefaults.php b/app/Services/Email/EmailDefaults.php index 65a104b88fdc..a374ddfa353c 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 d25ae3b3654d..399b0629e90b 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/AutoBillInvoice.php b/app/Services/Invoice/AutoBillInvoice.php index c05aecf18ba4..0585f888bd66 100644 --- a/app/Services/Invoice/AutoBillInvoice.php +++ b/app/Services/Invoice/AutoBillInvoice.php @@ -194,7 +194,7 @@ class AutoBillInvoice extends AbstractService $current_credit = false; foreach ($this->used_credit as $credit) { - $current_credit = Credit::find($credit['credit_id']); + $current_credit = Credit::query()->find($credit['credit_id']); $payment->credits() ->attach($current_credit->id, ['amount' => $credit['amount']]); @@ -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 5261df58f1b3..853090f5d166 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/EInvoice/FacturaEInvoice.php b/app/Services/Invoice/EInvoice/FacturaEInvoice.php index 7d109e21a618..9f97da9e4519 100644 --- a/app/Services/Invoice/EInvoice/FacturaEInvoice.php +++ b/app/Services/Invoice/EInvoice/FacturaEInvoice.php @@ -302,6 +302,7 @@ class FacturaEInvoice extends AbstractService private function resolvePaymentMethod(\App\Models\Payment $payment): array { $data = []; + $method = FacturaePayment::TYPE_CARD; match($payment->type_id){ PaymentType::BANK_TRANSFER => $method = FacturaePayment::TYPE_TRANSFER , @@ -482,8 +483,8 @@ class FacturaEInvoice extends AbstractService "fax" => "", "website" => substr($company->settings->website, 0, 50), "contactPeople" => substr($company->owner()->present()->name(), 0, 40), - "firstName" => $company->owner()->present()->firstName(), - "lastName" => $company->owner()->present()->lastName(), + "firstSurname" => $company->owner()->present()->firstName(), + "lastSurname" => $company->owner()->present()->lastName(), // 'centres' => $this->setFace(), // "cnoCnae" => "04647", // Clasif. Nacional de Act. Económicas // "ineTownCode" => "280796" // Cód. de municipio del INE diff --git a/app/Services/Invoice/HandleRestore.php b/app/Services/Invoice/HandleRestore.php index d5bf6c8275ba..de3a990baad2 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 58d566e51ce0..2b1410950e12 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/Invoice/InvoiceService.php b/app/Services/Invoice/InvoiceService.php index 2e167561f7c6..d350d28a597c 100644 --- a/app/Services/Invoice/InvoiceService.php +++ b/app/Services/Invoice/InvoiceService.php @@ -544,8 +544,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/DeletePayment.php b/app/Services/Payment/DeletePayment.php index 6c99757ea25e..27119ec5ca12 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/Payment/RefundPayment.php b/app/Services/Payment/RefundPayment.php index 15952fe8733c..fe56ef089145 100644 --- a/app/Services/Payment/RefundPayment.php +++ b/app/Services/Payment/RefundPayment.php @@ -238,7 +238,8 @@ class RefundPayment private function adjustInvoices() { if (isset($this->refund_data['invoices']) && count($this->refund_data['invoices']) > 0) { - foreach ($this->refund_data['invoices'] as $refunded_invoice) { + foreach ($this->refund_data['invoices'] as $refunded_invoice) + { $invoice = Invoice::withTrashed()->find($refunded_invoice['invoice_id']); if ($invoice->trashed()) { @@ -265,10 +266,10 @@ class RefundPayment $invoice->saveQuietly(); - //06-09-2022 + //08-08-2023 $client = $invoice->client ->service() - ->updateBalance($refunded_invoice['amount']) + ->updateBalanceAndPaidToDate($refunded_invoice['amount'], -1 * $refunded_invoice['amount']) ->save(); if ($invoice->is_deleted) { @@ -276,13 +277,6 @@ class RefundPayment } } - $client = $this->payment->client->fresh(); - - if ($client->trashed()) { - $client->restore(); - } - - $client->service()->updatePaidToDate(-1 * $refunded_invoice['amount'])->save(); } else { //if we are refunding and no payments have been tagged, then we need to decrement the client->paid_to_date by the total refund amount. diff --git a/app/Services/Payment/UpdateInvoicePayment.php b/app/Services/Payment/UpdateInvoicePayment.php index 882cba3e95bd..e0e793bd6e2b 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/Preview/StubBuilder.php b/app/Services/Preview/StubBuilder.php index 3755f077e742..4bf2eafcca47 100644 --- a/app/Services/Preview/StubBuilder.php +++ b/app/Services/Preview/StubBuilder.php @@ -42,7 +42,8 @@ class StubBuilder public $entity_type; - public \App\Models\Client | \App\Models\Vendor $recipient; + /** @var Client | Vendor $recipient **/ + public Client | Vendor $recipient; public mixed $contact; @@ -178,7 +179,7 @@ class StubBuilder $design_string = "{$this->entity_type}_design_id"; - $design = DesignModel::withTrashed()->find($this->decodePrimaryKey($html->settings->{$design_string})); + $design = DesignModel::query()->withTrashed()->find($this->decodePrimaryKey($html->settings->{$design_string})); $template = new PdfMakerDesign(strtolower($design->name)); diff --git a/app/Services/PurchaseOrder/CreateInvitations.php b/app/Services/PurchaseOrder/CreateInvitations.php index c33091bdc558..cef458d4e2fe 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 298c5718f617..e3e6036bf5a2 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 34468adaacfd..933bbdbe9de9 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() @@ -64,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 128c3bab1934..4fb3a7b1c1fa 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 77c729669bdc..bb8c7b2662bb 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 d94679776106..0c0eb85aca29 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 61e25ed58265..7bb5b47d8324 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 d070b7636614..12b19f6488f7 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]) @@ -293,7 +293,7 @@ class ProfitLoss foreach ($payment->paymentables as $pivot) { if ($pivot->paymentable_type == 'invoices') { - $invoice = Invoice::withTrashed()->find($pivot->paymentable_id); + $invoice = Invoice::query()->withTrashed()->find($pivot->paymentable_id); $amount_payment_paid += $pivot->amount - $pivot->refunded; $amount_payment_paid_converted += $amount_payment_paid / ($payment->exchange_rate ?: 1); @@ -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 782f08446b6a..0b36900c312d 100644 --- a/app/Services/Subscription/SubscriptionService.php +++ b/app/Services/Subscription/SubscriptionService.php @@ -213,7 +213,7 @@ class SubscriptionService $email_object->body = ctrans('texts.white_label_body', ['license_key' => $license_key]); $email_object->client_id = $invoice->client_id; $email_object->client_contact_id = $contact->id; - $email_object->invitation_key = $invitation->invitation_key; + $email_object->invitation_key = $invitation->key; $email_object->invitation_id = $invitation->id; $email_object->entity_id = $invoice->id; $email_object->entity_class = Invoice::class; @@ -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) @@ -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) @@ -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() @@ -676,7 +676,7 @@ class SubscriptionService $pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription); } elseif ($last_invoice->balance > 0) { - $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription); + $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice); nlog("pro rata charge = {$pro_rata_charge_amount}"); } else { $pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription) * -1; @@ -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) @@ -740,7 +740,7 @@ class SubscriptionService } if ($last_invoice->balance > 0) { - $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription); + $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice); nlog("pro rata charge = {$pro_rata_charge_amount}"); } else { $pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription) * -1; @@ -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) @@ -807,7 +807,7 @@ class SubscriptionService { nlog("handle plan change"); - $old_recurring_invoice = RecurringInvoice::find($this->decodePrimaryKey($payment_hash->data->billing_context->recurring_invoice)); + $old_recurring_invoice = RecurringInvoice::query()->find($this->decodePrimaryKey($payment_hash->data->billing_context->recurring_invoice)); if (!$old_recurring_invoice) { return $this->handleRedirect('/client/recurring_invoices/'); @@ -816,7 +816,7 @@ class SubscriptionService $recurring_invoice = $this->createNewRecurringInvoice($old_recurring_invoice); //update the invoice and attach to the recurring invoice!!!!! - $invoice = Invoice::find($payment_hash->fee_invoice_id); + $invoice = Invoice::query()->find($payment_hash->fee_invoice_id); $invoice->recurring_id = $recurring_invoice->id; $invoice->is_proforma = false; $invoice->save(); @@ -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, @@ -1166,9 +1166,9 @@ 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(); + return Product::query()->where('id', $keys)->get(); } } @@ -1186,9 +1186,9 @@ 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(); + return Product::query()->where('id', $keys)->get(); } } @@ -1207,9 +1207,9 @@ 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(); + return Product::query()->where('id', $keys)->get(); } } @@ -1227,9 +1227,9 @@ 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(); + return Product::query()->where('id', $keys)->get(); } } @@ -1243,7 +1243,7 @@ class SubscriptionService /** * Get available upgrades & downgrades for the plan. * - * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection + * @return \Illuminate\Database\Eloquent\Collection */ public function getPlans() { @@ -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) @@ -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 b5533ca8d2ee..000000000000 --- 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/ActivityTransformer.php b/app/Transformers/ActivityTransformer.php index 9bcf5b66dd63..77c3cebe6ae3 100644 --- a/app/Transformers/ActivityTransformer.php +++ b/app/Transformers/ActivityTransformer.php @@ -11,16 +11,24 @@ namespace App\Transformers; -use App\Models\Activity; -use App\Models\Backup; -use App\Models\ClientContact; -use App\Models\Invoice; -use App\Models\PurchaseOrder; use App\Models\Task; use App\Models\User; +use App\Models\Quote; +use App\Models\Backup; +use App\Models\Client; +use App\Models\Credit; use App\Models\Vendor; +use App\Models\Expense; +use App\Models\Invoice; +use App\Models\Payment; +use App\Models\Activity; +use App\Models\ClientContact; +use App\Models\PurchaseOrder; use App\Models\VendorContact; use App\Utils\Traits\MakesHash; +use App\Models\RecurringInvoice; +use App\Transformers\EntityTransformer; +use App\Transformers\InvoiceHistoryTransformer; class ActivityTransformer extends EntityTransformer { diff --git a/app/Transformers/BankIntegrationTransformer.php b/app/Transformers/BankIntegrationTransformer.php index b5eeb0ebea3c..0f296e19ad85 100644 --- a/app/Transformers/BankIntegrationTransformer.php +++ b/app/Transformers/BankIntegrationTransformer.php @@ -13,7 +13,9 @@ namespace App\Transformers; use App\Models\Account; use App\Models\BankIntegration; +use App\Models\BankTransaction; use App\Utils\Traits\MakesHash; +use App\Transformers\EntityTransformer; /** * Class BankIntegrationTransformer. diff --git a/app/Transformers/BankTransactionRuleTransformer.php b/app/Transformers/BankTransactionRuleTransformer.php index 588a802b492e..4d410c1b3bd9 100644 --- a/app/Transformers/BankTransactionRuleTransformer.php +++ b/app/Transformers/BankTransactionRuleTransformer.php @@ -43,7 +43,7 @@ class BankTransactionRuleTransformer extends EntityTransformer ]; /** - * @param BankTransaction $bank_integration + * @param BankTransactionRule $bank_transaction_rule * @return array */ public function transform(BankTransactionRule $bank_transaction_rule) diff --git a/app/Transformers/BankTransactionTransformer.php b/app/Transformers/BankTransactionTransformer.php index 5d941dbefe68..2a1c15f9e642 100644 --- a/app/Transformers/BankTransactionTransformer.php +++ b/app/Transformers/BankTransactionTransformer.php @@ -11,9 +11,11 @@ namespace App\Transformers; -use App\Models\BankTransaction; +use App\Models\Vendor; use App\Models\Company; use App\Models\Expense; +use App\Models\Payment; +use App\Models\BankTransaction; use App\Utils\Traits\MakesHash; /** diff --git a/app/Transformers/Contact/InvoiceTransformer.php b/app/Transformers/Contact/InvoiceTransformer.php index 1739bf95b626..2c711acd7a75 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 4846b56a336e..53d4f2fc0ed6 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/DocumentTransformer.php b/app/Transformers/DocumentTransformer.php index 5e409a044810..1b167ae21691 100644 --- a/app/Transformers/DocumentTransformer.php +++ b/app/Transformers/DocumentTransformer.php @@ -51,6 +51,7 @@ class DocumentTransformer extends EntityTransformer 'archived_at' => (int) $document->deleted_at, 'created_at' => (int) $document->created_at, 'is_deleted' => (bool) false, + 'is_public' => (bool) $document->is_public, ]; } } diff --git a/app/Transformers/TaskStatusTransformer.php b/app/Transformers/TaskStatusTransformer.php index c2c2f3347fad..f3f9465e29db 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, diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php index dc4cfd85a394..ee251477dea1 100644 --- a/app/Transformers/UserTransformer.php +++ b/app/Transformers/UserTransformer.php @@ -94,10 +94,14 @@ class UserTransformer extends EntityTransformer return $this->includeCollection($user->company_users, $transformer, CompanyUser::class); } + /** + * + * @param User $user + */ public function includeCompanyUser(User $user) { if (! $user->company_id && request()->header('X-API-TOKEN')) { - $company_token = CompanyToken::where('token', request()->header('X-API-TOKEN'))->first(); + $company_token = CompanyToken::query()->where('token', request()->header('X-API-TOKEN'))->first(); $user->company_id = $company_token->company_id; } diff --git a/app/Utils/EmailStats.php b/app/Utils/EmailStats.php index ff55bb08b4ae..6af60ece2fe6 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/Helpers.php b/app/Utils/Helpers.php index 912cc47f71fc..0debc7da4219 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/PhantomJS/Phantom.php b/app/Utils/PhantomJS/Phantom.php index 7786c7194b91..8080f5c66938 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); diff --git a/app/Utils/TemplateEngine.php b/app/Utils/TemplateEngine.php index 09b5ea8b9c5a..3cd5221d5de3 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 **/ @@ -98,17 +100,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(); @@ -302,6 +304,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, @@ -338,6 +342,7 @@ class TemplateEngine 'client_contact_id' => $contact->id, ]); + /** @var \App\Models\Invoice $invoice */ $this->entity_obj->invoices()->attach($invoice->id, [ 'amount' => 10, ]); @@ -376,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, @@ -389,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/app/Utils/Traits/GeneratesConvertedQuoteCounter.php b/app/Utils/Traits/GeneratesConvertedQuoteCounter.php index 06cf6fa36536..314b994e1ba0 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/app/Utils/Traits/NumberFormatter.php b/app/Utils/Traits/NumberFormatter.php index 96684e03650f..e2ea72649e10 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/app/Utils/Traits/Payment/Refundable.php b/app/Utils/Traits/Payment/Refundable.php index 482db74c39d4..442c1dfdad8f 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(); @@ -170,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) { @@ -189,8 +191,7 @@ trait Refundable $client_balance_adjustment = $this->adjustInvoices($data); - // $credit_note->ledger()->updateCreditBalance($client_balance_adjustment, $ledger_string); - + /** @var \App\Models\Payment $this */ $this->client->paid_to_date -= $data['amount']; $this->client->save(); @@ -237,6 +238,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(); diff --git a/config/ninja.php b/config/ninja.php index e50a4db22031..52ba2c49801d 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.28'), + 'app_tag' => env('APP_TAG','5.6.28'), 'minimum_client_version' => '5.0.16', 'terms_version' => '1.0.1', 'api_secret' => env('API_SECRET', ''), 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 a92881cca488..f246f588bf16 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 d7c605e661f1..d18acf9b66bb 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 f13e1357068f..24bf0df2607d 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 8a5dff484542..a53d737ad8d1 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 937dd3bace57..734063651bb8 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 b4610612d927..20ff447540f2 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 ab88783c5ea9..1cbfa10ad1b6 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 b5d6ed974fcc..f2a65b739950 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 fb0345a8c37b..f87334dc8e35 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 9b88b6d7e9cb..7104b7dbeeb1 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 46a8ec71ae94..3e319f8a7198 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 ca5cfc71782c..3b2a37765f1e 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 ecac6e4dc306..6bd5cb02a252 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 81d7736510c3..01f04630c9bf 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 d3f7033b1ca6..af159d264502 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 75b0d655b48b..29bb60d3f649 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 b0a15d6a7d95..5e3be4917375 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 76022056235a..8d5d3c1ce798 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 c8a1a8abb0c7..20316a338f63 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 new file mode 100644 index 000000000000..472f6b92c5f5 --- /dev/null +++ b/database/migrations/2023_08_06_070205_create_view_dashboard_permission_migration.php @@ -0,0 +1,45 @@ +where('is_admin', 0)->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/database/migrations/2023_08_08_212710_add_signature_ip_address_to_purchase_order_invitations.php b/database/migrations/2023_08_08_212710_add_signature_ip_address_to_purchase_order_invitations.php new file mode 100644 index 000000000000..6e6989cd70b9 --- /dev/null +++ b/database/migrations/2023_08_08_212710_add_signature_ip_address_to_purchase_order_invitations.php @@ -0,0 +1,60 @@ +text('signature_ip')->nullable(); + }); + + $xag = \App\Models\Currency::find(116); + + if(!$xag) { + + $xag = new \App\Models\Currency(); + $xag->id = 116; + $xag->code = 'XAG'; + $xag->name = 'Silver Troy Ounce'; + $xag->symbol = 'XAG'; + $xag->thousand_separator = ','; + $xag->decimal_separator = '.'; + $xag->precision = 2; + $xag->save(); + } + + $xau = \App\Models\Currency::find(117); + + if(!$xau) { + + $xau = new \App\Models\Currency(); + $xau->id = 117; + $xau->code = 'XAU'; + $xau->name = 'Gold Troy Ounce'; + $xau->symbol = 'XAU'; + $xau->thousand_separator = ','; + $xau->decimal_separator = '.'; + $xau->precision = 3; + $xau->save(); + } + + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + } +}; diff --git a/database/seeders/CurrenciesSeeder.php b/database/seeders/CurrenciesSeeder.php index 49ecce7e9d43..65778f979b29 100644 --- a/database/seeders/CurrenciesSeeder.php +++ b/database/seeders/CurrenciesSeeder.php @@ -138,6 +138,8 @@ class CurrenciesSeeder extends Seeder ['id' => 113, 'name' => 'Swazi lilangeni', 'code' => 'SZL', 'symbol' => 'E', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['id' => 114, 'name' => 'BZ Dollar', 'code' => 'BZD', 'symbol' => '$', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], ['id' => 115, 'name' => 'Libyan Dinar', 'code' => 'LYD', 'symbol' => 'LD', 'precision' => '3', 'thousand_separator' => ',', 'decimal_separator' => '.'], + ['id' => 116, 'name' => 'Silver Troy Ounce', 'code' => 'XAG', 'symbol' => 'XAG', 'precision' => '2', 'thousand_separator' => ',', 'decimal_separator' => '.'], + ['id' => 117, 'name' => 'Gold Troy Ounce', 'code' => 'XAU', 'symbol' => 'XAU', 'precision' => '3', 'thousand_separator' => ',', 'decimal_separator' => '.'], ]; foreach ($currencies as $currency) { diff --git a/lang/en/texts.php b/lang/en/texts.php index 5cac96a76c79..3fcd47c01969 100644 --- a/lang/en/texts.php +++ b/lang/en/texts.php @@ -2404,6 +2404,9 @@ $LANG = array( 'currency_cuban_peso' => 'Cuban Peso', 'currency_bz_dollar' => 'BZ Dollar', + 'currency_libyan_dinar' => 'Libyan Dinar', + 'currency_silver_troy_ounce' => 'Silver Troy Ounce', + 'currency_gold_troy_ounce' => 'Gold Troy Ounce', 'review_app_help' => 'We hope you\'re enjoying using the app.
If you\'d consider :link we\'d greatly appreciate it!', 'writing_a_review' => 'writing a review', diff --git a/phpstan.neon b/phpstan.neon index 2b60d7d20252..7aec499ed7bd 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 @@ -17,5 +18,8 @@ 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()\(\)#' - - '#Undefined method#' \ No newline at end of file + - '#Call to an undefined method [a-zA-Z0-9\\_]+::exclude\(\)#' + - '#Array has 2 duplicate keys with value#' + - '#Undefined method#' + - '#makeHidden#' + - '#Socialite#' \ No newline at end of file diff --git a/resources/views/portal/ninja2020/components/livewire/pdf-slot.blade.php b/resources/views/portal/ninja2020/components/livewire/pdf-slot.blade.php index 3e86f37eb68c..e8e2fcea3b40 100644 --- a/resources/views/portal/ninja2020/components/livewire/pdf-slot.blade.php +++ b/resources/views/portal/ninja2020/components/livewire/pdf-slot.blade.php @@ -1,7 +1,7 @@
-
- diff --git a/tests/Feature/BankTransactionApiTest.php b/tests/Feature/BankTransactionApiTest.php index f27aa681f843..a79cd8e50747 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/BaseApiTest.php b/tests/Feature/BaseApiTest.php index 75d4ae7f24b4..3fac9d506dc5 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); } @@ -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'), diff --git a/tests/Feature/ClientTest.php b/tests/Feature/ClientTest.php index 83c84201617a..8fcef3d6c14f 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 af02f493ea4b..6d0fefbc2bf1 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'),