From e75954b5c843c8ad9512aab618604f61e77be246 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 14 Feb 2023 08:12:50 +1100 Subject: [PATCH 01/72] Small patch --- app/Http/Livewire/RequiredClientInfo.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/Livewire/RequiredClientInfo.php b/app/Http/Livewire/RequiredClientInfo.php index 8b646a39e0f2..a2286249e584 100644 --- a/app/Http/Livewire/RequiredClientInfo.php +++ b/app/Http/Livewire/RequiredClientInfo.php @@ -238,8 +238,8 @@ class RequiredClientInfo extends Component if($cg && $cg->update_details){ $payment_gateway = $cg->driver($this->client)->init(); - if(method_exists($payment_gateway, "updateCustomer")) - $payment_gateway->updateCustomer(); + // if(method_exists($payment_gateway, "updateCustomer")) + // $payment_gateway->updateCustomer(); } return true; From 4670c06b7eabe74f8af47c387f5de7d93ca8cc4b Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 14 Feb 2023 10:03:54 +1100 Subject: [PATCH 02/72] Refactor for emails --- app/Services/Email/BaseMailer.php | 157 ++++++++++++++++++++++++++++++ app/Services/Email/MailBuild.php | 22 +++++ app/Services/Email/MailEntity.php | 38 ++++---- app/Services/Email/MailObject.php | 7 ++ 4 files changed, 204 insertions(+), 20 deletions(-) create mode 100644 app/Services/Email/BaseMailer.php create mode 100644 app/Services/Email/MailBuild.php diff --git a/app/Services/Email/BaseMailer.php b/app/Services/Email/BaseMailer.php new file mode 100644 index 000000000000..38b41c261bed --- /dev/null +++ b/app/Services/Email/BaseMailer.php @@ -0,0 +1,157 @@ +company) + $this->fail(); + + /* Handle deactivated company */ + if($this->company->is_disabled && !$this->override) + $this->fail(); + + /* To handle spam users we drop all emails from flagged accounts */ + if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) + $this->fail(); + + } + + public function configureMailer(): self + { + + return $this; + } + + public function trySending() + { + try { + + $mailer + ->to($this->nmo->to_user->email) + ->send($this->nmo->mailable); + + /* Count the amount of emails sent across all the users accounts */ + Cache::increment($this->company->account->key); + + LightLogs::create(new EmailSuccess($this->company->company_key)) + ->send(); + + } + catch(\Symfony\Component\Mime\Exception\RfcComplianceException $e) { + nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); + $this->fail(); + $this->cleanUpMailers(); + $this->logMailError($e->getMessage(), $this->company->clients()->first()); + return; + } + catch(\Symfony\Component\Mime\Exception\LogicException $e){ + nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); + $this->fail(); + $this->cleanUpMailers(); + $this->logMailError($e->getMessage(), $this->company->clients()->first()); + return; + } + catch (\Exception | \Google\Service\Exception $e) { + + nlog("Mailer failed with {$e->getMessage()}"); + $message = $e->getMessage(); + + /** + * Post mark buries the proper message in a a guzzle response + * this merges a text string with a json object + * need to harvest the ->Message property using the following + */ + if(stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) + { + + $message = "Either Attachment too large, or recipient has been suppressed."; + + $this->fail(); + $this->logMailError($e->getMessage(), $this->company->clients()->first()); + $this->cleanUpMailers(); + + return; + + } + + //only report once, not on all tries + if($this->attempts() == $this->tries) + { + + /* If the is an entity attached to the message send a failure mailer */ + if($this->nmo->entity) + $this->entityEmailFailed($message); + + /* Don't send postmark failures to Sentry */ + if(Ninja::isHosted() && (!$e instanceof ClientException)) + app('sentry')->captureException($e); + + } + + /* Releasing immediately does not add in the backoff */ + $this->release($this->backoff()[$this->attempts()-1]); + + } + } + + public function backoff() + { + return [5, 10, 30, 240]; + } + + public function failed($exception = null) + { + + config(['queue.failed.driver' => null]); + + } +} +` \ No newline at end of file diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php new file mode 100644 index 000000000000..2da48294db7a --- /dev/null +++ b/app/Services/Email/MailBuild.php @@ -0,0 +1,22 @@ +invitation = $invitation; + $this->company = $invitation->company; + $this->db = $db; - $this->reminder_template = $reminder_template; + $this->mail_object = $mail_object; - $this->template_data = $template_data; - - $this->override = $override; - - // $this->entity_string = $this->resolveEntityString(); - - // $this->entity = $invitation->{$this->entity_string}; - - // $this->settings = $invitation->contact->client->getMergedSettings(); - - // $this->reminder_template = $reminder_template ?: $this->entity->calculateTemplate($this->entity_string); - - // $this->html_engine = new HtmlEngine($invitation); - - // $this->template_data = $template_data; + $this->override = $mail_object->override; } - public function handle(): void + public function handle(MailBuild $builder): void { MultiDB::setDb($this->db); + $this->companyCheck(); + //construct mailable - //construct mailer + //spam checks + //what do we pass into a generaic builder? + + //construct mailer + $mailer = $this->configureMailer() + ->trySending(); + + } } diff --git a/app/Services/Email/MailObject.php b/app/Services/Email/MailObject.php index 08a540342e02..f9467866d60c 100644 --- a/app/Services/Email/MailObject.php +++ b/app/Services/Email/MailObject.php @@ -77,4 +77,11 @@ class MailObject public array $variables = []; + public ?string $reminder_template = null; + + public ?string $template_data = null; + + public bool $override = false; + + } \ No newline at end of file From a8362762cfb88042a3b5b7ea648d1434b5979285 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 14 Feb 2023 11:25:48 +1100 Subject: [PATCH 03/72] Fixes for base redirect --- app/Http/Controllers/BaseController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index 0c3c63a8858e..0c849ba98004 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -1033,7 +1033,7 @@ class BaseController extends Controller if ((bool) $this->checkAppSetup() !== false && $account = Account::first()) { //always redirect invoicing.co to invoicing.co - if(Ninja::isHosted() && (request()->getSchemeAndHttpHost() != 'https://invoicing.co')) + if(Ninja::isHosted() && !in_array(request()->getSchemeAndHttpHost(), ['https://staging.invoicing.co', 'https://invoicing.co'])) return redirect()->secure('https://invoicing.co'); if (config('ninja.require_https') && ! request()->isSecure()) { From 1a3d5420ed128baa17b4ad5378fa97808714fca4 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 14 Feb 2023 11:27:14 +1100 Subject: [PATCH 04/72] Minor fixes --- app/Http/Controllers/BaseController.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index 0c849ba98004..79947be64b77 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -1033,7 +1033,7 @@ class BaseController extends Controller if ((bool) $this->checkAppSetup() !== false && $account = Account::first()) { //always redirect invoicing.co to invoicing.co - if(Ninja::isHosted() && !in_array(request()->getSchemeAndHttpHost(), ['https://staging.invoicing.co', 'https://invoicing.co'])) + if(Ninja::isHosted() && !in_array(request()->getSchemeAndHttpHost(), ['https://staging.invoicing.co', 'https://invoicing.co', 'https://demo.invoicing.co'])) return redirect()->secure('https://invoicing.co'); if (config('ninja.require_https') && ! request()->isSecure()) { From 6384e27e4b2ac9b4bcd056b88eaf2f4fd4bcfa0b Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 14 Feb 2023 15:33:55 +1100 Subject: [PATCH 05/72] Working on new email handlers --- app/Services/Email/MailBuild.php | 304 +++++++++++++++++++++++++++++- app/Services/Email/MailEntity.php | 6 +- 2 files changed, 304 insertions(+), 6 deletions(-) diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index 2da48294db7a..0d58130bf941 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -11,12 +11,310 @@ namespace App\Services\Email; +use App\Models\Client; +use App\Models\Vendor; +use App\Utils\Ninja; +use Illuminate\Contracts\Mail\Mailable; +use Illuminate\Mail\Mailable as MailMailable; +use Illuminate\Support\Facades\App; + +/** + * Class assumption is that we will be emailing an entity that has an associated Invitation + */ class MailBuild { - - public function __construct() + + /** + * The settings object for this email + * @var CompanySettings $settings + */ + protected $settings; + + /** + * The HTML / Template to use for this email + * @var string $template + */ + private string $template; + + /** + * The locale to use for + * translations for this email + */ + private string $locale; + + private ?Client $client; + + private ?Vendor $vendor; + + public function __construct(public MailEntity $mail_entity) { - + } + public function run(): Mailable + { + //resolve settings, if client existing - use merged - else default to company + $this->settings = $this->mail_entity->company->settings; + $this->resolveEntities(); + } + + private function resolveEntities(): self + { + + $this->client = $this->mail_entity->mail_object->client_id ? Client::find($this->mail_entity->mail_object->client_id) : null; + + $this->vendor = $this->mail_entity->mail_object->vendor_id ? Vendor::find($this->mail_entity->mail_object->vendor_id) : null; + + $this->locale = $this->mail_entity->company->locale(); + + return $this; + } + + + /** + * Sets the meta data for the Email object + */ + private function setMetaData(): self + { + + $this->mail_entity->mail_object->company_key = $this->mail_entity->company->company_key; + + $this->mail_entity->mail_object->logo = $this->mail_entity->company->present()->logo(); + + $this->mail_entity->mail_object->signature = $this->mail_entity->mail_object->signature ?: $this->settings->email_signature; + + $this->mail_entity->mail_object->whitelabel = $this->mail_entity->company->account->isPaid() ? true : false; + + return $this; + + } + + /** + * Sets the locale + */ + private function setLocale(): self + { + + if($this->mail_entity->mail_object->client_id) + $this->locale = $this->mail_entity->mail_object->client->locale(); + elseif($this->mail_entity->mail_object->vendor) + $this->locale = $this->mail_entity->mail_object->vendor->locale(); + else + $this->locale = $this->mail_entity->company->locale(); + + App::setLocale($this->locale); + App::forgetInstance('translator'); + $t = app('translator'); + $t->replace(Ninja::transformTranslations($this->settings)); + + return $this; + } + + /** + * Sets the template + */ + private function setTemplate(): self + { + $this->template = $this->mail_entity->mail_object->settings->email_style; + + match($this->mail_entity->mail_object->settings->email_style){ + 'light' => $this->template = 'email.template.client', + 'dark' => $this->template = 'email.template.client', + 'custom' => $this->template = 'email.template.custom', + default => $this->template = 'email.template.client', + }; + + $this->mail_entity->mail_object->html_template = $this->template; + + return $this; + } + + /** + * Sets the FROM address + */ + private function setFrom(): self + { + + if(Ninja::isHosted() && $this->mail_entity->mail_object->settings->email_sending_method == 'default'){ + $this->mail_entity->mail_object->from = new Address(config('mail.from.address'), $this->mail_entity->company->owner()->name()); + return $this; + } + + if($this->mail_entity->mail_object->from) + return $this; + + $this->mail_entity->mail_object->from = new Address($this->mail_entity->company->owner()->email, $this->mail_entity->company->owner()->name()); + + return $this; + + } + + /** + * Sets the body of the email + */ + private function setBody(): self + { + + if($this->mail_entity->mail_object->body){ + $this->mail_entity->mail_object->body = $this->mail_entity->mail_object->body; + } + elseif(strlen($this->mail_entity->mail_object->settings->{$this->mail_entity->mail_object->email_template_body}) > 3){ + $this->mail_entity->mail_object->body = $this->mail_entity->mail_object->settings->{$this->mail_entity->mail_object->email_template_body}; + } + else{ + $this->mail_entity->mail_object->body = EmailTemplateDefaults::getDefaultTemplate($this->mail_entity->mail_object->email_template_body, $this->locale); + } + + if($this->template == 'email.template.custom'){ + $this->mail_entity->mail_object->body = (str_replace('$body', $this->mail_entity->mail_object->body, $this->mail_entity->mail_object->settings->email_style_custom)); + } + + return $this; + + } + + /** + * Sets the subject of the email + */ + private function setSubject(): self + { + + if ($this->mail_entity->mail_object->subject) //where the user updates the subject from the UI + return $this; + elseif(strlen($this->mail_entity->mail_object->settings->{$this->mail_entity->mail_object->email_template_subject}) > 3) + $this->mail_entity->mail_object->subject = $this->mail_entity->mail_object->settings->{$this->mail_entity->mail_object->email_template_subject}; + else + $this->mail_entity->mail_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->mail_entity->mail_object->email_template_subject, $this->locale); + + return $this; + + } + + /** + * Sets the reply to of the email + */ + private function setReplyTo(): self + { + + $reply_to_email = str_contains($this->mail_entity->mail_object->settings->reply_to_email, "@") ? $this->mail_entity->mail_object->settings->reply_to_email : $this->mail_entity->company->owner()->email; + + $reply_to_name = strlen($this->mail_entity->mail_object->settings->reply_to_name) > 3 ? $this->mail_entity->mail_object->settings->reply_to_name : $this->mail_entity->company->owner()->present()->name(); + + $this->mail_entity->mail_object->reply_to = array_merge($this->mail_entity->mail_object->reply_to, [new Address($reply_to_email, $reply_to_name)]); + + return $this; + } + + /** + * Replaces the template placeholders + * with variable values. + */ + public function setVariables(): self + { + + $this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $this->mail_entity->mail_object->variables); + + $this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $this->mail_entity->mail_object->variables); + + if($this->template != 'custom') + $this->mail_entity->mail_object->body = $this->parseMarkdownToHtml($this->mail_entity->mail_object->body); + + return $this; + } + + /** + * Sets the BCC of the email + */ + private function setBcc(): self + { + $bccs = []; + $bcc_array = []; + + if (strlen($this->mail_entity->mail_object->settings->bcc_email) > 1) { + + if (Ninja::isHosted() && $this->mail_entity->company->account->isPaid()) { + $bccs = array_slice(explode(',', str_replace(' ', '', $this->mail_entity->mail_object->settings->bcc_email)), 0, 2); + } elseif(Ninja::isSelfHost()) { + $bccs = (explode(',', str_replace(' ', '', $this->mail_entity->mail_object->settings->bcc_email))); + } + } + + foreach($bccs as $bcc) + { + $bcc_array[] = new Address($bcc); + } + + $this->mail_entity->mail_object->bcc = array_merge($this->mail_entity->mail_object->bcc, $bcc_array); + + return $this; + } + + /** + * Sets the CC of the email + * @todo at some point.... + */ + private function buildCc() + { + return [ + + ]; + } + + /** + * Sets the attachments for the email + * + * Note that we base64 encode these, as they + * sometimes may not survive serialization. + * + * We decode these in the Mailable later + */ + private function setAttachments(): self + { + $attachments = []; + + if ($this->mail_entity->mail_object->settings->document_email_attachment && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { + + foreach ($this->mail_entity->company->documents as $document) { + + $attachments[] = ['file' => base64_encode($document->getFile()), 'name' => $document->name]; + + } + + } + + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, $attachments); + + return $this; + + } + + /** + * Sets the headers for the email + */ + private function setHeaders(): self + { + if($this->mail_entity->mail_object->invitation_key) + $this->mail_entity->mail_object->headers = array_merge($this->mail_entity->mail_object->headers, ['x-invitation-key' => $this->mail_entity->mail_object->invitation_key]); + + return $this; + } + + /** + * Converts any markdown to HTML in the email + * + * @param string $markdown The body to convert + * @return string The parsed markdown response + */ + private function parseMarkdownToHtml(string $markdown): ?string + { + $converter = new CommonMarkConverter([ + 'allow_unsafe_links' => false, + ]); + + return $converter->convert($markdown); + } + + + + } diff --git a/app/Services/Email/MailEntity.php b/app/Services/Email/MailEntity.php index 576910319801..5994e2597cc7 100644 --- a/app/Services/Email/MailEntity.php +++ b/app/Services/Email/MailEntity.php @@ -24,9 +24,9 @@ class MailEntity extends BaseMailer implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - protected Company $company; + public Company $company; - public function __construct(protected $invitation, private ?string $db, public MailObject $mail_object) + public function __construct(protected ?mixed $invitation, private ?string $db, public MailObject $mail_object) { $this->invitation = $invitation; @@ -48,7 +48,7 @@ class MailEntity extends BaseMailer implements ShouldQueue $this->companyCheck(); //construct mailable - + $builder->run($this); //spam checks //what do we pass into a generaic builder? From 222cbc77039c7f672efcdc30cadabd635daec66b Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 14 Feb 2023 21:04:07 +1100 Subject: [PATCH 06/72] Updates for mailablej --- app/Models/CompanyUser.php | 5 +- app/Services/Email/BaseMailer.php | 138 +++++++-- app/Services/Email/MailBuild.php | 262 ++++++++++++------ app/Services/Email/MailEntity.php | 251 ++++++++++++++++- app/Services/Email/MailMailable.php | 107 +++++++ app/Services/Email/MailObject.php | 4 +- app/Transformers/CompanyUserTransformer.php | 1 + ...act_settings_column_company_user_table.php | 34 +++ 8 files changed, 685 insertions(+), 117 deletions(-) create mode 100644 app/Services/Email/MailMailable.php create mode 100644 database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php diff --git a/app/Models/CompanyUser.php b/app/Models/CompanyUser.php index cc1cbe796800..24e4935a705a 100644 --- a/app/Models/CompanyUser.php +++ b/app/Models/CompanyUser.php @@ -43,6 +43,7 @@ class CompanyUser extends Pivot 'permissions', 'notifications', 'settings', + 'react_settings', 'is_admin', 'is_owner', 'is_locked', @@ -71,12 +72,12 @@ class CompanyUser extends Pivot public function user_pivot() { - return $this->hasOne(User::class)->withPivot('permissions', 'settings', 'is_admin', 'is_owner', 'is_locked', 'slack_webhook_url', 'migrating'); + return $this->hasOne(User::class)->withPivot('permissions', 'settings', 'react_settings', 'is_admin', 'is_owner', 'is_locked', 'slack_webhook_url', 'migrating'); } public function company_pivot() { - return $this->hasOne(Company::class)->withPivot('permissions', 'settings', 'is_admin', 'is_owner', 'is_locked', 'slack_webhook_url', 'migrating'); + return $this->hasOne(Company::class)->withPivot('permissions', 'settings', 'react_settings', 'is_admin', 'is_owner', 'is_locked', 'slack_webhook_url', 'migrating'); } public function user() diff --git a/app/Services/Email/BaseMailer.php b/app/Services/Email/BaseMailer.php index 38b41c261bed..1fd066d5a8a5 100644 --- a/app/Services/Email/BaseMailer.php +++ b/app/Services/Email/BaseMailer.php @@ -11,15 +11,19 @@ namespace App\Services\Email; -use App\Libraries\MultiDB; -use App\Models\Company; -use App\Services\Email\MailBuild; use App\Utils\Ninja; +use App\Models\Company; use Illuminate\Bus\Queueable; +use App\Services\Email\MailBuild; +use Illuminate\Support\Facades\Mail; +use Illuminate\Support\Facades\Cache; +use Illuminate\Queue\SerializesModels; +use Turbo124\Beacon\Facades\LightLogs; +use Illuminate\Contracts\Mail\Mailable; +use Illuminate\Queue\InteractsWithQueue; +use App\DataMapper\Analytics\EmailSuccess; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; class BaseMailer implements ShouldQueue { @@ -29,27 +33,38 @@ class BaseMailer implements ShouldQueue public int $tries = 4; - public ?string $client_postmark_secret = false; + public ?string $client_postmark_secret = null; public ?string $client_mailgun_secret = null; public ?string $client_mailgun_domain = null; - public boolean $override = false; + public bool $override = false; public $deleteWhenMissingModels = true; - public function __construct() + public Mail $mail; + + private string $mailer = 'default'; + + public function __construct(public mixed $invitation, private ?string $db, public MailObject $mail_object) { + + $this->invitation = $invitation; + + $this->company = $invitation->company; + + $this->db = $db; + + $this->mail_object = $mail_object; + + $this->override = $mail_object->override; + } - public function handle(MailBuild $builder): void - { - } - public function companyCheck() + public function companyCheck(): void { - /* Handle bad state */ if(!$this->company) $this->fail(); @@ -66,17 +81,109 @@ class BaseMailer implements ShouldQueue public function configureMailer(): self { + $this->setMailDriver(); + $this->mail = Mail::mailer($this->mailer); + return $this; } + + /** + * Sets the mail driver to use and applies any specific configuration + * the the mailable + */ + private function setMailDriver(): self + { + + switch ($this->mail_object->settings->email_sending_method) { + case 'default': + $this->mailer = config('mail.default'); + break; + // case 'gmail': + // $this->mailer = 'gmail'; + // $this->setGmailMailer(); + // return $this; + // case 'office365': + // $this->mailer = 'office365'; + // $this->setOfficeMailer(); + // return $this; + // case 'client_postmark': + // $this->mailer = 'postmark'; + // $this->setPostmarkMailer(); + // return $this; + // case 'client_mailgun': + // $this->mailer = 'mailgun'; + // $this->setMailgunMailer(); + // return $this; + + default: + break; + } + + if(Ninja::isSelfHost()) + $this->setSelfHostMultiMailer(); + + return $this; + + } + + /** + * Allows configuration of multiple mailers + * per company for use by self hosted users + */ + private function setSelfHostMultiMailer(): void + { + + if (env($this->email_service->company->id . '_MAIL_HOST')) + { + + config([ + 'mail.mailers.smtp' => [ + 'transport' => 'smtp', + 'host' => env($this->email_service->company->id . '_MAIL_HOST'), + 'port' => env($this->email_service->company->id . '_MAIL_PORT'), + 'username' => env($this->email_service->company->id . '_MAIL_USERNAME'), + 'password' => env($this->email_service->company->id . '_MAIL_PASSWORD'), + ], + ]); + + if(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS')) + { + $this->email_mailable + ->from(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->email_service->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME'))); + } + + } + + } + + + /** + * Ensure we discard any data that is not required + * + * @return void + */ + private function cleanUpMailers(): void + { + $this->client_postmark_secret = false; + + $this->client_mailgun_secret = false; + + $this->client_mailgun_domain = false; + + //always dump the drivers to prevent reuse + app('mail.manager')->forgetMailers(); + } + + public function trySending() { try { $mailer - ->to($this->nmo->to_user->email) - ->send($this->nmo->mailable); + ->to($this->mail_object->to_user->email) + ->send($this->mail_object->mailable); /* Count the amount of emails sent across all the users accounts */ Cache::increment($this->company->account->key); @@ -154,4 +261,3 @@ class BaseMailer implements ShouldQueue } } -` \ No newline at end of file diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index 0d58130bf941..be5f68bc1ad3 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -11,53 +11,90 @@ namespace App\Services\Email; +use App\Utils\Ninja; use App\Models\Client; use App\Models\Vendor; -use App\Utils\Ninja; -use Illuminate\Contracts\Mail\Mailable; -use Illuminate\Mail\Mailable as MailMailable; +use App\Models\Account; +use App\Utils\HtmlEngine; use Illuminate\Support\Facades\App; +use App\Services\Email\MailMailable; +use Illuminate\Mail\Mailables\Address; +use Illuminate\Contracts\Mail\Mailable; +use App\DataMapper\EmailTemplateDefaults; +use League\CommonMark\CommonMarkConverter; -/** - * Class assumption is that we will be emailing an entity that has an associated Invitation - */ class MailBuild { - + /** - * The settings object for this email - * @var CompanySettings $settings + * settings + * + * @var mixed */ protected $settings; - - /** - * The HTML / Template to use for this email - * @var string $template - */ + + /** @var mixed $template */ private string $template; - - /** - * The locale to use for - * translations for this email - */ + + /** @var mixed $locale */ private string $locale; - + + /** @var mixed $client */ private ?Client $client; - + + /** @var mixed $vendor */ private ?Vendor $vendor; - - public function __construct(public MailEntity $mail_entity) - { - - } - - public function run(): Mailable + + /** + * __construct + * + * @param mixed $mail_entity + * @return void + */ + public function __construct(public MailEntity $mail_entity){} + + /** + * Builds the mailable + * + * @return self + */ + public function run(): self { //resolve settings, if client existing - use merged - else default to company $this->settings = $this->mail_entity->company->settings; - $this->resolveEntities(); + $this->mail_entity->mail_object->settings = $this->settings; + + $this->resolveEntities() + ->setLocale() + ->setFrom() + ->setTo() + ->setTemplate() + ->setSubject() + ->setBody() + ->setReplyTo() + ->setBcc() + ->setAttachments() + ->setMetaData() + ->setVariables(); + + return $this; + } + + /** + * Returns the mailable to the mailer + * + * @return Mailable + */ + public function getMailable(): Mailable + { + return new MailMailable($this->mail_entity->mail_object); //todo current depends on EmailObject } + /** + * Resolve any class entities + * + * @return self + */ private function resolveEntities(): self { @@ -65,14 +102,13 @@ class MailBuild $this->vendor = $this->mail_entity->mail_object->vendor_id ? Vendor::find($this->mail_entity->mail_object->vendor_id) : null; - $this->locale = $this->mail_entity->company->locale(); - return $this; } - /** * Sets the meta data for the Email object + * + * @return self */ private function setMetaData(): self { @@ -85,20 +121,28 @@ class MailBuild $this->mail_entity->mail_object->whitelabel = $this->mail_entity->company->account->isPaid() ? true : false; + $this->mail_entity->mail_object->company = $this->mail_entity->company; + return $this; } + /** * Sets the locale + * + * @return self */ private function setLocale(): self { - if($this->mail_entity->mail_object->client_id) - $this->locale = $this->mail_entity->mail_object->client->locale(); - elseif($this->mail_entity->mail_object->vendor) - $this->locale = $this->mail_entity->mail_object->vendor->locale(); + if($this->client){ + $this->locale = $this->client->locale(); + $this->settings = $this->client->getMergedSettings(); + $this->mail_entity->mail_object->settings = $this->settings; + } + elseif($this->vendor) + $this->locale = $this->vendor->locale(); else $this->locale = $this->mail_entity->company->locale(); @@ -112,12 +156,14 @@ class MailBuild /** * Sets the template + * + * @return self */ private function setTemplate(): self { - $this->template = $this->mail_entity->mail_object->settings->email_style; + $this->template = $this->settings->email_style; - match($this->mail_entity->mail_object->settings->email_style){ + match($this->settings->email_style){ 'light' => $this->template = 'email.template.client', 'dark' => $this->template = 'email.template.client', 'custom' => $this->template = 'email.template.custom', @@ -128,14 +174,28 @@ class MailBuild return $this; } - + + /** + * setTo + * + * @return self + */ + private function setTo(): self + { + $this->mail_entity->mail_object->to = [new Address($this->mail_entity->invitation->contact->email, $this->mail_entity->invitation->contact->present()->name())]; + + return $this; + } + /** * Sets the FROM address + * + * @return self */ private function setFrom(): self { - if(Ninja::isHosted() && $this->mail_entity->mail_object->settings->email_sending_method == 'default'){ + if(Ninja::isHosted() && $this->settings->email_sending_method == 'default'){ $this->mail_entity->mail_object->from = new Address(config('mail.from.address'), $this->mail_entity->company->owner()->name()); return $this; } @@ -148,9 +208,30 @@ class MailBuild return $this; } + + /** + * Sets the subject of the email + * + * @return self + */ + private function setSubject(): self + { - /** + if ($this->mail_entity->mail_object->subject) //where the user updates the subject from the UI + return $this; + elseif(is_string($this->mail_entity->mail_object->email_template_subject) && strlen($this->settings->{$this->mail_entity->mail_object->email_template_subject}) > 3) + $this->mail_entity->mail_object->subject = $this->settings->{$this->mail_entity->mail_object->email_template_subject}; + else + $this->mail_entity->mail_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->mail_entity->mail_object->email_template_subject, $this->locale); + + return $this; + + } + + /** * Sets the body of the email + * + * @return self */ private function setBody(): self { @@ -158,47 +239,64 @@ class MailBuild if($this->mail_entity->mail_object->body){ $this->mail_entity->mail_object->body = $this->mail_entity->mail_object->body; } - elseif(strlen($this->mail_entity->mail_object->settings->{$this->mail_entity->mail_object->email_template_body}) > 3){ - $this->mail_entity->mail_object->body = $this->mail_entity->mail_object->settings->{$this->mail_entity->mail_object->email_template_body}; + elseif(is_string($this->mail_entity->mail_object->email_template_body) && strlen($this->settings->{$this->mail_entity->mail_object->email_template_body}) > 3){ + $this->mail_entity->mail_object->body = $this->settings->{$this->mail_entity->mail_object->email_template_body}; } else{ $this->mail_entity->mail_object->body = EmailTemplateDefaults::getDefaultTemplate($this->mail_entity->mail_object->email_template_body, $this->locale); } if($this->template == 'email.template.custom'){ - $this->mail_entity->mail_object->body = (str_replace('$body', $this->mail_entity->mail_object->body, $this->mail_entity->mail_object->settings->email_style_custom)); + $this->mail_entity->mail_object->body = (str_replace('$body', $this->mail_entity->mail_object->body, $this->settings->email_style_custom)); } return $this; } - /** - * Sets the subject of the email - */ - private function setSubject(): self + /** + * Sets the attachments for the email + * + * Note that we base64 encode these, as they + * sometimes may not survive serialization. + * + * We decode these in the Mailable later + * + * @return self + */ + private function setAttachments(): self { + $attachments = []; - if ($this->mail_entity->mail_object->subject) //where the user updates the subject from the UI - return $this; - elseif(strlen($this->mail_entity->mail_object->settings->{$this->mail_entity->mail_object->email_template_subject}) > 3) - $this->mail_entity->mail_object->subject = $this->mail_entity->mail_object->settings->{$this->mail_entity->mail_object->email_template_subject}; - else - $this->mail_entity->mail_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->mail_entity->mail_object->email_template_subject, $this->locale); + if ($this->settings->document_email_attachment && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { + + foreach ($this->mail_entity->company->documents as $document) { + + $attachments[] = ['file' => base64_encode($document->getFile()), 'name' => $document->name]; + + } + + } + + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, $attachments); return $this; } + + /** * Sets the reply to of the email + * + * @return self */ private function setReplyTo(): self { - $reply_to_email = str_contains($this->mail_entity->mail_object->settings->reply_to_email, "@") ? $this->mail_entity->mail_object->settings->reply_to_email : $this->mail_entity->company->owner()->email; + $reply_to_email = str_contains($this->settings->reply_to_email, "@") ? $this->settings->reply_to_email : $this->mail_entity->company->owner()->email; - $reply_to_name = strlen($this->mail_entity->mail_object->settings->reply_to_name) > 3 ? $this->mail_entity->mail_object->settings->reply_to_name : $this->mail_entity->company->owner()->present()->name(); + $reply_to_name = strlen($this->settings->reply_to_name) > 3 ? $this->settings->reply_to_name : $this->mail_entity->company->owner()->present()->name(); $this->mail_entity->mail_object->reply_to = array_merge($this->mail_entity->mail_object->reply_to, [new Address($reply_to_email, $reply_to_name)]); @@ -208,13 +306,22 @@ class MailBuild /** * Replaces the template placeholders * with variable values. + * + * @return self */ public function setVariables(): self { - $this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $this->mail_entity->mail_object->variables); - $this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $this->mail_entity->mail_object->variables); + if($this->mail_entity->mail_object->variables){ + $this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $this->mail_entity->mail_object->variables); + $this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $this->mail_entity->mail_object->variables); + } + + $variables = (new HtmlEngine($this->mail_entity->invitation))->makeValues(); + + $this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $variables); + $this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $variables); if($this->template != 'custom') $this->mail_entity->mail_object->body = $this->parseMarkdownToHtml($this->mail_entity->mail_object->body); @@ -224,18 +331,20 @@ class MailBuild /** * Sets the BCC of the email + * + * @return self */ private function setBcc(): self { $bccs = []; $bcc_array = []; - if (strlen($this->mail_entity->mail_object->settings->bcc_email) > 1) { + if (strlen($this->settings->bcc_email) > 1) { if (Ninja::isHosted() && $this->mail_entity->company->account->isPaid()) { - $bccs = array_slice(explode(',', str_replace(' ', '', $this->mail_entity->mail_object->settings->bcc_email)), 0, 2); + $bccs = array_slice(explode(',', str_replace(' ', '', $this->settings->bcc_email)), 0, 2); } elseif(Ninja::isSelfHost()) { - $bccs = (explode(',', str_replace(' ', '', $this->mail_entity->mail_object->settings->bcc_email))); + $bccs = (explode(',', str_replace(' ', '', $this->settings->bcc_email))); } } @@ -260,41 +369,18 @@ class MailBuild ]; } - /** - * Sets the attachments for the email - * - * Note that we base64 encode these, as they - * sometimes may not survive serialization. - * - * We decode these in the Mailable later - */ - private function setAttachments(): self - { - $attachments = []; - - if ($this->mail_entity->mail_object->settings->document_email_attachment && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - - foreach ($this->mail_entity->company->documents as $document) { - - $attachments[] = ['file' => base64_encode($document->getFile()), 'name' => $document->name]; - - } - - } - - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, $attachments); - - return $this; - - } /** * Sets the headers for the email + * + * @return self */ private function setHeaders(): self { if($this->mail_entity->mail_object->invitation_key) $this->mail_entity->mail_object->headers = array_merge($this->mail_entity->mail_object->headers, ['x-invitation-key' => $this->mail_entity->mail_object->invitation_key]); + elseif($this->mail_entity->invitation) + $this->mail_entity->mail_object->headers = array_merge($this->mail_entity->mail_object->headers, ['x-invitation-key' => $this->mail_entity->invitation->key]); return $this; } diff --git a/app/Services/Email/MailEntity.php b/app/Services/Email/MailEntity.php index 5994e2597cc7..4b56f70ba719 100644 --- a/app/Services/Email/MailEntity.php +++ b/app/Services/Email/MailEntity.php @@ -11,22 +11,52 @@ namespace App\Services\Email; -use App\Libraries\MultiDB; +use App\Utils\Ninja; use App\Models\Company; -use App\Services\Email\MailBuild; +use App\Libraries\MultiDB; use Illuminate\Bus\Queueable; +use Illuminate\Mail\Mailable; +use App\Services\Email\MailBuild; +use Illuminate\Support\Facades\Mail; +use Illuminate\Support\Facades\Cache; +use Illuminate\Queue\SerializesModels; +use Turbo124\Beacon\Facades\LightLogs; +use Illuminate\Queue\InteractsWithQueue; +use App\DataMapper\Analytics\EmailSuccess; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; -class MailEntity extends BaseMailer implements ShouldQueue +class MailEntity implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public Company $company; - public function __construct(protected ?mixed $invitation, private ?string $db, public MailObject $mail_object) + public int $tries = 4; + + public ?string $client_postmark_secret = null; + + public ?string $client_mailgun_secret = null; + + public ?string $client_mailgun_domain = null; + + public bool $override = false; + + public $deleteWhenMissingModels = true; + + private string $mailer = ''; + + public $invitation; + + public Mail $mail; + + private ?string $db; + + public MailObject $mail_object; + + public Mailable $mailable; + + public function __construct($invitation, $db, $mail_object) { $this->invitation = $invitation; @@ -41,23 +71,224 @@ class MailEntity extends BaseMailer implements ShouldQueue } - public function handle(MailBuild $builder): void + public function handle(): void { + $builder = new MailBuild($this); + MultiDB::setDb($this->db); $this->companyCheck(); //construct mailable $builder->run($this); + + $this->mailable = $builder->getMailable(); + + $this->setMailDriver() + ->trySending(); + //spam checks //what do we pass into a generaic builder? //construct mailer - $mailer = $this->configureMailer() - ->trySending(); - } + public function companyCheck(): void + { + /* Handle bad state */ + if(!$this->company) + $this->fail(); + + /* Handle deactivated company */ + if($this->company->is_disabled && !$this->override) + $this->fail(); + + /* To handle spam users we drop all emails from flagged accounts */ + if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) + $this->fail(); + + } + + public function configureMailer(): self + { + $this->setMailDriver(); + + $this->mail = Mail::mailer($this->mailer); + + return $this; + } + + + /** + * Sets the mail driver to use and applies any specific configuration + * the the mailable + */ + private function setMailDriver(): self + { + + switch ($this->mail_object->settings->email_sending_method) { + case 'default': + $this->mailer = config('mail.default'); + break; + // case 'gmail': + // $this->mailer = 'gmail'; + // $this->setGmailMailer(); + // return $this; + // case 'office365': + // $this->mailer = 'office365'; + // $this->setOfficeMailer(); + // return $this; + // case 'client_postmark': + // $this->mailer = 'postmark'; + // $this->setPostmarkMailer(); + // return $this; + // case 'client_mailgun': + // $this->mailer = 'mailgun'; + // $this->setMailgunMailer(); + // return $this; + + default: + break; + } + + if(Ninja::isSelfHost()) + $this->setSelfHostMultiMailer(); + + return $this; + + } + + /** + * Allows configuration of multiple mailers + * per company for use by self hosted users + */ + private function setSelfHostMultiMailer(): void + { + + if (env($this->company->id . '_MAIL_HOST')) + { + + config([ + 'mail.mailers.smtp' => [ + 'transport' => 'smtp', + 'host' => env($this->company->id . '_MAIL_HOST'), + 'port' => env($this->company->id . '_MAIL_PORT'), + 'username' => env($this->company->id . '_MAIL_USERNAME'), + 'password' => env($this->company->id . '_MAIL_PASSWORD'), + ], + ]); + + if(env($this->company->id . '_MAIL_FROM_ADDRESS')) + { + $this->mailable + ->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME'))); + } + + } + + } + + + /** + * Ensure we discard any data that is not required + * + * @return void + */ + private function cleanUpMailers(): void + { + $this->client_postmark_secret = false; + + $this->client_mailgun_secret = false; + + $this->client_mailgun_domain = false; + + //always dump the drivers to prevent reuse + app('mail.manager')->forgetMailers(); + } + + + public function trySending() + { + try { + + $mail = Mail::mailer($this->mailer); + $mail->send($this->mailable); + + /* Count the amount of emails sent across all the users accounts */ + Cache::increment($this->company->account->key); + + LightLogs::create(new EmailSuccess($this->company->company_key)) + ->send(); + + } + catch(\Symfony\Component\Mime\Exception\RfcComplianceException $e) { + nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); + $this->fail(); + $this->cleanUpMailers(); + $this->logMailError($e->getMessage(), $this->company->clients()->first()); + return; + } + catch(\Symfony\Component\Mime\Exception\LogicException $e){ + nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); + $this->fail(); + $this->cleanUpMailers(); + $this->logMailError($e->getMessage(), $this->company->clients()->first()); + return; + } + catch (\Exception | \Google\Service\Exception $e) { + + nlog("Mailer failed with {$e->getMessage()}"); + $message = $e->getMessage(); + + /** + * Post mark buries the proper message in a a guzzle response + * this merges a text string with a json object + * need to harvest the ->Message property using the following + */ + if(stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) + { + + $message = "Either Attachment too large, or recipient has been suppressed."; + + $this->fail(); + $this->logMailError($e->getMessage(), $this->company->clients()->first()); + $this->cleanUpMailers(); + + return; + + } + + //only report once, not on all tries + if($this->attempts() == $this->tries) + { + + /* If the is an entity attached to the message send a failure mailer */ + if($this->nmo->entity) + $this->entityEmailFailed($message); + + /* Don't send postmark failures to Sentry */ + if(Ninja::isHosted() && (!$e instanceof ClientException)) + app('sentry')->captureException($e); + + } + + /* Releasing immediately does not add in the backoff */ + $this->release($this->backoff()[$this->attempts()-1]); + + } + } + + public function backoff() + { + return [5, 10, 30, 240]; + } + + public function failed($exception = null) + { + + config(['queue.failed.driver' => null]); + + } } diff --git a/app/Services/Email/MailMailable.php b/app/Services/Email/MailMailable.php new file mode 100644 index 000000000000..d88a6a62ded9 --- /dev/null +++ b/app/Services/Email/MailMailable.php @@ -0,0 +1,107 @@ +mail_object->subject, + tags: [$this->mail_object->company_key], + replyTo: $this->mail_object->reply_to, + from: $this->mail_object->from, + to: $this->mail_object->to, + bcc: $this->mail_object->bcc + ); + } + + /** + * Get the message content definition. + * + * @return \Illuminate\Mail\Mailables\Content + */ + public function content() + { + return new Content( + view: $this->mail_object->html_template, + text: $this->mail_object->text_template, + with: [ + 'text_body' => strip_tags($this->mail_object->body), //@todo this is a bit hacky here. + 'body' => $this->mail_object->body, + 'settings' => $this->mail_object->settings, + 'whitelabel' => $this->mail_object->whitelabel, + 'logo' => $this->mail_object->logo, + 'signature' => $this->mail_object->signature, + 'company' => $this->mail_object->company, + 'greeting' => '' + ] + ); + } + + /** + * Get the attachments for the message. + * + * @return array + */ + public function attachments() + { + + $attachments = []; + + foreach($this->mail_object->attachments as $file) + { + $attachments[] = Attachment::fromData(fn () => base64_decode($file['file']), $file['name']); + } + + return $attachments; + + } + + /** + * Get the message headers. + * + * @return \Illuminate\Mail\Mailables\Headers + */ + public function headers() + { + + return new Headers( + messageId: null, + references: [], + text: $this->mail_object->headers, + ); + + } + +} diff --git a/app/Services/Email/MailObject.php b/app/Services/Email/MailObject.php index f9467866d60c..8cb9f4abc723 100644 --- a/app/Services/Email/MailObject.php +++ b/app/Services/Email/MailObject.php @@ -11,6 +11,7 @@ namespace App\Services\Email; +use App\Models\Company; use Illuminate\Mail\Mailables\Address; /** @@ -77,11 +78,12 @@ class MailObject public array $variables = []; - public ?string $reminder_template = null; + public ?string $template = null; public ?string $template_data = null; public bool $override = false; + public ?Company $company = null; } \ No newline at end of file diff --git a/app/Transformers/CompanyUserTransformer.php b/app/Transformers/CompanyUserTransformer.php index e71eed9ad542..6a0643d11b9c 100644 --- a/app/Transformers/CompanyUserTransformer.php +++ b/app/Transformers/CompanyUserTransformer.php @@ -44,6 +44,7 @@ class CompanyUserTransformer extends EntityTransformer 'permissions' => $company_user->permissions ?: '', 'notifications' => $company_user->notifications ? (object) $company_user->notifications : $blank_obj, 'settings' => $company_user->settings ? (object) $company_user->settings : $blank_obj, + 'react_settings' => $company_user->react_settings ? (object) $company_user->react_settings : $blank_obj, 'is_owner' => (bool) $company_user->is_owner, 'is_admin' => (bool) $company_user->is_admin, 'is_locked' => (bool) $company_user->is_locked, diff --git a/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php b/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php new file mode 100644 index 000000000000..281b7d8e4c9d --- /dev/null +++ b/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php @@ -0,0 +1,34 @@ +mediumText('react_settings')->nullable(); + + \Illuminate\Support\Facades\Artisan::call('ninja:design-update'); + + }); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + + } +}; From 5b5458d70add736a1b48e6eabd95d1e33e50e4b9 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 14 Feb 2023 22:50:20 +1100 Subject: [PATCH 07/72] Testing mailers --- app/Services/Email/MailEntity.php | 147 ++++++++++++++++++++++++------ 1 file changed, 120 insertions(+), 27 deletions(-) diff --git a/app/Services/Email/MailEntity.php b/app/Services/Email/MailEntity.php index 4b56f70ba719..820f26ac9b54 100644 --- a/app/Services/Email/MailEntity.php +++ b/app/Services/Email/MailEntity.php @@ -32,30 +32,30 @@ class MailEntity implements ShouldQueue public Company $company; - public int $tries = 4; - - public ?string $client_postmark_secret = null; - - public ?string $client_mailgun_secret = null; - - public ?string $client_mailgun_domain = null; - - public bool $override = false; - - public $deleteWhenMissingModels = true; - - private string $mailer = ''; - - public $invitation; - - public Mail $mail; - - private ?string $db; - public MailObject $mail_object; public Mailable $mailable; + + public Mail $mail; + public ?string $client_postmark_secret = null; + + public ?string $client_mailgun_secret = null; + + public ?string $client_mailgun_domain = null; + + public bool $override = false; + + private string $mailer = ''; + + public $invitation; + + private ?string $db; + + public int $tries = 4; + + public $deleteWhenMissingModels = true; + public function __construct($invitation, $db, $mail_object) { @@ -73,22 +73,26 @@ class MailEntity implements ShouldQueue public function handle(): void { - $builder = new MailBuild($this); - + MultiDB::setDb($this->db); - + $this->companyCheck(); + + $builder = new MailBuild($this); //construct mailable $builder->run($this); $this->mailable = $builder->getMailable(); + //spam checks + if($this->preFlightChecksFail()) + return; + $this->setMailDriver() ->trySending(); - //spam checks - + //what do we pass into a generaic builder? //construct mailer @@ -265,7 +269,7 @@ class MailEntity implements ShouldQueue { /* If the is an entity attached to the message send a failure mailer */ - if($this->nmo->entity) + if($this->mail_object->entity_id) $this->entityEmailFailed($message); /* Don't send postmark failures to Sentry */ @@ -280,13 +284,102 @@ class MailEntity implements ShouldQueue } } + /** + * On the hosted platform we scan all outbound email for + * spam. This sequence processes the filters we use on all + * emails. + */ + public function preFlightChecksFail(): bool + { + + /* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */ + if($this->hasInValidEmails()) + return true; + + /* GMail users are uncapped */ + if(in_array($this->mail_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun'])) + return false; + + /* On the hosted platform, if the user is over the email quotas, we do not send the email. */ + if($this->company->account && $this->company->account->emailQuotaExceeded()) + return true; + + /* If the account is verified, we allow emails to flow */ + if($this->company->account && $this->company->account->is_verified_account) { + + //11-01-2022 + + /* Continue to analyse verified accounts in case they later start sending poor quality emails*/ + // if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) + // (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run(); + + // return false; + } + + + /* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */ + if($this->company->account && !$this->company->account->account_sms_verified){ + + if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) + (new \Modules\Admin\Jobs\Account\EmailFilter($this->mail_object, $this->company))->run(); + + return true; + + } + + /* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */ + if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) + (new \Modules\Admin\Jobs\Account\EmailFilter($this->mail_object, $this->company))->run(); + + return false; + + } + + + /** + * Checks if emails are have some illegal / required characters. + * + * @return bool + */ + private function hasInValidEmails(): bool + { + + foreach($this->mail_object->to as $address_object) + { + + if(strpos($address_object->address, '@example.com') !== false) + return true; + + if(!str_contains($address_object->address, "@")) + return true; + + if($address_object->address == " ") + return true; + } + + + return false; + } + + /** + * Backoff time + * + * @return void + */ public function backoff() { return [5, 10, 30, 240]; } - + + /** + * Failed handler + * + * @param mixed $exception + * @return void + */ public function failed($exception = null) { + nlog("dying now"); config(['queue.failed.driver' => null]); From 4c7a7e4c05e79537b05cde6a4367745ffa211589 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Tue, 14 Feb 2023 23:31:12 +1100 Subject: [PATCH 08/72] doc blocks for entity mailers --- app/Services/Email/MailBuild.php | 53 +++-- app/Services/Email/MailEntity.php | 374 +++++++++++++++++++++++------- 2 files changed, 331 insertions(+), 96 deletions(-) diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index be5f68bc1ad3..f1855284f114 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -16,6 +16,9 @@ use App\Models\Client; use App\Models\Vendor; use App\Models\Account; use App\Utils\HtmlEngine; +use App\Models\ClientContact; +use App\Models\VendorContact; +use App\Utils\VendorHtmlEngine; use Illuminate\Support\Facades\App; use App\Services\Email\MailMailable; use Illuminate\Mail\Mailables\Address; @@ -44,7 +47,12 @@ class MailBuild /** @var mixed $vendor */ private ?Vendor $vendor; + + /** @var mixed $html_engine */ + private mixed $html_engine; + /** @var mixed $variables */ + private array $variables = []; /** * __construct * @@ -61,11 +69,9 @@ class MailBuild public function run(): self { //resolve settings, if client existing - use merged - else default to company - $this->settings = $this->mail_entity->company->settings; - $this->mail_entity->mail_object->settings = $this->settings; - $this->resolveEntities() ->setLocale() + ->setMetaData() ->setFrom() ->setTo() ->setTemplate() @@ -74,7 +80,6 @@ class MailBuild ->setReplyTo() ->setBcc() ->setAttachments() - ->setMetaData() ->setVariables(); return $this; @@ -98,10 +103,14 @@ class MailBuild private function resolveEntities(): self { - $this->client = $this->mail_entity->mail_object->client_id ? Client::find($this->mail_entity->mail_object->client_id) : null; + $client_contact = $this->mail_entity?->invitation?->client_contact_id ? ClientContact::withTrashed()->find($this->mail_entity->invitation->client_contact_id) : null; - $this->vendor = $this->mail_entity->mail_object->vendor_id ? Vendor::find($this->mail_entity->mail_object->vendor_id) : null; + $this->client = $client_contact?->client; + + $vendor_contact = $this->mail_entity?->invitation?->vendor_contact_id ? VendorContact::withTrashed()->find($this->mail_entity->invitation->vendor_contact_id) : null; + $this->vendor = $vendor_contact?->vendor; + return $this; } @@ -127,9 +136,10 @@ class MailBuild } - /** * Sets the locale + * Sets the settings object depending on context + * Sets the HTML variables depending on context * * @return self */ @@ -137,14 +147,31 @@ class MailBuild { if($this->client){ + $this->locale = $this->client->locale(); $this->settings = $this->client->getMergedSettings(); - $this->mail_entity->mail_object->settings = $this->settings; + + if($this->mail_entity->invitation) + $this->variables = (new HtmlEngine($this->mail_entity->invitation))->makeValues(); + } - elseif($this->vendor) + elseif($this->vendor){ + $this->locale = $this->vendor->locale(); - else + $this->settings = $this->mail_entity->company->settings; + + if($this->mail_entity->invitation) + $this->variables = (new VendorHtmlEngine($this->mail_entity->invitation))->makeValues(); + + + } + else{ $this->locale = $this->mail_entity->company->locale(); + $this->settings = $this->mail_entity->company->settings; + } + + $this->mail_entity->mail_object->settings = $this->settings; + App::setLocale($this->locale); App::forgetInstance('translator'); @@ -318,10 +345,8 @@ class MailBuild $this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $this->mail_entity->mail_object->variables); } - $variables = (new HtmlEngine($this->mail_entity->invitation))->makeValues(); - - $this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $variables); - $this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $variables); + $this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $this->variables); + $this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $this->variables); if($this->template != 'custom') $this->mail_entity->mail_object->body = $this->parseMarkdownToHtml($this->mail_entity->mail_object->body); diff --git a/app/Services/Email/MailEntity.php b/app/Services/Email/MailEntity.php index 820f26ac9b54..f0e24133f7e3 100644 --- a/app/Services/Email/MailEntity.php +++ b/app/Services/Email/MailEntity.php @@ -11,29 +11,31 @@ namespace App\Services\Email; +use App\Models\User; use App\Utils\Ninja; use App\Models\Company; use App\Libraries\MultiDB; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; +use App\Utils\Traits\MakesHash; +use App\Libraries\Google\Google; use App\Services\Email\MailBuild; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Cache; use Illuminate\Queue\SerializesModels; use Turbo124\Beacon\Facades\LightLogs; use Illuminate\Queue\InteractsWithQueue; +use GuzzleHttp\Exception\ClientException; use App\DataMapper\Analytics\EmailSuccess; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; class MailEntity implements ShouldQueue { - use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; + use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, MakesHash; public Company $company; - public MailObject $mail_object; - public Mailable $mailable; public Mail $mail; @@ -48,73 +50,44 @@ class MailEntity implements ShouldQueue private string $mailer = ''; - public $invitation; - - private ?string $db; - public int $tries = 4; public $deleteWhenMissingModels = true; - public function __construct($invitation, $db, $mail_object) - { - - $this->invitation = $invitation; - - $this->company = $invitation->company; - - $this->db = $db; - - $this->mail_object = $mail_object; - - $this->override = $mail_object->override; - - } - + public function __construct(public mixed $invitation, private ?string $db, public MailObject $mail_object){} + + /** + * Handle the job + * + * @return void + */ public function handle(): void { - + MultiDB::setDb($this->db); - - $this->companyCheck(); - + + /* Where there are no invitations, we need to harvest the company and also use the correct context to build the mailable*/ + $this->company = $this->invitation->company; + + $this->override = $this->mail_object->override; + $builder = new MailBuild($this); - //construct mailable + /* Construct Mailable */ $builder->run($this); $this->mailable = $builder->getMailable(); - //spam checks + /* Email quality checks */ if($this->preFlightChecksFail()) return; + /* Try sending email */ $this->setMailDriver() ->trySending(); - - //what do we pass into a generaic builder? - - //construct mailer - } - - public function companyCheck(): void - { - /* Handle bad state */ - if(!$this->company) - $this->fail(); - - /* Handle deactivated company */ - if($this->company->is_disabled && !$this->override) - $this->fail(); - - /* To handle spam users we drop all emails from flagged accounts */ - if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) - $this->fail(); - - } - + public function configureMailer(): self { $this->setMailDriver(); @@ -136,22 +109,22 @@ class MailEntity implements ShouldQueue case 'default': $this->mailer = config('mail.default'); break; - // case 'gmail': - // $this->mailer = 'gmail'; - // $this->setGmailMailer(); - // return $this; - // case 'office365': - // $this->mailer = 'office365'; - // $this->setOfficeMailer(); - // return $this; - // case 'client_postmark': - // $this->mailer = 'postmark'; - // $this->setPostmarkMailer(); - // return $this; - // case 'client_mailgun': - // $this->mailer = 'mailgun'; - // $this->setMailgunMailer(); - // return $this; + case 'gmail': + $this->mailer = 'gmail'; + $this->setGmailMailer(); + return $this; + case 'office365': + $this->mailer = 'office365'; + $this->setOfficeMailer(); + return $this; + case 'client_postmark': + $this->mailer = 'postmark'; + $this->setPostmarkMailer(); + return $this; + case 'client_mailgun': + $this->mailer = 'mailgun'; + $this->setMailgunMailer(); + return $this; default: break; @@ -208,14 +181,18 @@ class MailEntity implements ShouldQueue $this->client_mailgun_domain = false; - //always dump the drivers to prevent reuse app('mail.manager')->forgetMailers(); } - - public function trySending() + + /** + * Attempts to send the email + * + * @return void + */ + public function trySending(): void { - try { + try { $mail = Mail::mailer($this->mailer); $mail->send($this->mailable); @@ -231,14 +208,14 @@ class MailEntity implements ShouldQueue nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); $this->fail(); $this->cleanUpMailers(); - $this->logMailError($e->getMessage(), $this->company->clients()->first()); + // $this->logMailError($e->getMessage(), $this->company->clients()->first()); return; } catch(\Symfony\Component\Mime\Exception\LogicException $e){ nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); $this->fail(); $this->cleanUpMailers(); - $this->logMailError($e->getMessage(), $this->company->clients()->first()); + // $this->logMailError($e->getMessage(), $this->company->clients()->first()); return; } catch (\Exception | \Google\Service\Exception $e) { @@ -257,7 +234,7 @@ class MailEntity implements ShouldQueue $message = "Either Attachment too large, or recipient has been suppressed."; $this->fail(); - $this->logMailError($e->getMessage(), $this->company->clients()->first()); + // $this->logMailError($e->getMessage(), $this->company->clients()->first()); $this->cleanUpMailers(); return; @@ -270,7 +247,7 @@ class MailEntity implements ShouldQueue /* If the is an entity attached to the message send a failure mailer */ if($this->mail_object->entity_id) - $this->entityEmailFailed($message); + // $this->entityEmailFailed($message); /* Don't send postmark failures to Sentry */ if(Ninja::isHosted() && (!$e instanceof ClientException)) @@ -291,6 +268,17 @@ class MailEntity implements ShouldQueue */ public function preFlightChecksFail(): bool { + /* Handle bad state */ + if(!$this->company) + return true; + + /* Handle deactivated company */ + if($this->company->is_disabled && !$this->override) + return true; + + /* To handle spam users we drop all emails from flagged accounts */ + if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) + return true; /* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */ if($this->hasInValidEmails()) @@ -301,19 +289,19 @@ class MailEntity implements ShouldQueue return false; /* On the hosted platform, if the user is over the email quotas, we do not send the email. */ - if($this->company->account && $this->company->account->emailQuotaExceeded()) + if(Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded()) return true; /* If the account is verified, we allow emails to flow */ - if($this->company->account && $this->company->account->is_verified_account) { + if(Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) { //11-01-2022 /* Continue to analyse verified accounts in case they later start sending poor quality emails*/ // if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) - // (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run(); + // (new \Modules\Admin\Jobs\Account\EmailQuality($this->mail_object, $this->company))->run(); - // return false; + return false; } @@ -343,6 +331,8 @@ class MailEntity implements ShouldQueue */ private function hasInValidEmails(): bool { + if(Ninja::isSelfHost()) + return false; foreach($this->mail_object->to as $address_object) { @@ -360,7 +350,230 @@ class MailEntity implements ShouldQueue return false; } - + + + /** + * Check to ensure no cross account + * emails can be sent. + * + * @param User $user + */ + private function checkValidSendingUser($user) + { + /* Always ensure the user is set on the correct account */ + if($user->account_id != $this->company->account_id){ + + $this->mail_object->settings->email_sending_method = 'default'; + return $this->setMailDriver(); + } + } + + /** + * Resolves the sending user + * when configuring the Mailer + * on behalf of the client + * + * @return User $user + */ + private function resolveSendingUser(): ?User + { + $sending_user = $this->mail_object->settings->gmail_sending_user_id; + + if($sending_user == "0") + $user = $this->company->owner(); + else + $user = User::find($this->decodePrimaryKey($sending_user)); + + return $user; + } + + /** + * Configures Mailgun using client supplied secret + * as the Mailer + */ + private function setMailgunMailer() + { + if(strlen($this->mail_object->settings->mailgun_secret) > 2 && strlen($this->mail_object->settings->mailgun_domain) > 2){ + $this->client_mailgun_secret = $this->mail_object->settings->mailgun_secret; + $this->client_mailgun_domain = $this->mail_object->settings->mailgun_domain; + } + else{ + $this->mail_object->settings->email_sending_method = 'default'; + return $this->setMailDriver(); + } + + $user = $this->resolveSendingUser(); + + $sending_email = (isset($this->mail_object->settings->custom_sending_email) && stripos($this->mail_object->settings->custom_sending_email, "@")) ? $this->mail_object->settings->custom_sending_email : $user->email; + $sending_user = (isset($this->mail_object->settings->email_from_name) && strlen($this->mail_object->settings->email_from_name) > 2) ? $this->mail_object->settings->email_from_name : $user->name(); + + $this->mailable + ->from($sending_email, $sending_user); + } + + /** + * Configures Postmark using client supplied secret + * as the Mailer + */ + private function setPostmarkMailer() + { + if(strlen($this->mail_object->settings->postmark_secret) > 2){ + $this->client_postmark_secret = $this->mail_object->settings->postmark_secret; + } + else{ + $this->mail_object->settings->email_sending_method = 'default'; + return $this->setMailDriver(); + } + + $user = $this->resolveSendingUser(); + + $sending_email = (isset($this->mail_object->settings->custom_sending_email) && stripos($this->mail_object->settings->custom_sending_email, "@")) ? $this->mail_object->settings->custom_sending_email : $user->email; + $sending_user = (isset($this->mail_object->settings->email_from_name) && strlen($this->mail_object->settings->email_from_name) > 2) ? $this->mail_object->settings->email_from_name : $user->name(); + + $this->mailable + ->from($sending_email, $sending_user); + } + + /** + * Configures Microsoft via Oauth + * as the Mailer + */ + private function setOfficeMailer() + { + $user = $this->resolveSendingUser(); + + $this->checkValidSendingUser($user); + + nlog("Sending via {$user->name()}"); + + $token = $this->refreshOfficeToken($user); + + if($token) + { + $user->oauth_user_token = $token; + $user->save(); + + } + else { + + $this->mail_object->settings->email_sending_method = 'default'; + return $this->setMailDriver(); + + } + + $this->mailable + ->from($user->email, $user->name()) + ->withSymfonyMessage(function ($message) use($token) { + $message->getHeaders()->addTextHeader('gmailtoken', $token); + }); + + } + + /** + * Configures GMail via Oauth + * as the Mailer + */ + private function setGmailMailer() + { + + $user = $this->resolveSendingUser(); + + $this->checkValidSendingUser($user); + + nlog("Sending via {$user->name()}"); + + $google = (new Google())->init(); + + try{ + + if ($google->getClient()->isAccessTokenExpired()) { + $google->refreshToken($user); + $user = $user->fresh(); + } + + $google->getClient()->setAccessToken(json_encode($user->oauth_user_token)); + + } + catch(\Exception $e) { + // $this->logMailError('Gmail Token Invalid', $this->company->clients()->first()); + $this->mail_object->settings->email_sending_method = 'default'; + return $this->setMailDriver(); + } + + /** + * If the user doesn't have a valid token, notify them + */ + + if(!$user->oauth_user_token) { + $this->company->account->gmailCredentialNotification(); + $this->mail_object->settings->email_sending_method = 'default'; + return $this->setMailDriver(); + } + + /* + * Now that our token is refreshed and valid we can boot the + * mail driver at runtime and also set the token which will persist + * just for this request. + */ + + $token = $user->oauth_user_token->access_token; + + if(!$token) { + $this->company->account->gmailCredentialNotification(); + $this->mail_object->settings->email_sending_method = 'default'; + return $this->setMailDriver(); + } + + $this->mailable + ->from($user->email, $user->name()) + ->withSymfonyMessage(function ($message) use($token) { + $message->getHeaders()->addTextHeader('gmailtoken', $token); + }); + + } + + /** + * Attempts to refresh the Microsoft refreshToken + * + * @param App\Models\User + * @return string | boool + */ + private function refreshOfficeToken($user) + { + $expiry = $user->oauth_user_token_expiry ?: now()->subDay(); + + if($expiry->lt(now())) + { + $guzzle = new \GuzzleHttp\Client(); + $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'; + + $token = json_decode($guzzle->post($url, [ + 'form_params' => [ + 'client_id' => config('ninja.o365.client_id') , + 'client_secret' => config('ninja.o365.client_secret') , + 'scope' => 'email Mail.Send offline_access profile User.Read openid', + 'grant_type' => 'refresh_token', + 'refresh_token' => $user->oauth_user_refresh_token + ], + ])->getBody()->getContents()); + + if($token){ + + $user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token; + $user->oauth_user_token = $token->access_token; + $user->oauth_user_token_expiry = now()->addSeconds($token->expires_in); + $user->save(); + + return $token->access_token; + } + + return false; + } + + return $user->oauth_user_token; + + } + /** * Backoff time * @@ -379,9 +592,6 @@ class MailEntity implements ShouldQueue */ public function failed($exception = null) { - nlog("dying now"); - config(['queue.failed.driver' => null]); - } } From 2db527efe0d9a3bbf3209f187f66faafbfa1c9e9 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 00:01:55 +1100 Subject: [PATCH 09/72] doc blocks for entity mailers --- app/Services/Email/MailBuild.php | 165 ++++++++++++++++++++++-------- app/Services/Email/MailObject.php | 2 + 2 files changed, 124 insertions(+), 43 deletions(-) diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index f1855284f114..c1966562a3b4 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -19,44 +19,47 @@ use App\Utils\HtmlEngine; use App\Models\ClientContact; use App\Models\VendorContact; use App\Utils\VendorHtmlEngine; +use App\Jobs\Entity\CreateRawPdf; use Illuminate\Support\Facades\App; +use Illuminate\Support\Facades\URL; use App\Services\Email\MailMailable; use Illuminate\Mail\Mailables\Address; use Illuminate\Contracts\Mail\Mailable; use App\DataMapper\EmailTemplateDefaults; use League\CommonMark\CommonMarkConverter; +use App\Jobs\Vendor\CreatePurchaseOrderPdf; class MailBuild { - - /** - * settings - * - * @var mixed - */ + + /** @var mixed $settings */ protected $settings; - /** @var mixed $template */ + /** @var string $template */ private string $template; - /** @var mixed $locale */ + /** @var string $locale */ private string $locale; - /** @var mixed $client */ + /** @var ?Client $client */ private ?Client $client; - /** @var mixed $vendor */ + /** @var ?Vendor $vendor */ private ?Vendor $vendor; /** @var mixed $html_engine */ private mixed $html_engine; - /** @var mixed $variables */ + /** @var array $variables */ private array $variables = []; + + /** @var int $max_attachment_size */ + public int $max_attachment_size = 3000000; + /** * __construct * - * @param mixed $mail_entity + * @param MailEntity $mail_entity * @return void */ public function __construct(public MailEntity $mail_entity){} @@ -92,7 +95,7 @@ class MailBuild */ public function getMailable(): Mailable { - return new MailMailable($this->mail_entity->mail_object); //todo current depends on EmailObject + return new MailMailable($this->mail_entity->mail_object); } /** @@ -114,28 +117,6 @@ class MailBuild return $this; } - /** - * Sets the meta data for the Email object - * - * @return self - */ - private function setMetaData(): self - { - - $this->mail_entity->mail_object->company_key = $this->mail_entity->company->company_key; - - $this->mail_entity->mail_object->logo = $this->mail_entity->company->present()->logo(); - - $this->mail_entity->mail_object->signature = $this->mail_entity->mail_object->signature ?: $this->settings->email_signature; - - $this->mail_entity->mail_object->whitelabel = $this->mail_entity->company->account->isPaid() ? true : false; - - $this->mail_entity->mail_object->company = $this->mail_entity->company; - - return $this; - - } - /** * Sets the locale * Sets the settings object depending on context @@ -166,13 +147,14 @@ class MailBuild } else{ + $this->locale = $this->mail_entity->company->locale(); $this->settings = $this->mail_entity->company->settings; + } $this->mail_entity->mail_object->settings = $this->settings; - App::setLocale($this->locale); App::forgetInstance('translator'); $t = app('translator'); @@ -181,6 +163,28 @@ class MailBuild return $this; } + /** + * Sets the meta data for the Email object + * + * @return self + */ + private function setMetaData(): self + { + + $this->mail_entity->mail_object->company_key = $this->mail_entity->company->company_key; + + $this->mail_entity->mail_object->logo = $this->mail_entity->company->present()->logo(); + + $this->mail_entity->mail_object->signature = $this->mail_entity->mail_object->signature ?: $this->settings->email_signature; + + $this->mail_entity->mail_object->whitelabel = $this->mail_entity->company->account->isPaid() ? true : false; + + $this->mail_entity->mail_object->company = $this->mail_entity->company; + + return $this; + + } + /** * Sets the template * @@ -209,8 +213,12 @@ class MailBuild */ private function setTo(): self { - $this->mail_entity->mail_object->to = [new Address($this->mail_entity->invitation->contact->email, $this->mail_entity->invitation->contact->present()->name())]; - + + $this->mail_entity->mail_object->to = array_merge( + $this->mail_entity->mail_object->to , + [new Address($this->mail_entity->invitation->contact->email, $this->mail_entity->invitation->contact->present()->name())] + ); + return $this; } @@ -293,24 +301,95 @@ class MailBuild */ private function setAttachments(): self { - $attachments = []; + $this->setContextAttachments(); if ($this->settings->document_email_attachment && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { foreach ($this->mail_entity->company->documents as $document) { - $attachments[] = ['file' => base64_encode($document->getFile()), 'name' => $document->name]; + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['file' => base64_encode($document->getFile()), 'name' => $document->name]); } } - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, $attachments); - return $this; } + + /** + * Depending on context we may need to resolve the + * attachment dependencies. + * + * ie. Resolve the entity. + * ie. Resolve if we should attach the Entity PDF + * ie. Create the Entity PDF + * ie. Inject the PDF + * + * @return array + */ + private function setContextAttachments(): self + { + if(!$this->settings->pdf_email_attachment || !$this->mail_entity->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) + return []; + + if($this->mail_entity->invitation?->purchase_order){ + + $pdf = (new CreatePurchaseOrderPdf($this->mail_entity->invitation))->rawPdf(); + + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->purchase_order->numberFormatter().'.pdf']); + + if ($this->vendor->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { + + // Storage::url + foreach ($this->mail_entity->invitation->purchase_order->documents as $document) { + + if($document->size > $this->max_attachment_size) + $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [" $document->hash]) ."'>". $document->name .""]); + else + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]); + + } + } + + return $this; + + } + + if($this->mail_entity->invitation?->invoice) + $entity = 'invoice'; + + if($this->mail_entity->invitation?->quote) + $entity = 'quote'; + + if($this->mail_entity->invitation?->credit) + $entity = 'credit'; + + $pdf = ((new CreateRawPdf($this->mail_entity->invitation, $this->mail_entity->invitation->company->db))->handle()); + + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->{$entity}->numberFormatter().'.pdf']); + + if ($this->client->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { + + // Storage::url + foreach ($this->mail_entity->invitation->{$entity}->documents as $document) { + + if($document->size > $this->max_attachment_size) + $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [" $document->hash]) ."'>". $document->name .""]); + else + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]); + + } + } + + if($this->settings->pdf_email_attachment && $entity == 'invoice') + { + + } + + return $this; + } /** @@ -338,7 +417,6 @@ class MailBuild */ public function setVariables(): self { - if($this->mail_entity->mail_object->variables){ $this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $this->mail_entity->mail_object->variables); @@ -352,6 +430,7 @@ class MailBuild $this->mail_entity->mail_object->body = $this->parseMarkdownToHtml($this->mail_entity->mail_object->body); return $this; + } /** diff --git a/app/Services/Email/MailObject.php b/app/Services/Email/MailObject.php index 8cb9f4abc723..8f31f10a71df 100644 --- a/app/Services/Email/MailObject.php +++ b/app/Services/Email/MailObject.php @@ -38,6 +38,8 @@ class MailObject public array $attachments = []; + public array $attachment_links = []; + public string $company_key; public ?object $settings = null; From 2d3fe13c8253e8a91f6d08484a19d7cfee1a1dc5 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 00:30:16 +1100 Subject: [PATCH 10/72] doc blocks for entity mailers --- app/Mail/Engine/InvoiceEmailEngine.php | 2 +- app/Services/Email/MailBuild.php | 89 ++++++++++++++++++++++---- 2 files changed, 78 insertions(+), 13 deletions(-) diff --git a/app/Mail/Engine/InvoiceEmailEngine.php b/app/Mail/Engine/InvoiceEmailEngine.php index cf326986bdbf..46b13aabcec3 100644 --- a/app/Mail/Engine/InvoiceEmailEngine.php +++ b/app/Mail/Engine/InvoiceEmailEngine.php @@ -212,7 +212,7 @@ class InvoiceEmailEngine extends BaseEmailEngine }); } } - } + return $this; } diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index c1966562a3b4..cc1e388c197f 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -11,10 +11,12 @@ namespace App\Services\Email; +use App\Models\Task; use App\Utils\Ninja; use App\Models\Client; use App\Models\Vendor; use App\Models\Account; +use App\Models\Expense; use App\Utils\HtmlEngine; use App\Models\ClientContact; use App\Models\VendorContact; @@ -28,10 +30,12 @@ use Illuminate\Contracts\Mail\Mailable; use App\DataMapper\EmailTemplateDefaults; use League\CommonMark\CommonMarkConverter; use App\Jobs\Vendor\CreatePurchaseOrderPdf; +use App\Utils\Traits\MakesHash; class MailBuild { - + use MakesHash; + /** @var mixed $settings */ protected $settings; @@ -326,19 +330,19 @@ class MailBuild * ie. Create the Entity PDF * ie. Inject the PDF * - * @return array + * @return self */ private function setContextAttachments(): self { if(!$this->settings->pdf_email_attachment || !$this->mail_entity->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) - return []; + return $this; if($this->mail_entity->invitation?->purchase_order){ $pdf = (new CreatePurchaseOrderPdf($this->mail_entity->invitation))->rawPdf(); - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->purchase_order->numberFormatter().'.pdf']); + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->purchase_order->numberFormatter().'.pdf']]); if ($this->vendor->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { @@ -346,9 +350,9 @@ class MailBuild foreach ($this->mail_entity->invitation->purchase_order->documents as $document) { if($document->size > $this->max_attachment_size) - $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [" $document->hash]) ."'>". $document->name .""]); + $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); else - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]); + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); } } @@ -365,10 +369,12 @@ class MailBuild if($this->mail_entity->invitation?->credit) $entity = 'credit'; - - $pdf = ((new CreateRawPdf($this->mail_entity->invitation, $this->mail_entity->invitation->company->db))->handle()); - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->{$entity}->numberFormatter().'.pdf']); + $pdf = ((new CreateRawPdf($this->mail_entity->invitation, $this->mail_entity->invitation->company->db))->handle()); + + nlog($this->mail_entity->mail_object->attachments); + + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->{$entity}->numberFormatter().'.pdf']]); if ($this->client->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { @@ -376,19 +382,78 @@ class MailBuild foreach ($this->mail_entity->invitation->{$entity}->documents as $document) { if($document->size > $this->max_attachment_size) - $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [" $document->hash]) ."'>". $document->name .""]); + $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); else - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]); + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); } } - if($this->settings->pdf_email_attachment && $entity == 'invoice') + return $this; + + + + + if($this->settings->ubl_email_attachment && $entity == 'invoice') { } + if($entity == 'invoice') + { + + $line_items = $this->mail_entity->invitation->invoice->line_items; + + foreach ($line_items as $item) { + $expense_ids = []; + + if (property_exists($item, 'expense_id')) { + $expense_ids[] = $item->expense_id; + } + + if (count($expense_ids) > 0) { + $expenses = Expense::whereIn('id', $this->transformKeys($expense_ids)) + ->where('invoice_documents', 1) + ->cursor() + ->each(function ($expense) { + foreach ($expense->documents as $document) { + + if($document->size > $this->max_attachment_size) + $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); + else + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); + + + } + }); + } + + $task_ids = []; + + if (property_exists($item, 'task_id')) { + $task_ids[] = $item->task_id; + } + + if (count($task_ids) > 0 && $this->mail_entity->company->invoice_task_documents) { + $tasks = Task::whereIn('id', $this->transformKeys($task_ids)) + ->cursor() + ->each(function ($task) { + foreach ($task->documents as $document) { + + if($document->size > $this->max_attachment_size) + $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); + else + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); + + } + }); + } + } + } + + return $this; + } From 32363d85ca8e0c605f39a1da722a4233fc4bb09c Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 00:39:38 +1100 Subject: [PATCH 11/72] Attaching documents --- app/Services/Email/MailBuild.php | 56 ++++++++++++-------------------- 1 file changed, 21 insertions(+), 35 deletions(-) diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index cc1e388c197f..8799c7472c42 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -309,11 +309,7 @@ class MailBuild if ($this->settings->document_email_attachment && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - foreach ($this->mail_entity->company->documents as $document) { - - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, ['file' => base64_encode($document->getFile()), 'name' => $document->name]); - - } + $this->attachDocuments($this->mail_entity->company->documents); } @@ -321,6 +317,21 @@ class MailBuild } + private function attachDocuments($documents): self + { + + foreach ($documents as $document) { + + if($document->size > $this->max_attachment_size) + $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); + else + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments,[['file' => base64_encode($document->getFile()), 'name' => $document->name]]); + + } + + return $this; + } + /** * Depending on context we may need to resolve the * attachment dependencies. @@ -346,15 +357,8 @@ class MailBuild if ($this->vendor->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - // Storage::url - foreach ($this->mail_entity->invitation->purchase_order->documents as $document) { - - if($document->size > $this->max_attachment_size) - $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); - else - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); + $this->attachDocuments($this->mail_entity->invitation->purchase_order->documents); - } } return $this; @@ -378,15 +382,8 @@ class MailBuild if ($this->client->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - // Storage::url - foreach ($this->mail_entity->invitation->{$entity}->documents as $document) { - - if($document->size > $this->max_attachment_size) - $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); - else - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); - - } + $this->attachDocuments($this->mail_entity->invitation->{$entity}->documents); + } return $this; @@ -416,15 +413,9 @@ class MailBuild ->where('invoice_documents', 1) ->cursor() ->each(function ($expense) { - foreach ($expense->documents as $document) { - if($document->size > $this->max_attachment_size) - $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); - else - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); + $this->attachDocuments($expense->documents); - - } }); } @@ -438,14 +429,9 @@ class MailBuild $tasks = Task::whereIn('id', $this->transformKeys($task_ids)) ->cursor() ->each(function ($task) { - foreach ($task->documents as $document) { - if($document->size > $this->max_attachment_size) - $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); - else - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); + $this->attachDocuments($task->documents); - } }); } } From 5617e5708cfb1f4649dfbbdfc1c0461ceccd0374 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 07:41:21 +1100 Subject: [PATCH 12/72] Remove predis 2 --- app/PaymentDrivers/BaseDriver.php | 10 ++ composer.json | 2 +- composer.lock | 274 +++++++++++++++--------------- 3 files changed, 147 insertions(+), 139 deletions(-) diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index 9f5c2cf8cee5..af1ba7d446ee 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -99,6 +99,16 @@ class BaseDriver extends AbstractPaymentDriver * @return array[] */ + public function init() + { + return $this; + } + + public function updateCustomer() + { + return $this; + } + public function getClientRequiredFields(): array { $fields = []; diff --git a/composer.json b/composer.json index e8141b11cea0..a9fd6cad3f2d 100644 --- a/composer.json +++ b/composer.json @@ -74,7 +74,7 @@ "omnipay/paypal": "^3.0", "payfast/payfast-php-sdk": "^1.1", "pragmarx/google2fa": "^8.0", - "predis/predis": "2.*", + "turbo124/predis": "1.1.11", "razorpay/razorpay": "2.*", "sentry/sentry-laravel": "^3", "setasign/fpdf": "^1.8", diff --git a/composer.lock b/composer.lock index dc8c91a34e64..5381e6ec4340 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "0ac024e516d3ec373954f9da6e3d6256", + "content-hash": "0c7d0b98049debcdc39406241b36770a", "packages": [ { "name": "afosto/yaac", @@ -379,16 +379,16 @@ }, { "name": "aws/aws-sdk-php", - "version": "3.258.5", + "version": "3.258.10", "source": { "type": "git", "url": "https://github.com/aws/aws-sdk-php.git", - "reference": "c29a1db83373f8a5c4735acfdd3470e1bc594fee" + "reference": "e164c9c5faf3965bd27ff2a4e9b7b3048ba8a337" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/c29a1db83373f8a5c4735acfdd3470e1bc594fee", - "reference": "c29a1db83373f8a5c4735acfdd3470e1bc594fee", + "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/e164c9c5faf3965bd27ff2a4e9b7b3048ba8a337", + "reference": "e164c9c5faf3965bd27ff2a4e9b7b3048ba8a337", "shasum": "" }, "require": { @@ -467,9 +467,9 @@ "support": { "forum": "https://forums.aws.amazon.com/forum.jspa?forumID=80", "issues": "https://github.com/aws/aws-sdk-php/issues", - "source": "https://github.com/aws/aws-sdk-php/tree/3.258.5" + "source": "https://github.com/aws/aws-sdk-php/tree/3.258.10" }, - "time": "2023-02-07T19:22:14+00:00" + "time": "2023-02-14T19:21:16+00:00" }, { "name": "bacon/bacon-qr-code", @@ -1909,16 +1909,16 @@ }, { "name": "firebase/php-jwt", - "version": "v6.3.2", + "version": "v6.4.0", "source": { "type": "git", "url": "https://github.com/firebase/php-jwt.git", - "reference": "ea7dda77098b96e666c5ef382452f94841e439cd" + "reference": "4dd1e007f22a927ac77da5a3fbb067b42d3bc224" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/firebase/php-jwt/zipball/ea7dda77098b96e666c5ef382452f94841e439cd", - "reference": "ea7dda77098b96e666c5ef382452f94841e439cd", + "url": "https://api.github.com/repos/firebase/php-jwt/zipball/4dd1e007f22a927ac77da5a3fbb067b42d3bc224", + "reference": "4dd1e007f22a927ac77da5a3fbb067b42d3bc224", "shasum": "" }, "require": { @@ -1933,6 +1933,7 @@ "psr/http-factory": "^1.0" }, "suggest": { + "ext-sodium": "Support EdDSA (Ed25519) signatures", "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present" }, "type": "library", @@ -1965,9 +1966,9 @@ ], "support": { "issues": "https://github.com/firebase/php-jwt/issues", - "source": "https://github.com/firebase/php-jwt/tree/v6.3.2" + "source": "https://github.com/firebase/php-jwt/tree/v6.4.0" }, - "time": "2022-12-19T17:10:46+00:00" + "time": "2023-02-09T21:01:23+00:00" }, { "name": "fruitcake/php-cors", @@ -2042,16 +2043,16 @@ }, { "name": "gocardless/gocardless-pro", - "version": "4.25.0", + "version": "4.26.0", "source": { "type": "git", "url": "https://github.com/gocardless/gocardless-pro-php.git", - "reference": "ebaed83ae21cf40d7eb05f568c26f88d2cae1e5a" + "reference": "a8595043eb13d597e8d11c4c1bfb0e040696e6b7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/gocardless/gocardless-pro-php/zipball/ebaed83ae21cf40d7eb05f568c26f88d2cae1e5a", - "reference": "ebaed83ae21cf40d7eb05f568c26f88d2cae1e5a", + "url": "https://api.github.com/repos/gocardless/gocardless-pro-php/zipball/a8595043eb13d597e8d11c4c1bfb0e040696e6b7", + "reference": "a8595043eb13d597e8d11c4c1bfb0e040696e6b7", "shasum": "" }, "require": { @@ -2091,9 +2092,9 @@ ], "support": { "issues": "https://github.com/gocardless/gocardless-pro-php/issues", - "source": "https://github.com/gocardless/gocardless-pro-php/tree/v4.25.0" + "source": "https://github.com/gocardless/gocardless-pro-php/tree/v4.26.0" }, - "time": "2023-01-31T13:01:05+00:00" + "time": "2023-02-14T11:07:20+00:00" }, { "name": "google/apiclient", @@ -2167,16 +2168,16 @@ }, { "name": "google/apiclient-services", - "version": "v0.286.0", + "version": "v0.287.0", "source": { "type": "git", "url": "https://github.com/googleapis/google-api-php-client-services.git", - "reference": "4a00eb9803e01f97d96e49fd82dbb03802610def" + "reference": "ed58596d34272a5cd0dc2c0595d9a678b9834880" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/4a00eb9803e01f97d96e49fd82dbb03802610def", - "reference": "4a00eb9803e01f97d96e49fd82dbb03802610def", + "url": "https://api.github.com/repos/googleapis/google-api-php-client-services/zipball/ed58596d34272a5cd0dc2c0595d9a678b9834880", + "reference": "ed58596d34272a5cd0dc2c0595d9a678b9834880", "shasum": "" }, "require": { @@ -2205,9 +2206,9 @@ ], "support": { "issues": "https://github.com/googleapis/google-api-php-client-services/issues", - "source": "https://github.com/googleapis/google-api-php-client-services/tree/v0.286.0" + "source": "https://github.com/googleapis/google-api-php-client-services/tree/v0.287.0" }, - "time": "2023-02-05T01:20:11+00:00" + "time": "2023-02-12T01:08:11+00:00" }, { "name": "google/auth", @@ -3576,16 +3577,16 @@ }, { "name": "laravel/framework", - "version": "v9.51.0", + "version": "v9.52.0", "source": { "type": "git", "url": "https://github.com/laravel/framework.git", - "reference": "b81123134349a013a738a9f7f715c6ce99d5a414" + "reference": "eb85cd9d72e5bfa54b4d0d9040786f26d6184a9e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/framework/zipball/b81123134349a013a738a9f7f715c6ce99d5a414", - "reference": "b81123134349a013a738a9f7f715c6ce99d5a414", + "url": "https://api.github.com/repos/laravel/framework/zipball/eb85cd9d72e5bfa54b4d0d9040786f26d6184a9e", + "reference": "eb85cd9d72e5bfa54b4d0d9040786f26d6184a9e", "shasum": "" }, "require": { @@ -3770,7 +3771,7 @@ "issues": "https://github.com/laravel/framework/issues", "source": "https://github.com/laravel/framework" }, - "time": "2023-02-07T15:37:18+00:00" + "time": "2023-02-14T14:51:14+00:00" }, { "name": "laravel/serializable-closure", @@ -7092,76 +7093,6 @@ }, "time": "2022-06-13T21:57:56+00:00" }, - { - "name": "predis/predis", - "version": "v2.1.1", - "source": { - "type": "git", - "url": "https://github.com/predis/predis.git", - "reference": "c5b60884e89630f9518a7919f0566db438f0fc9a" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/predis/predis/zipball/c5b60884e89630f9518a7919f0566db438f0fc9a", - "reference": "c5b60884e89630f9518a7919f0566db438f0fc9a", - "shasum": "" - }, - "require": { - "php": "^7.2 || ^8.0" - }, - "require-dev": { - "phpunit/phpunit": "^8.0 || ~9.4.4" - }, - "suggest": { - "ext-curl": "Allows access to Webdis when paired with phpiredis" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "2.0-dev" - } - }, - "autoload": { - "psr-4": { - "Predis\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Till Krüss", - "homepage": "https://till.im", - "role": "Maintainer" - }, - { - "name": "Daniele Alessandri", - "email": "suppakilla@gmail.com", - "homepage": "http://clorophilla.net", - "role": "Creator" - } - ], - "description": "A flexible and feature-complete Redis client for PHP.", - "homepage": "http://github.com/predis/predis", - "keywords": [ - "nosql", - "predis", - "redis" - ], - "support": { - "issues": "https://github.com/predis/predis/issues", - "source": "https://github.com/predis/predis/tree/v2.1.1" - }, - "funding": [ - { - "url": "https://github.com/sponsors/tillkruss", - "type": "github" - } - ], - "time": "2023-01-17T20:57:35+00:00" - }, { "name": "psr/cache", "version": "3.0.0", @@ -8255,16 +8186,16 @@ }, { "name": "sentry/sentry", - "version": "3.13.0", + "version": "3.13.1", "source": { "type": "git", "url": "https://github.com/getsentry/sentry-php.git", - "reference": "a046ff5a37f5a0a0c285a6543dc17a7fc93b47f8" + "reference": "71c86fe4699a7f1a40c7d985f3dc7667045152f0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/getsentry/sentry-php/zipball/a046ff5a37f5a0a0c285a6543dc17a7fc93b47f8", - "reference": "a046ff5a37f5a0a0c285a6543dc17a7fc93b47f8", + "url": "https://api.github.com/repos/getsentry/sentry-php/zipball/71c86fe4699a7f1a40c7d985f3dc7667045152f0", + "reference": "71c86fe4699a7f1a40c7d985f3dc7667045152f0", "shasum": "" }, "require": { @@ -8276,7 +8207,7 @@ "php": "^7.2|^8.0", "php-http/async-client-implementation": "^1.0", "php-http/client-common": "^1.5|^2.0", - "php-http/discovery": "^1.11", + "php-http/discovery": "^1.11, <1.15", "php-http/httplug": "^1.1|^2.0", "php-http/message": "^1.5", "psr/http-factory": "^1.0", @@ -8343,7 +8274,7 @@ ], "support": { "issues": "https://github.com/getsentry/sentry-php/issues", - "source": "https://github.com/getsentry/sentry-php/tree/3.13.0" + "source": "https://github.com/getsentry/sentry-php/tree/3.13.1" }, "funding": [ { @@ -8355,7 +8286,7 @@ "type": "custom" } ], - "time": "2023-02-03T10:03:13+00:00" + "time": "2023-02-10T10:17:57+00:00" }, { "name": "sentry/sentry-laravel", @@ -8498,16 +8429,16 @@ }, { "name": "setasign/fpdi", - "version": "v2.3.6", + "version": "v2.3.7", "source": { "type": "git", "url": "https://github.com/Setasign/FPDI.git", - "reference": "6231e315f73e4f62d72b73f3d6d78ff0eed93c31" + "reference": "bccc892d5fa1f48c43f8ba7db5ed4ba6f30c8c05" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Setasign/FPDI/zipball/6231e315f73e4f62d72b73f3d6d78ff0eed93c31", - "reference": "6231e315f73e4f62d72b73f3d6d78ff0eed93c31", + "url": "https://api.github.com/repos/Setasign/FPDI/zipball/bccc892d5fa1f48c43f8ba7db5ed4ba6f30c8c05", + "reference": "bccc892d5fa1f48c43f8ba7db5ed4ba6f30c8c05", "shasum": "" }, "require": { @@ -8558,7 +8489,7 @@ ], "support": { "issues": "https://github.com/Setasign/FPDI/issues", - "source": "https://github.com/Setasign/FPDI/tree/v2.3.6" + "source": "https://github.com/Setasign/FPDI/tree/v2.3.7" }, "funding": [ { @@ -8566,20 +8497,20 @@ "type": "tidelift" } ], - "time": "2021-02-11T11:37:01+00:00" + "time": "2023-02-09T10:38:43+00:00" }, { "name": "socialiteproviders/apple", - "version": "5.3.0", + "version": "5.3.1", "source": { "type": "git", "url": "https://github.com/SocialiteProviders/Apple.git", - "reference": "13bfd5ad4a6ab33ecab35d933deba01e9de6e404" + "reference": "f3b9a435e302b1a3d9a50285e934a6be66b2754a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/SocialiteProviders/Apple/zipball/13bfd5ad4a6ab33ecab35d933deba01e9de6e404", - "reference": "13bfd5ad4a6ab33ecab35d933deba01e9de6e404", + "url": "https://api.github.com/repos/SocialiteProviders/Apple/zipball/f3b9a435e302b1a3d9a50285e934a6be66b2754a", + "reference": "f3b9a435e302b1a3d9a50285e934a6be66b2754a", "shasum": "" }, "require": { @@ -8637,7 +8568,7 @@ "issues": "https://github.com/socialiteproviders/providers/issues", "source": "https://github.com/socialiteproviders/providers" }, - "time": "2022-07-18T08:37:00+00:00" + "time": "2023-02-11T04:00:50+00:00" }, { "name": "socialiteproviders/manager", @@ -12292,17 +12223,83 @@ "time": "2023-01-29T00:13:12+00:00" }, { - "name": "twilio/sdk", - "version": "6.44.2", + "name": "turbo124/predis", + "version": "v1.1.11", "source": { "type": "git", - "url": "git@github.com:twilio/twilio-php.git", - "reference": "deec3203857387213825e2634c4eb4b56880877a" + "url": "https://github.com/turbo124/predis.git", + "reference": "3ebce475e48ed0842dbe6f252ae55a4523b35116" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/twilio/twilio-php/zipball/deec3203857387213825e2634c4eb4b56880877a", - "reference": "deec3203857387213825e2634c4eb4b56880877a", + "url": "https://api.github.com/repos/turbo124/predis/zipball/3ebce475e48ed0842dbe6f252ae55a4523b35116", + "reference": "3ebce475e48ed0842dbe6f252ae55a4523b35116", + "shasum": "" + }, + "require": { + "php": ">=5.3.9" + }, + "require-dev": { + "phpunit/phpunit": "~4.8" + }, + "suggest": { + "ext-curl": "Allows access to Webdis when paired with phpiredis", + "ext-phpiredis": "Allows faster serialization and deserialization of the Redis protocol" + }, + "type": "library", + "autoload": { + "psr-4": { + "Predis\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Daniele Alessandri", + "email": "suppakilla@gmail.com", + "homepage": "http://clorophilla.net", + "role": "Creator & Maintainer" + }, + { + "name": "Till Krüss", + "homepage": "https://till.im", + "role": "Maintainer" + } + ], + "description": "Flexible and feature-complete Redis client for PHP and HHVM", + "homepage": "http://github.com/predis/predis", + "keywords": [ + "nosql", + "predis", + "redis" + ], + "support": { + "issues": "https://github.com/predis/predis/issues", + "source": "https://github.com/turbo124/predis/tree/v1.1.11" + }, + "funding": [ + { + "url": "https://github.com/sponsors/tillkruss", + "type": "github" + } + ], + "time": "2022-10-28T04:36:19+00:00" + }, + { + "name": "twilio/sdk", + "version": "6.44.3", + "source": { + "type": "git", + "url": "git@github.com:twilio/twilio-php.git", + "reference": "0e3e513d3c428f08bde195c579cbc0788415190f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/twilio/twilio-php/zipball/0e3e513d3c428f08bde195c579cbc0788415190f", + "reference": "0e3e513d3c428f08bde195c579cbc0788415190f", "shasum": "" }, "require": { @@ -12310,7 +12307,7 @@ }, "require-dev": { "guzzlehttp/guzzle": "^6.3 || ^7.0", - "phpunit/phpunit": ">=7.0" + "phpunit/phpunit": ">=7.0 < 10" }, "suggest": { "guzzlehttp/guzzle": "An HTTP client to execute the API requests" @@ -12338,7 +12335,7 @@ "sms", "twilio" ], - "time": "2023-01-25T19:34:30+00:00" + "time": "2023-02-08T20:09:20+00:00" }, { "name": "vlucas/phpdotenv", @@ -14549,37 +14546,38 @@ }, { "name": "php-webdriver/webdriver", - "version": "1.13.1", + "version": "1.14.0", "source": { "type": "git", "url": "https://github.com/php-webdriver/php-webdriver.git", - "reference": "6dfe5f814b796c1b5748850aa19f781b9274c36c" + "reference": "3ea4f924afb43056bf9c630509e657d951608563" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-webdriver/php-webdriver/zipball/6dfe5f814b796c1b5748850aa19f781b9274c36c", - "reference": "6dfe5f814b796c1b5748850aa19f781b9274c36c", + "url": "https://api.github.com/repos/php-webdriver/php-webdriver/zipball/3ea4f924afb43056bf9c630509e657d951608563", + "reference": "3ea4f924afb43056bf9c630509e657d951608563", "shasum": "" }, "require": { "ext-curl": "*", "ext-json": "*", "ext-zip": "*", - "php": "^5.6 || ~7.0 || ^8.0", + "php": "^7.3 || ^8.0", "symfony/polyfill-mbstring": "^1.12", - "symfony/process": "^2.8 || ^3.1 || ^4.0 || ^5.0 || ^6.0" + "symfony/process": "^5.0 || ^6.0" }, "replace": { "facebook/webdriver": "*" }, "require-dev": { - "ondram/ci-detector": "^2.1 || ^3.5 || ^4.0", + "ergebnis/composer-normalize": "^2.20.0", + "ondram/ci-detector": "^4.0", "php-coveralls/php-coveralls": "^2.4", - "php-mock/php-mock-phpunit": "^1.1 || ^2.0", + "php-mock/php-mock-phpunit": "^2.0", "php-parallel-lint/php-parallel-lint": "^1.2", - "phpunit/phpunit": "^5.7 || ^7 || ^8 || ^9", + "phpunit/phpunit": "^9.3", "squizlabs/php_codesniffer": "^3.5", - "symfony/var-dumper": "^3.3 || ^4.0 || ^5.0 || ^6.0" + "symfony/var-dumper": "^5.0 || ^6.0" }, "suggest": { "ext-SimpleXML": "For Firefox profile creation" @@ -14608,9 +14606,9 @@ ], "support": { "issues": "https://github.com/php-webdriver/php-webdriver/issues", - "source": "https://github.com/php-webdriver/php-webdriver/tree/1.13.1" + "source": "https://github.com/php-webdriver/php-webdriver/tree/1.14.0" }, - "time": "2022-10-11T11:49:44+00:00" + "time": "2023-02-09T12:12:19+00:00" }, { "name": "phpdocumentor/reflection-common", From 7787d1f6533a62be4971de8dd70fd1c2021ee181 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 09:28:23 +1100 Subject: [PATCH 13/72] Clean up for access permissions --- .../StoreBankTransactionRuleRequest.php | 5 +++-- app/Http/Requests/Design/StoreDesignRequest.php | 3 ++- .../Requests/GroupSetting/StoreGroupSettingRequest.php | 9 +++++---- .../Requests/Subscription/StoreSubscriptionRequest.php | 5 +++-- app/Http/Requests/Webhook/StoreWebhookRequest.php | 3 ++- app/Models/Account.php | 1 + lang/en/texts.php | 1 + 7 files changed, 17 insertions(+), 10 deletions(-) diff --git a/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php b/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php index b5df369a7495..1a3341edfe4b 100644 --- a/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php +++ b/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php @@ -11,9 +11,10 @@ namespace App\Http\Requests\BankTransactionRule; +use App\Models\Account; use App\Http\Requests\Request; -use App\Models\BankTransactionRule; use App\Utils\Traits\MakesHash; +use App\Models\BankTransactionRule; class StoreBankTransactionRuleRequest extends Request { @@ -26,7 +27,7 @@ class StoreBankTransactionRuleRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', BankTransactionRule::class); + return auth()->user()->can('create', BankTransactionRule::class) && auth()->user()->account->hasFeature(Account::FEATURE_API);; } public function rules() diff --git a/app/Http/Requests/Design/StoreDesignRequest.php b/app/Http/Requests/Design/StoreDesignRequest.php index 1c55e19ce565..73e494e09844 100644 --- a/app/Http/Requests/Design/StoreDesignRequest.php +++ b/app/Http/Requests/Design/StoreDesignRequest.php @@ -11,6 +11,7 @@ namespace App\Http\Requests\Design; +use App\Models\Account; use App\Http\Requests\Request; class StoreDesignRequest extends Request @@ -22,7 +23,7 @@ class StoreDesignRequest extends Request */ public function authorize() : bool { - return auth()->user()->isAdmin(); + return auth()->user()->isAdmin() && auth()->user()->account->hasFeature(Account::FEATURE_API);; } public function rules() diff --git a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php index 9762b7371113..a8f092d38d12 100644 --- a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php @@ -11,10 +11,11 @@ namespace App\Http\Requests\GroupSetting; -use App\DataMapper\ClientSettings; -use App\Http\Requests\Request; -use App\Http\ValidationRules\ValidClientGroupSettingsRule; +use App\Models\Account; use App\Models\GroupSetting; +use App\Http\Requests\Request; +use App\DataMapper\ClientSettings; +use App\Http\ValidationRules\ValidClientGroupSettingsRule; class StoreGroupSettingRequest extends Request { @@ -25,7 +26,7 @@ class StoreGroupSettingRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', GroupSetting::class); + return auth()->user()->can('create', GroupSetting::class) && && auth()->user()->account->hasFeature(Account::FEATURE_API);; } public function rules() diff --git a/app/Http/Requests/Subscription/StoreSubscriptionRequest.php b/app/Http/Requests/Subscription/StoreSubscriptionRequest.php index c4e6daae4ff6..aa781f351da1 100644 --- a/app/Http/Requests/Subscription/StoreSubscriptionRequest.php +++ b/app/Http/Requests/Subscription/StoreSubscriptionRequest.php @@ -11,8 +11,9 @@ namespace App\Http\Requests\Subscription; -use App\Http\Requests\Request; +use App\Models\Account; use App\Models\Subscription; +use App\Http\Requests\Request; use Illuminate\Validation\Rule; class StoreSubscriptionRequest extends Request @@ -24,7 +25,7 @@ class StoreSubscriptionRequest extends Request */ public function authorize() { - return auth()->user()->can('create', Subscription::class); + return auth()->user()->can('create', Subscription::class) && auth()->user()->account->hasFeature(Account::FEATURE_API); } /** diff --git a/app/Http/Requests/Webhook/StoreWebhookRequest.php b/app/Http/Requests/Webhook/StoreWebhookRequest.php index 9b36c4331117..9ae591d36cb2 100644 --- a/app/Http/Requests/Webhook/StoreWebhookRequest.php +++ b/app/Http/Requests/Webhook/StoreWebhookRequest.php @@ -11,6 +11,7 @@ namespace App\Http\Requests\Webhook; +use App\Models\Account; use App\Http\Requests\Request; class StoreWebhookRequest extends Request @@ -22,7 +23,7 @@ class StoreWebhookRequest extends Request */ public function authorize() : bool { - return auth()->user()->isAdmin(); + return auth()->user()->isAdmin() && auth()->user()->account->hasFeature(Account::FEATURE_API) } public function rules() diff --git a/app/Models/Account.php b/app/Models/Account.php index 2dbd6373dfa2..a4ec1d5d568b 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -110,6 +110,7 @@ class Account extends BaseModel const FEATURE_USERS = 'users'; // Grandfathered for old Pro users const FEATURE_DOCUMENTS = 'documents'; const FEATURE_USER_PERMISSIONS = 'permissions'; + const FEATURE_SUBSCRIPTIONS = 'subscriptions'; const RESULT_FAILURE = 'failure'; const RESULT_SUCCESS = 'success'; diff --git a/lang/en/texts.php b/lang/en/texts.php index 1766559164fc..8eace4e16873 100644 --- a/lang/en/texts.php +++ b/lang/en/texts.php @@ -4952,6 +4952,7 @@ $LANG = array( 'update_payment' => 'Update Payment', 'markup' => 'Markup', 'unlock_pro' => 'Unlock Pro', + 'preferences' => 'Preferences' ); From d1a35510e9c0557460c18c5d9fcf4a991f5dc706 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 09:39:17 +1100 Subject: [PATCH 14/72] Fixes for tests --- app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php index a8f092d38d12..46a9bfc0ca99 100644 --- a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php @@ -26,7 +26,7 @@ class StoreGroupSettingRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', GroupSetting::class) && && auth()->user()->account->hasFeature(Account::FEATURE_API);; + return auth()->user()->can('create', GroupSetting::class) && auth()->user()->account->hasFeature(Account::FEATURE_API);; } public function rules() From 1e5b96ddadef4ba02aecfacc01de8c757bf90c9b Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 09:50:46 +1100 Subject: [PATCH 15/72] Fixes for tests --- app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php | 2 +- app/Http/Requests/Webhook/StoreWebhookRequest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php index 46a9bfc0ca99..7e15f9a66a2e 100644 --- a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php @@ -26,7 +26,7 @@ class StoreGroupSettingRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', GroupSetting::class) && auth()->user()->account->hasFeature(Account::FEATURE_API);; + return auth()->user()->can('create', GroupSetting::class) && auth()->user()->account->hasFeature(Account::FEATURE_API); } public function rules() diff --git a/app/Http/Requests/Webhook/StoreWebhookRequest.php b/app/Http/Requests/Webhook/StoreWebhookRequest.php index 9ae591d36cb2..7fd5d372c24a 100644 --- a/app/Http/Requests/Webhook/StoreWebhookRequest.php +++ b/app/Http/Requests/Webhook/StoreWebhookRequest.php @@ -23,7 +23,7 @@ class StoreWebhookRequest extends Request */ public function authorize() : bool { - return auth()->user()->isAdmin() && auth()->user()->account->hasFeature(Account::FEATURE_API) + return auth()->user()->isAdmin() && auth()->user()->account->hasFeature(Account::FEATURE_API); } public function rules() From a4f2d40d7564acaa19359f5b3ef094ba182fa7f9 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 11:04:47 +1100 Subject: [PATCH 16/72] Working on emailers --- app/Http/Controllers/EmailController.php | 3 + app/Http/Middleware/TokenAuth.php | 1 - app/Jobs/Entity/EmailEntity.php | 6 - app/Models/Quote.php | 12 ++ app/Providers/MultiDBProvider.php | 1 - app/Services/Email/BaseMailer.php | 263 ----------------------- app/Services/Email/MailBuild.php | 75 +++++-- app/Services/Email/MailObject.php | 2 + app/Services/Quote/SendEmail.php | 15 +- 9 files changed, 89 insertions(+), 289 deletions(-) delete mode 100644 app/Services/Email/BaseMailer.php diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index b7b0582c90a3..25dca243d6bf 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -23,6 +23,7 @@ use App\Models\Invoice; use App\Models\PurchaseOrder; use App\Models\Quote; use App\Models\RecurringInvoice; +use App\Services\Email\MailObject; use App\Transformers\CreditTransformer; use App\Transformers\InvoiceTransformer; use App\Transformers\PurchaseOrderTransformer; @@ -127,6 +128,8 @@ class EmailController extends BaseController 'body' => $body, ]; + $mo = new MailObject; + if(Ninja::isHosted() && !$entity_obj->company->account->account_sms_verified) return response(['message' => 'Please verify your account to send emails.'], 400); diff --git a/app/Http/Middleware/TokenAuth.php b/app/Http/Middleware/TokenAuth.php index b312e1df5263..abd52376f098 100644 --- a/app/Http/Middleware/TokenAuth.php +++ b/app/Http/Middleware/TokenAuth.php @@ -73,7 +73,6 @@ class TokenAuth | session */ app('queue')->createPayloadUsing(function () use ($company_token) { - nlog("setting DB ". $company_token->company->db); return ['db' => $company_token->company->db]; }); diff --git a/app/Jobs/Entity/EmailEntity.php b/app/Jobs/Entity/EmailEntity.php index 96e8b088f55b..dda2c0711fab 100644 --- a/app/Jobs/Entity/EmailEntity.php +++ b/app/Jobs/Entity/EmailEntity.php @@ -11,19 +11,14 @@ namespace App\Jobs\Entity; -use App\Events\Invoice\InvoiceReminderWasEmailed; -use App\Events\Invoice\InvoiceWasEmailed; use App\Events\Invoice\InvoiceWasEmailedAndFailed; -use App\Jobs\Mail\EntityFailedSendMailer; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; use App\Mail\TemplateEmail; -use App\Models\Activity; use App\Models\Company; use App\Models\CreditInvitation; use App\Models\InvoiceInvitation; -use App\Models\PurchaseOrderInvitation; use App\Models\QuoteInvitation; use App\Models\RecurringInvoiceInvitation; use App\Utils\HtmlEngine; @@ -34,7 +29,6 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Mail; use Illuminate\Support\Str; /*Multi Mailer implemented*/ diff --git a/app/Models/Quote.php b/app/Models/Quote.php index 03c09ae60a77..f03d8c9ff5d9 100644 --- a/app/Models/Quote.php +++ b/app/Models/Quote.php @@ -351,4 +351,16 @@ class Quote extends BaseModel { return ctrans('texts.quote'); } + + /** + * calculateTemplate + * + * @param string $entity_string + * @return string + */ + public function calculateTemplate(string $entity_string): string + { + return $entity_string; + } + } diff --git a/app/Providers/MultiDBProvider.php b/app/Providers/MultiDBProvider.php index 72beb2abc594..f00a1d436693 100644 --- a/app/Providers/MultiDBProvider.php +++ b/app/Providers/MultiDBProvider.php @@ -37,7 +37,6 @@ class MultiDBProvider extends ServiceProvider JobProcessing::class, function ($event) { if (isset($event->job->payload()['db'])) { - nlog("Settings DB: " . $event->job->payload()['db']); MultiDB::setDb($event->job->payload()['db']); } } diff --git a/app/Services/Email/BaseMailer.php b/app/Services/Email/BaseMailer.php deleted file mode 100644 index 1fd066d5a8a5..000000000000 --- a/app/Services/Email/BaseMailer.php +++ /dev/null @@ -1,263 +0,0 @@ -invitation = $invitation; - - $this->company = $invitation->company; - - $this->db = $db; - - $this->mail_object = $mail_object; - - $this->override = $mail_object->override; - - } - - - public function companyCheck(): void - { - /* Handle bad state */ - if(!$this->company) - $this->fail(); - - /* Handle deactivated company */ - if($this->company->is_disabled && !$this->override) - $this->fail(); - - /* To handle spam users we drop all emails from flagged accounts */ - if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) - $this->fail(); - - } - - public function configureMailer(): self - { - $this->setMailDriver(); - - $this->mail = Mail::mailer($this->mailer); - - return $this; - } - - - /** - * Sets the mail driver to use and applies any specific configuration - * the the mailable - */ - private function setMailDriver(): self - { - - switch ($this->mail_object->settings->email_sending_method) { - case 'default': - $this->mailer = config('mail.default'); - break; - // case 'gmail': - // $this->mailer = 'gmail'; - // $this->setGmailMailer(); - // return $this; - // case 'office365': - // $this->mailer = 'office365'; - // $this->setOfficeMailer(); - // return $this; - // case 'client_postmark': - // $this->mailer = 'postmark'; - // $this->setPostmarkMailer(); - // return $this; - // case 'client_mailgun': - // $this->mailer = 'mailgun'; - // $this->setMailgunMailer(); - // return $this; - - default: - break; - } - - if(Ninja::isSelfHost()) - $this->setSelfHostMultiMailer(); - - return $this; - - } - - /** - * Allows configuration of multiple mailers - * per company for use by self hosted users - */ - private function setSelfHostMultiMailer(): void - { - - if (env($this->email_service->company->id . '_MAIL_HOST')) - { - - config([ - 'mail.mailers.smtp' => [ - 'transport' => 'smtp', - 'host' => env($this->email_service->company->id . '_MAIL_HOST'), - 'port' => env($this->email_service->company->id . '_MAIL_PORT'), - 'username' => env($this->email_service->company->id . '_MAIL_USERNAME'), - 'password' => env($this->email_service->company->id . '_MAIL_PASSWORD'), - ], - ]); - - if(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS')) - { - $this->email_mailable - ->from(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->email_service->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME'))); - } - - } - - } - - - /** - * Ensure we discard any data that is not required - * - * @return void - */ - private function cleanUpMailers(): void - { - $this->client_postmark_secret = false; - - $this->client_mailgun_secret = false; - - $this->client_mailgun_domain = false; - - //always dump the drivers to prevent reuse - app('mail.manager')->forgetMailers(); - } - - - public function trySending() - { - try { - - $mailer - ->to($this->mail_object->to_user->email) - ->send($this->mail_object->mailable); - - /* Count the amount of emails sent across all the users accounts */ - Cache::increment($this->company->account->key); - - LightLogs::create(new EmailSuccess($this->company->company_key)) - ->send(); - - } - catch(\Symfony\Component\Mime\Exception\RfcComplianceException $e) { - nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); - $this->fail(); - $this->cleanUpMailers(); - $this->logMailError($e->getMessage(), $this->company->clients()->first()); - return; - } - catch(\Symfony\Component\Mime\Exception\LogicException $e){ - nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); - $this->fail(); - $this->cleanUpMailers(); - $this->logMailError($e->getMessage(), $this->company->clients()->first()); - return; - } - catch (\Exception | \Google\Service\Exception $e) { - - nlog("Mailer failed with {$e->getMessage()}"); - $message = $e->getMessage(); - - /** - * Post mark buries the proper message in a a guzzle response - * this merges a text string with a json object - * need to harvest the ->Message property using the following - */ - if(stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) - { - - $message = "Either Attachment too large, or recipient has been suppressed."; - - $this->fail(); - $this->logMailError($e->getMessage(), $this->company->clients()->first()); - $this->cleanUpMailers(); - - return; - - } - - //only report once, not on all tries - if($this->attempts() == $this->tries) - { - - /* If the is an entity attached to the message send a failure mailer */ - if($this->nmo->entity) - $this->entityEmailFailed($message); - - /* Don't send postmark failures to Sentry */ - if(Ninja::isHosted() && (!$e instanceof ClientException)) - app('sentry')->captureException($e); - - } - - /* Releasing immediately does not add in the backoff */ - $this->release($this->backoff()[$this->attempts()-1]); - - } - } - - public function backoff() - { - return [5, 10, 30, 240]; - } - - public function failed($exception = null) - { - - config(['queue.failed.driver' => null]); - - } -} diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index 8799c7472c42..e9e9b4aa902b 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -13,13 +13,18 @@ namespace App\Services\Email; use App\Models\Task; use App\Utils\Ninja; +use App\Models\Quote; use App\Models\Client; +use App\Models\Credit; use App\Models\Vendor; use App\Models\Account; use App\Models\Expense; +use App\Models\Invoice; use App\Utils\HtmlEngine; use App\Models\ClientContact; +use App\Models\PurchaseOrder; use App\Models\VendorContact; +use App\Utils\Traits\MakesHash; use App\Utils\VendorHtmlEngine; use App\Jobs\Entity\CreateRawPdf; use Illuminate\Support\Facades\App; @@ -30,7 +35,6 @@ use Illuminate\Contracts\Mail\Mailable; use App\DataMapper\EmailTemplateDefaults; use League\CommonMark\CommonMarkConverter; use App\Jobs\Vendor\CreatePurchaseOrderPdf; -use App\Utils\Traits\MakesHash; class MailBuild { @@ -118,6 +122,30 @@ class MailBuild $this->vendor = $vendor_contact?->vendor; + if($this->mail_entity?->invitation){ + + + if($this->mail_entity->invitation?->invoice){ + $this->mail_entity->mail_object->entity_string = 'invoice'; + $this->mail_entity->mail_object->entity_class = Invoice::class; + } + + if($this->mail_entity->invitation?->quote){ + $this->mail_entity->mail_object->entity_string = 'quote'; + $this->mail_entity->mail_object->entity_class = Quote::class; + } + + if($this->mail_entity->invitation?->credit){ + $this->mail_entity->mail_object->entity_string = 'credit'; + $this->mail_entity->mail_object->entity_class = Credit::class; + } + + if($this->mail_entity->invitation?->puchase_order){ + $this->mail_entity->mail_object->entity_string = 'purchase_order'; + $this->mail_entity->mail_object->entity_class = PurchaseOrder::class; + } + } + return $this; } @@ -261,7 +289,7 @@ class MailBuild elseif(is_string($this->mail_entity->mail_object->email_template_subject) && strlen($this->settings->{$this->mail_entity->mail_object->email_template_subject}) > 3) $this->mail_entity->mail_object->subject = $this->settings->{$this->mail_entity->mail_object->email_template_subject}; else - $this->mail_entity->mail_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->mail_entity->mail_object->email_template_subject, $this->locale); + $this->mail_entity->mail_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->resolveBaseEntityTemplate(), $this->locale); return $this; @@ -282,7 +310,7 @@ class MailBuild $this->mail_entity->mail_object->body = $this->settings->{$this->mail_entity->mail_object->email_template_body}; } else{ - $this->mail_entity->mail_object->body = EmailTemplateDefaults::getDefaultTemplate($this->mail_entity->mail_object->email_template_body, $this->locale); + $this->mail_entity->mail_object->body = EmailTemplateDefaults::getDefaultTemplate($this->resolveBaseEntityTemplate('body'), $this->locale); } if($this->template == 'email.template.custom'){ @@ -292,6 +320,29 @@ class MailBuild return $this; } + + /** + * Where no template is explicitly passed, we need to infer by the entity type - + * which is hopefully resolvable. + * + * @param string $type + * @return string + */ + private function resolveBaseEntityTemplate(string $type = 'subject'): string + { + //handle statements being emailed + //handle custom templates these types won't have a resolvable entity_string + if(!$this->mail_entity->mail_object->entity_string) + return 'email_template_invoice'; + + match($type){ + 'subject' => $template = "email_subject_{$this->mail_entity->mail_object->entity_string}", + 'body' => $template = "email_template_{$this->mail_entity->mail_object->entity_string}", + default => $template = "email_template_invoice", + }; + + return $template; + } /** * Sets the attachments for the email @@ -365,24 +416,18 @@ class MailBuild } - if($this->mail_entity->invitation?->invoice) - $entity = 'invoice'; - - if($this->mail_entity->invitation?->quote) - $entity = 'quote'; - - if($this->mail_entity->invitation?->credit) - $entity = 'credit'; + if(!$this->mail_entity->mail_object->entity_string) + return $this; $pdf = ((new CreateRawPdf($this->mail_entity->invitation, $this->mail_entity->invitation->company->db))->handle()); nlog($this->mail_entity->mail_object->attachments); - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->{$entity}->numberFormatter().'.pdf']]); + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->{$this->mail_entity->mail_object->entity_string}->numberFormatter().'.pdf']]); if ($this->client->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - $this->attachDocuments($this->mail_entity->invitation->{$entity}->documents); + $this->attachDocuments($this->mail_entity->invitation->{$this->mail_entity->mail_object->entity_string}->documents); } @@ -391,12 +436,12 @@ class MailBuild - if($this->settings->ubl_email_attachment && $entity == 'invoice') + if($this->settings->ubl_email_attachment && $this->mail_entity->mail_object->entity_string == 'invoice') { } - if($entity == 'invoice') + if($this->mail_entity->mail_object->entity_string == 'invoice') { $line_items = $this->mail_entity->invitation->invoice->line_items; diff --git a/app/Services/Email/MailObject.php b/app/Services/Email/MailObject.php index 8f31f10a71df..30ace3436ec7 100644 --- a/app/Services/Email/MailObject.php +++ b/app/Services/Email/MailObject.php @@ -78,6 +78,8 @@ class MailObject public ?string $entity_class = null; + public ?string $entity_string = null; + public array $variables = []; public ?string $template = null; diff --git a/app/Services/Quote/SendEmail.php b/app/Services/Quote/SendEmail.php index 0c1226b3410a..b060616429ff 100644 --- a/app/Services/Quote/SendEmail.php +++ b/app/Services/Quote/SendEmail.php @@ -13,6 +13,8 @@ namespace App\Services\Quote; use App\Jobs\Entity\EmailEntity; use App\Models\ClientContact; +use App\Services\Email\MailEntity; +use App\Services\Email\MailObject; class SendEmail { @@ -37,15 +39,22 @@ class SendEmail */ public function run() { + nlog($this->reminder_template); + nlog("is there a template"); + if (! $this->reminder_template) { $this->reminder_template = $this->quote->calculateTemplate('quote'); } - + + $mo = new MailObject(); + $this->quote->service()->markSent()->save(); - $this->quote->invitations->each(function ($invitation) { + $this->quote->invitations->each(function ($invitation) use ($mo){ if (! $invitation->contact->trashed() && $invitation->contact->email) { - EmailEntity::dispatch($invitation, $invitation->company, $this->reminder_template); + // EmailEntity::dispatch($invitation, $invitation->company, $this->reminder_template); + + MailEntity::dispatch($invitation, $invitation->company->db, $mo); } }); From 453042f7e8c8a9ee781b114058ba118b3fb4a6e6 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 11:37:14 +1100 Subject: [PATCH 17/72] Fixes for mailable --- app/Http/Controllers/EmailController.php | 11 +++++++++-- app/Services/Email/MailBuild.php | 19 +++++++++++++++---- app/Services/Email/MailMailable.php | 2 +- app/Services/Email/MailObject.php | 4 +--- 4 files changed, 26 insertions(+), 10 deletions(-) diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index 25dca243d6bf..8329a71337bd 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -23,6 +23,7 @@ use App\Models\Invoice; use App\Models\PurchaseOrder; use App\Models\Quote; use App\Models\RecurringInvoice; +use App\Services\Email\MailEntity; use App\Services\Email\MailObject; use App\Transformers\CreditTransformer; use App\Transformers\InvoiceTransformer; @@ -129,6 +130,10 @@ class EmailController extends BaseController ]; $mo = new MailObject; + $mo->subject = empty($subject) ? null : $subject; + $mo->body = empty($body) ? null : $body; + $mo->entity_string = $entity; + $mo->email_template = $template; if(Ninja::isHosted() && !$entity_obj->company->account->account_sms_verified) return response(['message' => 'Please verify your account to send emails.'], 400); @@ -137,12 +142,14 @@ class EmailController extends BaseController return $this->sendPurchaseOrder($entity_obj, $data, $template); } - $entity_obj->invitations->each(function ($invitation) use ($data, $entity_string, $entity_obj, $template) { + $entity_obj->invitations->each(function ($invitation) use ($data, $entity_string, $entity_obj, $template, $mo) { if (! $invitation->contact->trashed() && $invitation->contact->email) { $entity_obj->service()->markSent()->save(); - EmailEntity::dispatch($invitation->fresh(), $invitation->company, $template, $data); + // EmailEntity::dispatch($invitation->fresh(), $invitation->company, $template, $data); + + MailEntity::dispatch($invitation, $invitation->company->db, $mo); } }); diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index e9e9b4aa902b..222368dd3ab6 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -286,8 +286,8 @@ class MailBuild if ($this->mail_entity->mail_object->subject) //where the user updates the subject from the UI return $this; - elseif(is_string($this->mail_entity->mail_object->email_template_subject) && strlen($this->settings->{$this->mail_entity->mail_object->email_template_subject}) > 3) - $this->mail_entity->mail_object->subject = $this->settings->{$this->mail_entity->mail_object->email_template_subject}; + elseif(is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate()}) > 3) + $this->mail_entity->mail_object->subject = $this->settings->{$this->resolveBaseEntityTemplate()}; else $this->mail_entity->mail_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->resolveBaseEntityTemplate(), $this->locale); @@ -306,8 +306,8 @@ class MailBuild if($this->mail_entity->mail_object->body){ $this->mail_entity->mail_object->body = $this->mail_entity->mail_object->body; } - elseif(is_string($this->mail_entity->mail_object->email_template_body) && strlen($this->settings->{$this->mail_entity->mail_object->email_template_body}) > 3){ - $this->mail_entity->mail_object->body = $this->settings->{$this->mail_entity->mail_object->email_template_body}; + elseif(is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate('body')}) > 3){ + $this->mail_entity->mail_object->body = $this->settings->{$this->resolveBaseEntityTemplate('body')}; } else{ $this->mail_entity->mail_object->body = EmailTemplateDefaults::getDefaultTemplate($this->resolveBaseEntityTemplate('body'), $this->locale); @@ -330,6 +330,17 @@ class MailBuild */ private function resolveBaseEntityTemplate(string $type = 'subject'): string { + if($this->mail_entity->mail_object->email_template){ + + match($type){ + 'subject' => $template = "email_subject_{$this->mail_entity->mail_object->email_template}", + 'body' => $template = "email_template_{$this->mail_entity->mail_object->email_template}", + default => $template = "email_template_invoice", + }; + + return $template; + } + //handle statements being emailed //handle custom templates these types won't have a resolvable entity_string if(!$this->mail_entity->mail_object->entity_string) diff --git a/app/Services/Email/MailMailable.php b/app/Services/Email/MailMailable.php index d88a6a62ded9..4d0dd5008e66 100644 --- a/app/Services/Email/MailMailable.php +++ b/app/Services/Email/MailMailable.php @@ -57,7 +57,7 @@ class MailMailable extends Mailable view: $this->mail_object->html_template, text: $this->mail_object->text_template, with: [ - 'text_body' => strip_tags($this->mail_object->body), //@todo this is a bit hacky here. + 'text_body' => str_replace("
","\n", strip_tags($this->mail_object->body,"
")), //@todo this is a bit hacky here. 'body' => $this->mail_object->body, 'settings' => $this->mail_object->settings, 'whitelabel' => $this->mail_object->whitelabel, diff --git a/app/Services/Email/MailObject.php b/app/Services/Email/MailObject.php index 30ace3436ec7..d5788ce00c42 100644 --- a/app/Services/Email/MailObject.php +++ b/app/Services/Email/MailObject.php @@ -62,9 +62,7 @@ class MailObject public ?int $vendor_contact_id = null; - public ?string $email_template_body = null; - - public ?string $email_template_subject = null; + public ?string $email_template = null; //this defines the template in short notation WITH the email_template prefix public ?string $html_template = null; From 342f33b5e1bee60ec4d37503725d2aa8ce922bfe Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 11:55:16 +1100 Subject: [PATCH 18/72] Updates for Task Status --- app/Http/Controllers/BaseController.php | 44 +++++++++++++------------ 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index 79947be64b77..8e16e319bb51 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -11,32 +11,33 @@ namespace App\Http\Controllers; -use App\Models\Account; -use App\Models\BankIntegration; -use App\Models\BankTransaction; -use App\Models\BankTransactionRule; -use App\Models\CompanyGateway; -use App\Models\Design; -use App\Models\ExpenseCategory; -use App\Models\GroupSetting; -use App\Models\PaymentTerm; -use App\Models\Scheduler; -use App\Models\TaxRate; use App\Models\User; -use App\Models\Webhook; -use App\Transformers\ArraySerializer; -use App\Transformers\EntityTransformer; use App\Utils\Ninja; +use App\Models\Design; use App\Utils\Statics; -use App\Utils\Traits\AppSetup; -use Illuminate\Contracts\Container\BindingResolutionException; -use Illuminate\Database\Eloquent\Builder; +use App\Models\Account; +use App\Models\TaxRate; +use App\Models\Webhook; +use App\Models\Scheduler; +use App\Models\TaskStatus; +use App\Models\PaymentTerm; use Illuminate\Support\Str; use League\Fractal\Manager; -use League\Fractal\Pagination\IlluminatePaginatorAdapter; -use League\Fractal\Resource\Collection; +use App\Models\GroupSetting; +use App\Models\CompanyGateway; +use App\Utils\Traits\AppSetup; +use App\Models\BankIntegration; +use App\Models\BankTransaction; +use App\Models\ExpenseCategory; use League\Fractal\Resource\Item; +use App\Models\BankTransactionRule; +use App\Transformers\ArraySerializer; +use App\Transformers\EntityTransformer; +use League\Fractal\Resource\Collection; +use Illuminate\Database\Eloquent\Builder; use League\Fractal\Serializer\JsonApiSerializer; +use League\Fractal\Pagination\IlluminatePaginatorAdapter; +use Illuminate\Contracts\Container\BindingResolutionException; /** * Class BaseController. @@ -911,8 +912,9 @@ class BaseController extends Controller else $query->where('user_id', '=', auth()->user()->id); } - elseif(in_array($this->entity_type,[Design::class, GroupSetting::class, PaymentTerm::class])){ - // nlog($this->entity_type); + elseif(in_array($this->entity_type, [Design::class, GroupSetting::class, PaymentTerm::class, TaskStatus::class])){ + nlog("inside"); + nlog($this->entity_type); } else $query->where('user_id', '=', auth()->user()->id)->orWhere('assigned_user_id', auth()->user()->id); From 55bdc6b1cc0550a031b4377b68598c5b35f2cae9 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 21:11:34 +1100 Subject: [PATCH 19/72] Fixes for designs and client compatibility --- app/Http/Controllers/BaseController.php | 3 +- app/Http/Requests/Task/UpdateTaskRequest.php | 2 +- app/Jobs/Mail/NinjaMailerJob.php | 3 + app/Services/Email/MailBuild.php | 2 - app/Utils/HtmlEngine.php | 32 ++++- .../email/admin/download_credits.blade.php | 16 ++- .../email/admin/download_documents.blade.php | 15 ++- .../email/admin/download_files.blade.php | 13 +- .../email/admin/download_invoices.blade.php | 15 ++- .../admin/download_purchase_orders.blade.php | 15 ++- .../email/admin/download_quotes.blade.php | 15 ++- .../email/admin/download_report.blade.php | 11 ++ resources/views/email/admin/generic.blade.php | 13 +- .../views/email/admin/generic_email.blade.php | 10 +- resources/views/email/auth/verify.blade.php | 16 ++- .../billing/passwordless-login.blade.php | 13 +- .../views/email/client/generic.blade.php | 13 +- .../views/email/components/button.blade.php | 13 +- .../ach-verification-notification.blade.php | 13 +- .../views/email/import/completed.blade.php | 12 +- .../email/import/csv_completed.blade.php | 12 +- .../views/email/migration/completed.blade.php | 14 ++- .../views/email/template/admin.blade.php | 119 ++++++++++++------ .../views/email/template/client.blade.php | 33 ++--- .../views/themes/ninja2020/clean.blade.php | 7 ++ 25 files changed, 342 insertions(+), 88 deletions(-) diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index 8e16e319bb51..f319791092be 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -913,8 +913,7 @@ class BaseController extends Controller $query->where('user_id', '=', auth()->user()->id); } elseif(in_array($this->entity_type, [Design::class, GroupSetting::class, PaymentTerm::class, TaskStatus::class])){ - nlog("inside"); - nlog($this->entity_type); + // nlog($this->entity_type); } else $query->where('user_id', '=', auth()->user()->id)->orWhere('assigned_user_id', auth()->user()->id); diff --git a/app/Http/Requests/Task/UpdateTaskRequest.php b/app/Http/Requests/Task/UpdateTaskRequest.php index 501861c48ed9..2046a5e8f868 100644 --- a/app/Http/Requests/Task/UpdateTaskRequest.php +++ b/app/Http/Requests/Task/UpdateTaskRequest.php @@ -29,7 +29,7 @@ class UpdateTaskRequest extends Request * @return bool */ public function authorize() : bool - { + {nlog("oioi"); //prevent locked tasks from updating if($this->task->invoice_id && $this->task->company->invoice_task_lock) return false; diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php index ecaf942e9e37..695e4f0b34fa 100644 --- a/app/Jobs/Mail/NinjaMailerJob.php +++ b/app/Jobs/Mail/NinjaMailerJob.php @@ -649,6 +649,9 @@ class NinjaMailerJob implements ShouldQueue public function failed($exception = null) { + if($exception) + nlog($exception->getMessage()); + config(['queue.failed.driver' => null]); } diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index 222368dd3ab6..4117a9b72ff7 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -432,8 +432,6 @@ class MailBuild $pdf = ((new CreateRawPdf($this->mail_entity->invitation, $this->mail_entity->invitation->company->db))->handle()); - nlog($this->mail_entity->mail_object->attachments); - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->{$this->mail_entity->mail_object->entity_string}->numberFormatter().'.pdf']]); if ($this->client->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { diff --git a/app/Utils/HtmlEngine.php b/app/Utils/HtmlEngine.php index ad80141063d7..c39afbdc67b8 100644 --- a/app/Utils/HtmlEngine.php +++ b/app/Utils/HtmlEngine.php @@ -147,7 +147,7 @@ class HtmlEngine $data['$invoice.datetime'] = &$data['$entity.datetime']; $data['$quote.datetime'] = &$data['$entity.datetime']; $data['$credit.datetime'] = &$data['$entity.datetime']; - $data['$payment_button'] = ['value' => ''.ctrans('texts.pay_now').'', 'label' => ctrans('texts.pay_now')]; + $data['$payment_button'] = ['value' => $this->buildViewButton($this->invitation->getPaymentLink(), ctrans('texts.pay_now')), 'label' => ctrans('texts.pay_now')]; $data['$payment_link'] = ['value' => $this->invitation->getPaymentLink(), 'label' => ctrans('texts.pay_now')]; $data['$payment_qrcode'] = ['value' => $this->invitation->getPaymentQrCode(), 'label' => ctrans('texts.pay_now')]; @@ -159,7 +159,7 @@ class HtmlEngine $data['$number_short'] = ['value' => $this->entity->number ?: ' ', 'label' => ctrans('texts.invoice_number_short')]; $data['$entity.terms'] = ['value' => Helpers::processReservedKeywords(\nl2br($this->entity->terms ?: ''), $this->client) ?: '', 'label' => ctrans('texts.invoice_terms')]; $data['$terms'] = &$data['$entity.terms']; - $data['$view_link'] = ['value' => ''.ctrans('texts.view_invoice').'', 'label' => ctrans('texts.view_invoice')]; + $data['$view_link'] = ['value' => $this->buildViewButton($this->invitation->getLink(), ctrans('texts.view_invoice')), 'label' => ctrans('texts.view_invoice')]; $data['$viewLink'] = &$data['$view_link']; $data['$viewButton'] = &$data['$view_link']; $data['$view_button'] = &$data['$view_link']; @@ -218,11 +218,11 @@ class HtmlEngine $data['$number_short'] = ['value' => $this->entity->number ?: '', 'label' => ctrans('texts.quote_number_short')]; $data['$entity.terms'] = ['value' => Helpers::processReservedKeywords(\nl2br($this->entity->terms ?: ''), $this->client) ?: '', 'label' => ctrans('texts.quote_terms')]; $data['$terms'] = &$data['$entity.terms']; - $data['$view_link'] = ['value' => ''.ctrans('texts.view_quote').'', 'label' => ctrans('texts.view_quote')]; + $data['$view_link'] = ['value' => $this->buildViewButton($this->invitation->getLink(), ctrans('texts.view_quote')), 'label' => ctrans('texts.view_quote')]; $data['$viewLink'] = &$data['$view_link']; $data['$viewButton'] = &$data['$view_link']; $data['$view_button'] = &$data['$view_link']; - $data['$approveButton'] = ['value' => ''.ctrans('texts.view_quote').'', 'label' => ctrans('texts.approve')]; + $data['$approveButton'] = ['value' => $this->buildViewButton($this->invitation->getLink(), ctrans('texts.view_quote')), 'label' => ctrans('texts.approve')]; $data['$view_url'] = ['value' => $this->invitation->getLink(), 'label' => ctrans('texts.view_quote')]; $data['$date'] = ['value' => $this->translateDate($this->entity->date, $this->client->date_format(), $this->client->locale()) ?: ' ', 'label' => ctrans('texts.quote_date')]; @@ -263,7 +263,7 @@ class HtmlEngine $data['$number_short'] = ['value' => $this->entity->number ?: '', 'label' => ctrans('texts.credit_number_short')]; $data['$entity.terms'] = ['value' => Helpers::processReservedKeywords(\nl2br($this->entity->terms ?: ''), $this->client) ?: '', 'label' => ctrans('texts.credit_terms')]; $data['$terms'] = &$data['$entity.terms']; - $data['$view_link'] = ['value' => ''.ctrans('texts.view_credit').'', 'label' => ctrans('texts.view_credit')]; + $data['$view_link'] = ['value' => $this->buildViewButton($this->invitation->getLink(), ctrans('texts.view_credit')), 'label' => ctrans('texts.view_credit')]; $data['$viewButton'] = &$data['$view_link']; $data['$view_button'] = &$data['$view_link']; $data['$viewLink'] = &$data['$view_link']; @@ -489,7 +489,7 @@ class HtmlEngine $data['$contact.last_name'] = ['value' => isset($this->contact) ? $this->contact->last_name : '', 'label' => ctrans('texts.last_name')]; - $data['$portal_button'] = ['value' => ''.ctrans('texts.view_client_portal').'', 'label' => ctrans('view_client_portal')]; + $data['$portal_button'] = ['value' => $this->buildViewButton($this->contact->getLoginLink().'?client_hash='.$this->client->client_hash, ctrans('texts.view_client_portal')), 'label' => ctrans('view_client_portal')]; $data['$contact.portal_button'] = &$data['$portal_button']; $data['$portalButton'] = &$data['$portal_button']; @@ -984,4 +984,24 @@ html { return $html; } + + /** + * buildViewButton + * + * @param string $link + * @param string $text + * @return string + */ + private function buildViewButton(string $link, string $text): string + { + return ' + + + + +
+ '. $text .' +
+ '; + } } diff --git a/resources/views/email/admin/download_credits.blade.php b/resources/views/email/admin/download_credits.blade.php index d408647715e1..f82acaa78ca5 100644 --- a/resources/views/email/admin/download_credits.blade.php +++ b/resources/views/email/admin/download_credits.blade.php @@ -3,8 +3,20 @@

{{ ctrans('texts.credits_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

- + + + + + + + +
+ + {{ ctrans('texts.download') }} + +
+ @endcomponent diff --git a/resources/views/email/admin/download_documents.blade.php b/resources/views/email/admin/download_documents.blade.php index a428452a1953..13300defede4 100644 --- a/resources/views/email/admin/download_documents.blade.php +++ b/resources/views/email/admin/download_documents.blade.php @@ -3,8 +3,19 @@

{{ ctrans('texts.document_download_subject') }}

{{ ctrans('texts.download_timeframe') }}

-
+ + + + + + + +
+ + {{ ctrans('texts.download') }} + +
@endcomponent diff --git a/resources/views/email/admin/download_files.blade.php b/resources/views/email/admin/download_files.blade.php index 292208a908b7..f556c3a7dd49 100644 --- a/resources/views/email/admin/download_files.blade.php +++ b/resources/views/email/admin/download_files.blade.php @@ -3,8 +3,15 @@

{{ ctrans('texts.download_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

-
- {{ ctrans('texts.download') }} - + + + + +
+ + {{ ctrans('texts.download') }} + +
+ @endcomponent diff --git a/resources/views/email/admin/download_invoices.blade.php b/resources/views/email/admin/download_invoices.blade.php index 5a3bbb14c483..14bb01ade58b 100644 --- a/resources/views/email/admin/download_invoices.blade.php +++ b/resources/views/email/admin/download_invoices.blade.php @@ -3,8 +3,19 @@

{{ ctrans('texts.invoices_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

- + + + + + + + +
+ + {{ ctrans('texts.download') }} + +
@endcomponent diff --git a/resources/views/email/admin/download_purchase_orders.blade.php b/resources/views/email/admin/download_purchase_orders.blade.php index ce40579d97ea..96e1a676ec8d 100644 --- a/resources/views/email/admin/download_purchase_orders.blade.php +++ b/resources/views/email/admin/download_purchase_orders.blade.php @@ -3,8 +3,19 @@

{{ ctrans('texts.purchase_orders_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

-
+ + + + + + + +
+ + {{ ctrans('texts.download') }} + +
@endcomponent diff --git a/resources/views/email/admin/download_quotes.blade.php b/resources/views/email/admin/download_quotes.blade.php index d98daec5ac63..ee033e75a5d6 100644 --- a/resources/views/email/admin/download_quotes.blade.php +++ b/resources/views/email/admin/download_quotes.blade.php @@ -2,9 +2,20 @@

{{ ctrans('texts.quotes_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

- + + + + + + +
+ + {{ ctrans('texts.download') }} + +
+
@endcomponent diff --git a/resources/views/email/admin/download_report.blade.php b/resources/views/email/admin/download_report.blade.php index c5b2c385ea3e..036757c5a376 100644 --- a/resources/views/email/admin/download_report.blade.php +++ b/resources/views/email/admin/download_report.blade.php @@ -3,5 +3,16 @@

{{ ctrans('texts.download_files') }}

{{ ctrans('texts.download_report_description') }}

+ + + + +
+ + {{ ctrans('texts.download') }} + +
+ + @endcomponent diff --git a/resources/views/email/admin/generic.blade.php b/resources/views/email/admin/generic.blade.php index 7985594ff734..ddc4a2d12ccb 100644 --- a/resources/views/email/admin/generic.blade.php +++ b/resources/views/email/admin/generic.blade.php @@ -27,7 +27,18 @@ @endisset @isset($url) -
{{ ctrans($button) }} + + + + + + +
+ + {{ ctrans($button) }} + +
+ @endisset @isset($signature) diff --git a/resources/views/email/admin/generic_email.blade.php b/resources/views/email/admin/generic_email.blade.php index d439347a7143..3813b3a42544 100644 --- a/resources/views/email/admin/generic_email.blade.php +++ b/resources/views/email/admin/generic_email.blade.php @@ -5,7 +5,15 @@ {{ ctrans("texts.{$body}") }} @isset($view_link) - {{{ $view_text }}} + + + + + +
+ {{ $view_text }} +
+ @endisset @isset($signature) diff --git a/resources/views/email/auth/verify.blade.php b/resources/views/email/auth/verify.blade.php index d975af40e3c5..4c3e94fe58c2 100644 --- a/resources/views/email/auth/verify.blade.php +++ b/resources/views/email/auth/verify.blade.php @@ -2,8 +2,20 @@ @endcomponent diff --git a/resources/views/email/billing/passwordless-login.blade.php b/resources/views/email/billing/passwordless-login.blade.php index 6ab144802f7e..b9bb676770e9 100644 --- a/resources/views/email/billing/passwordless-login.blade.php +++ b/resources/views/email/billing/passwordless-login.blade.php @@ -3,6 +3,17 @@

{{ ctrans('texts.login_link_requested_label') }}

{{ ctrans('texts.login_link_requested') }}

-
{{ ctrans('texts.login')}} + + + + + + +
+ + {{ ctrans('texts.login')}} + +
+ @endcomponent diff --git a/resources/views/email/client/generic.blade.php b/resources/views/email/client/generic.blade.php index da83af7bcb9d..f8ef4934dcc6 100644 --- a/resources/views/email/client/generic.blade.php +++ b/resources/views/email/client/generic.blade.php @@ -21,7 +21,18 @@ @endisset @isset($url) - {{ ctrans($button) }} + + + + + + +
+ + {{ ctrans($button) }} + +
+ @endisset @isset($signature) diff --git a/resources/views/email/components/button.blade.php b/resources/views/email/components/button.blade.php index 13d2f7159f67..405b0c3df97d 100644 --- a/resources/views/email/components/button.blade.php +++ b/resources/views/email/components/button.blade.php @@ -1,3 +1,12 @@ - + + + + + +
+ + {{ $slot }} + +
\ No newline at end of file diff --git a/resources/views/email/gateways/ach-verification-notification.blade.php b/resources/views/email/gateways/ach-verification-notification.blade.php index 765173d62e43..6c75d66bf454 100644 --- a/resources/views/email/gateways/ach-verification-notification.blade.php +++ b/resources/views/email/gateways/ach-verification-notification.blade.php @@ -3,6 +3,17 @@

{{ ctrans('texts.ach_verification_notification_label') }}

{{ ctrans('texts.ach_verification_notification') }}

-
{{ ctrans('texts.complete_verification') }} + + + + + + +
+ + {{ ctrans('texts.complete_verification') }} + +
+ @endcomponent diff --git a/resources/views/email/import/completed.blade.php b/resources/views/email/import/completed.blade.php index d4681962a1be..6883db8aceb1 100644 --- a/resources/views/email/import/completed.blade.php +++ b/resources/views/email/import/completed.blade.php @@ -96,7 +96,17 @@ @endif - {{ ctrans('texts.account_login')}} + + + + + + +
+ + {{ ctrans('texts.account_login') }} + +

{{ ctrans('texts.email_signature')}}

{{ ctrans('texts.email_from') }}

diff --git a/resources/views/email/import/csv_completed.blade.php b/resources/views/email/import/csv_completed.blade.php index 44f196105842..c61f56d2cde8 100644 --- a/resources/views/email/import/csv_completed.blade.php +++ b/resources/views/email/import/csv_completed.blade.php @@ -93,7 +93,17 @@ @endif - {{ ctrans('texts.account_login')}} + + + + + + +
+ + {{ ctrans('texts.account_login') }} + +

{{ ctrans('texts.email_signature')}}

{{ ctrans('texts.email_from') }}

diff --git a/resources/views/email/migration/completed.blade.php b/resources/views/email/migration/completed.blade.php index a099f094953f..d6879ef6debd 100644 --- a/resources/views/email/migration/completed.blade.php +++ b/resources/views/email/migration/completed.blade.php @@ -2,10 +2,20 @@

{{ ctrans('texts.migration_completed')}}

{{ ctrans('texts.migration_completed_description')}}

- + + + + + +
+ + {{ ctrans('texts.account_login') }} + +
+

{{ ctrans('texts.email_signature')}}
{{ ctrans('texts.email_from') }}

diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index 7aecb654c82e..08fb36abe60c 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -68,9 +68,26 @@ .btn-white, [data-ogsc] .btn-white { background-color: #fefefe !important; + mso-padding-alt: 40px; + mso-border-alt: 40px solid #fefefe; + mso-padding-alt: 0; + mso-ansi-font-size:20px !important; + mso-line-height-alt:150%; + mso-border-left-alt: 20 #fefefe 0; + mso-border-right-alt: 20 #fefefe 0; } @endif + .btn-white { + mso-padding-alt: 40px; + mso-border-alt: 40px solid #fefefe; + mso-padding-alt: 0; + mso-ansi-font-size:20px !important; + mso-line-height-alt:150%; + mso-border-left-alt: 20 #FFFFFF 0; + mso-border-right-alt: 20 #FFFFFF 0; + } + /** Content-specific styles. **/ #content .button { display: inline-block; @@ -131,6 +148,12 @@ z-index:200 !important; position: fixed; } + + .new_button { + background-color: {{ $primary_color }}; + } + + @@ -139,8 +162,7 @@
- +
@@ -148,18 +170,9 @@
@@ -167,13 +180,20 @@ + + + + style="background-color: {{ $primary_color }}; ccborder-bottom-color: {{ $primary_color }};">
-
+
- - - - + alt_text
+ style="border: none; padding: 20px;"> {{ $slot }}
+ style="background-color: #242424; border: none;">

© {{ date('Y') }} Invoice Ninja, All Rights Reserved diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index b8e3fca9dbbc..45262ba2a858 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -117,6 +117,9 @@ color: inherit !important; } + .new_button { + background-color: {{ $primary_color }}; + } @@ -135,30 +138,22 @@
- +
+ + - - + diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index 650b0b7f2ce6..6fe1f62058b9 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -148,15 +148,15 @@
-
+
- - - + alt_text
-
-
+
+ style="text-align: center; padding-top: 10px; padding-bottom: 25px; background-color: #f9f9f9; "> @isset($signature)

{!! nl2br($signature) !!} @@ -217,7 +218,7 @@

+ style="padding-top: 10px;padding-bottom: 10px; background-color: #242424; "> @if(isset($company)) @if($company->account->isPaid())

+ @if(\App\Utils\Ninja::isHosted()) + + + + @endif + @if(session()->has('message'))

{{ session('message') }} From 40665bb5b06f1bb65332f4ec9c460314fea916f1 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 21:31:25 +1100 Subject: [PATCH 20/72] Minor fixes --- app/Http/Requests/Report/GenericReportRequest.php | 2 +- lang/en/texts.php | 2 +- .../views/email/admin/download_report.blade.php | 12 ------------ 3 files changed, 2 insertions(+), 14 deletions(-) diff --git a/app/Http/Requests/Report/GenericReportRequest.php b/app/Http/Requests/Report/GenericReportRequest.php index b70ffd7afabc..c17326cfe537 100644 --- a/app/Http/Requests/Report/GenericReportRequest.php +++ b/app/Http/Requests/Report/GenericReportRequest.php @@ -58,7 +58,7 @@ class GenericReportRequest extends Request $input['start_date'] = null; $input['end_date'] = null; } - +nlog($input); $this->replace($input); } diff --git a/lang/en/texts.php b/lang/en/texts.php index 8eace4e16873..dd851787bb5b 100644 --- a/lang/en/texts.php +++ b/lang/en/texts.php @@ -4586,7 +4586,7 @@ $LANG = array( 'alternate_pdf_viewer' => 'Alternate PDF Viewer', 'alternate_pdf_viewer_help' => 'Improve scrolling over the PDF preview [BETA]', 'currency_cayman_island_dollar' => 'Cayman Island Dollar', - 'download_report_description' => 'Please see attached file to check your report.', + 'download_report_description' => 'Your report(s) are attached.', 'left' => 'Left', 'right' => 'Right', 'center' => 'Center', diff --git a/resources/views/email/admin/download_report.blade.php b/resources/views/email/admin/download_report.blade.php index 036757c5a376..132d2ff6507a 100644 --- a/resources/views/email/admin/download_report.blade.php +++ b/resources/views/email/admin/download_report.blade.php @@ -2,17 +2,5 @@

{{ ctrans('texts.download_files') }}

{{ ctrans('texts.download_report_description') }}

- - - - - -
- - {{ ctrans('texts.download') }} - -
- -
@endcomponent From 9745cbed4a2192dd21d9b15997cbdf43e986affa Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 22:31:02 +1100 Subject: [PATCH 21/72] Wind back mailmailer' --- app/Exceptions/Handler.php | 24 ++++++++++++------------ app/Http/Controllers/EmailController.php | 4 ++-- app/Jobs/Mail/NinjaMailerJob.php | 8 ++++++-- app/Mail/Engine/InvoiceEmailEngine.php | 1 + app/Providers/AppServiceProvider.php | 2 +- app/Services/Quote/SendEmail.php | 4 ++-- 6 files changed, 24 insertions(+), 19 deletions(-) diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index a7d534780cec..b19c3525a93e 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -55,18 +55,18 @@ class Handler extends ExceptionHandler ]; protected $selfHostDontReport = [ - FilePermissionsFailure::class, - PDOException::class, - MaxAttemptsExceededException::class, - CommandNotFoundException::class, - ValidationException::class, - ModelNotFoundException::class, - NotFoundHttpException::class, - UnableToCreateDirectory::class, - GuzzleHttp\Exception\ConnectException::class, - Symfony\Component\Process\Exception\RuntimeException::class, - InvalidArgumentException::class, - RuntimeException::class, + // FilePermissionsFailure::class, + // PDOException::class, + // MaxAttemptsExceededException::class, + // CommandNotFoundException::class, + // ValidationException::class, + // ModelNotFoundException::class, + // NotFoundHttpException::class, + // UnableToCreateDirectory::class, + // GuzzleHttp\Exception\ConnectException::class, + // Symfony\Component\Process\Exception\RuntimeException::class, + // InvalidArgumentException::class, + // RuntimeException::class, ]; protected $hostedDontReport = [ diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index 8329a71337bd..d618d8cf0dd9 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -147,9 +147,9 @@ class EmailController extends BaseController if (! $invitation->contact->trashed() && $invitation->contact->email) { $entity_obj->service()->markSent()->save(); - // EmailEntity::dispatch($invitation->fresh(), $invitation->company, $template, $data); + EmailEntity::dispatch($invitation->fresh(), $invitation->company, $template, $data); - MailEntity::dispatch($invitation, $invitation->company->db, $mo); + // MailEntity::dispatch($invitation, $invitation->company->db, $mo); } }); diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php index 695e4f0b34fa..8511280b2cdd 100644 --- a/app/Jobs/Mail/NinjaMailerJob.php +++ b/app/Jobs/Mail/NinjaMailerJob.php @@ -138,6 +138,8 @@ class NinjaMailerJob implements ShouldQueue $mailer->mailgun_config($this->client_mailgun_secret, $this->client_mailgun_domain); } +nlog($this->nmo->to_user->email); + $mailer ->to($this->nmo->to_user->email) ->send($this->nmo->mailable); @@ -393,8 +395,9 @@ class NinjaMailerJob implements ShouldQueue * as the Mailer */ private function setPostmarkMailer() - { + {nlog("configuring postmark"); if(strlen($this->nmo->settings->postmark_secret) > 2){ + nlog($this->nmo->settings->postmark_secret); $this->client_postmark_secret = $this->nmo->settings->postmark_secret; } else{ @@ -406,7 +409,8 @@ class NinjaMailerJob implements ShouldQueue $sending_email = (isset($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; $sending_user = (isset($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); - +nlog($sending_email); +nlog($sending_user); $this->nmo ->mailable ->from($sending_email, $sending_user); diff --git a/app/Mail/Engine/InvoiceEmailEngine.php b/app/Mail/Engine/InvoiceEmailEngine.php index 46b13aabcec3..a089c0696af6 100644 --- a/app/Mail/Engine/InvoiceEmailEngine.php +++ b/app/Mail/Engine/InvoiceEmailEngine.php @@ -217,3 +217,4 @@ class InvoiceEmailEngine extends BaseEmailEngine return $this; } } +} \ No newline at end of file diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index a0c93ab683fb..f7a75620ecf9 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -94,7 +94,7 @@ class AppServiceProvider extends ServiceProvider }); Mailer::macro('postmark_config', function (string $postmark_key) { - + nlog($postmark_key); Mailer::setSymfonyTransport(app('mail.manager')->createSymfonyTransport([ 'transport' => 'postmark', 'token' => $postmark_key diff --git a/app/Services/Quote/SendEmail.php b/app/Services/Quote/SendEmail.php index b060616429ff..9e05fbb74f2c 100644 --- a/app/Services/Quote/SendEmail.php +++ b/app/Services/Quote/SendEmail.php @@ -52,9 +52,9 @@ class SendEmail $this->quote->invitations->each(function ($invitation) use ($mo){ if (! $invitation->contact->trashed() && $invitation->contact->email) { - // EmailEntity::dispatch($invitation, $invitation->company, $this->reminder_template); + EmailEntity::dispatch($invitation, $invitation->company, $this->reminder_template); - MailEntity::dispatch($invitation, $invitation->company->db, $mo); + // MailEntity::dispatch($invitation, $invitation->company->db, $mo); } }); From 8d0b9fef1f5676067bfc2582b0d31775998f4219 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 22:55:18 +1100 Subject: [PATCH 22/72] minor fixes --- app/Http/Controllers/EmailController.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index d618d8cf0dd9..b24d34d0f98b 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -130,10 +130,10 @@ class EmailController extends BaseController ]; $mo = new MailObject; - $mo->subject = empty($subject) ? null : $subject; - $mo->body = empty($body) ? null : $body; - $mo->entity_string = $entity; - $mo->email_template = $template; + // $mo->subject = empty($subject) ? null : $subject; + // $mo->body = empty($body) ? null : $body; + // $mo->entity_string = $entity; + // $mo->email_template = $template; if(Ninja::isHosted() && !$entity_obj->company->account->account_sms_verified) return response(['message' => 'Please verify your account to send emails.'], 400); From 329d3595baaec0a5bc274e8c3289aed5e5f9b2e3 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 23:09:27 +1100 Subject: [PATCH 23/72] Fixes for invoiceemailengine --- app/Jobs/Mail/NinjaMailerJob.php | 11 ++--------- app/Mail/Engine/InvoiceEmailEngine.php | 4 ++-- app/Providers/AppServiceProvider.php | 2 +- 3 files changed, 5 insertions(+), 12 deletions(-) diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php index 8511280b2cdd..ecaf942e9e37 100644 --- a/app/Jobs/Mail/NinjaMailerJob.php +++ b/app/Jobs/Mail/NinjaMailerJob.php @@ -138,8 +138,6 @@ class NinjaMailerJob implements ShouldQueue $mailer->mailgun_config($this->client_mailgun_secret, $this->client_mailgun_domain); } -nlog($this->nmo->to_user->email); - $mailer ->to($this->nmo->to_user->email) ->send($this->nmo->mailable); @@ -395,9 +393,8 @@ nlog($this->nmo->to_user->email); * as the Mailer */ private function setPostmarkMailer() - {nlog("configuring postmark"); + { if(strlen($this->nmo->settings->postmark_secret) > 2){ - nlog($this->nmo->settings->postmark_secret); $this->client_postmark_secret = $this->nmo->settings->postmark_secret; } else{ @@ -409,8 +406,7 @@ nlog($this->nmo->to_user->email); $sending_email = (isset($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; $sending_user = (isset($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); -nlog($sending_email); -nlog($sending_user); + $this->nmo ->mailable ->from($sending_email, $sending_user); @@ -653,9 +649,6 @@ nlog($sending_user); public function failed($exception = null) { - if($exception) - nlog($exception->getMessage()); - config(['queue.failed.driver' => null]); } diff --git a/app/Mail/Engine/InvoiceEmailEngine.php b/app/Mail/Engine/InvoiceEmailEngine.php index a089c0696af6..598db7a00a3d 100644 --- a/app/Mail/Engine/InvoiceEmailEngine.php +++ b/app/Mail/Engine/InvoiceEmailEngine.php @@ -213,8 +213,8 @@ class InvoiceEmailEngine extends BaseEmailEngine } } - + } + return $this; } } -} \ No newline at end of file diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index f7a75620ecf9..a0c93ab683fb 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -94,7 +94,7 @@ class AppServiceProvider extends ServiceProvider }); Mailer::macro('postmark_config', function (string $postmark_key) { - nlog($postmark_key); + Mailer::setSymfonyTransport(app('mail.manager')->createSymfonyTransport([ 'transport' => 'postmark', 'token' => $postmark_key From 7df4274d72c7f644155039b16c412e36a6f49f86 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Wed, 15 Feb 2023 23:23:37 +1100 Subject: [PATCH 24/72] Add back in exception handler list --- app/Exceptions/Handler.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index b19c3525a93e..a7d534780cec 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -55,18 +55,18 @@ class Handler extends ExceptionHandler ]; protected $selfHostDontReport = [ - // FilePermissionsFailure::class, - // PDOException::class, - // MaxAttemptsExceededException::class, - // CommandNotFoundException::class, - // ValidationException::class, - // ModelNotFoundException::class, - // NotFoundHttpException::class, - // UnableToCreateDirectory::class, - // GuzzleHttp\Exception\ConnectException::class, - // Symfony\Component\Process\Exception\RuntimeException::class, - // InvalidArgumentException::class, - // RuntimeException::class, + FilePermissionsFailure::class, + PDOException::class, + MaxAttemptsExceededException::class, + CommandNotFoundException::class, + ValidationException::class, + ModelNotFoundException::class, + NotFoundHttpException::class, + UnableToCreateDirectory::class, + GuzzleHttp\Exception\ConnectException::class, + Symfony\Component\Process\Exception\RuntimeException::class, + InvalidArgumentException::class, + RuntimeException::class, ]; protected $hostedDontReport = [ From eefd2eb5d40ccc198034b4add43211a3c0b0c4c5 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 07:51:12 +1100 Subject: [PATCH 25/72] minor fixes --- app/Http/Controllers/EmailController.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index b24d34d0f98b..8329a71337bd 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -130,10 +130,10 @@ class EmailController extends BaseController ]; $mo = new MailObject; - // $mo->subject = empty($subject) ? null : $subject; - // $mo->body = empty($body) ? null : $body; - // $mo->entity_string = $entity; - // $mo->email_template = $template; + $mo->subject = empty($subject) ? null : $subject; + $mo->body = empty($body) ? null : $body; + $mo->entity_string = $entity; + $mo->email_template = $template; if(Ninja::isHosted() && !$entity_obj->company->account->account_sms_verified) return response(['message' => 'Please verify your account to send emails.'], 400); @@ -147,9 +147,9 @@ class EmailController extends BaseController if (! $invitation->contact->trashed() && $invitation->contact->email) { $entity_obj->service()->markSent()->save(); - EmailEntity::dispatch($invitation->fresh(), $invitation->company, $template, $data); + // EmailEntity::dispatch($invitation->fresh(), $invitation->company, $template, $data); - // MailEntity::dispatch($invitation, $invitation->company->db, $mo); + MailEntity::dispatch($invitation, $invitation->company->db, $mo); } }); From b76e78e9ed23137f0bd75cd430c503fa65575023 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 09:20:24 +1100 Subject: [PATCH 26/72] Fixes for email designs and cross client compatibility --- app/Http/Controllers/EmailController.php | 4 +-- app/Mail/Engine/PaymentEmailEngine.php | 32 +++++++++++++++++-- app/Utils/VendorHtmlEngine.php | 23 ++++++++++++- .../email/admin/download_credits.blade.php | 3 +- .../email/admin/download_documents.blade.php | 2 +- .../email/admin/download_files.blade.php | 2 +- .../email/admin/download_invoices.blade.php | 2 +- .../admin/download_purchase_orders.blade.php | 2 +- .../email/admin/download_quotes.blade.php | 2 +- resources/views/email/admin/generic.blade.php | 2 +- .../views/email/admin/generic_email.blade.php | 2 +- .../views/email/template/admin.blade.php | 5 ++- .../views/email/template/client.blade.php | 10 ++++++ 13 files changed, 75 insertions(+), 16 deletions(-) diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index 8329a71337bd..d618d8cf0dd9 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -147,9 +147,9 @@ class EmailController extends BaseController if (! $invitation->contact->trashed() && $invitation->contact->email) { $entity_obj->service()->markSent()->save(); - // EmailEntity::dispatch($invitation->fresh(), $invitation->company, $template, $data); + EmailEntity::dispatch($invitation->fresh(), $invitation->company, $template, $data); - MailEntity::dispatch($invitation, $invitation->company->db, $mo); + // MailEntity::dispatch($invitation, $invitation->company->db, $mo); } }); diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php index 6a76d5209efe..8213215fbc9f 100644 --- a/app/Mail/Engine/PaymentEmailEngine.php +++ b/app/Mail/Engine/PaymentEmailEngine.php @@ -244,12 +244,12 @@ class PaymentEmailEngine extends BaseEmailEngine $data['$company3'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'company3', $this->settings->custom_value3, $this->client) ?: ' ', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'company3')]; $data['$company4'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'company4', $this->settings->custom_value4, $this->client) ?: ' ', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'company4')]; - $data['$view_link'] = ['value' => ''.ctrans('texts.view_payment').'', 'label' => ctrans('texts.view_payment')]; + $data['$view_link'] = ['value' => $this->buildViewButton($this->payment->getLink(), ctrans('texts.view_payment')), 'label' => ctrans('texts.view_payment')]; $data['$view_button'] = &$data['$view_link']; $data['$viewButton'] = &$data['$view_link']; $data['$viewLink'] = &$data['$view_link']; $data['$paymentLink'] = &$data['$view_link']; - $data['$portalButton'] = ['value' => "".ctrans('texts.login').'', 'label' =>'']; + $data['$portalButton'] = ['value' => $this->buildViewButton($this->payment->getPortalLink(), ctrans('texts.login')), 'label' =>'']; $data['$portal_url'] = &$data['$portalButton']; $data['$view_url'] = ['value' => $this->payment->getLink(), 'label' => ctrans('texts.view_payment')]; @@ -367,7 +367,12 @@ class PaymentEmailEngine extends BaseEmailEngine return $data; } - + + /** + * generateLabelsAndValues + * + * @return void + */ public function generateLabelsAndValues() { $data = []; @@ -381,4 +386,25 @@ class PaymentEmailEngine extends BaseEmailEngine return $data; } + + /** + * buildViewButton + * + * @param string $link + * @param string $text + * @return string + */ + private function buildViewButton(string $link, string $text): string + { + return ' + + + + +
+ '. $text .' +
+ '; + } + } diff --git a/app/Utils/VendorHtmlEngine.php b/app/Utils/VendorHtmlEngine.php index da513836f642..f4b3239158a3 100644 --- a/app/Utils/VendorHtmlEngine.php +++ b/app/Utils/VendorHtmlEngine.php @@ -156,7 +156,7 @@ class VendorHtmlEngine $data['$number_short'] = ['value' => $this->entity->number ?: ' ', 'label' => ctrans('texts.purchase_order_number_short')]; $data['$entity.terms'] = ['value' => Helpers::processReservedKeywords(\nl2br($this->entity->terms), $this->company) ?: '', 'label' => ctrans('texts.invoice_terms')]; $data['$terms'] = &$data['$entity.terms']; - $data['$view_link'] = ['value' => ''.ctrans('texts.view_purchase_order').'', 'label' => ctrans('texts.view_purchase_order')]; + $data['$view_link'] = ['value' => $this->buildViewButton($this->invitation->getLink(), ctrans('texts.view_purchase_order')), 'label' => ctrans('texts.view_purchase_order')]; $data['$viewLink'] = &$data['$view_link']; $data['$viewButton'] = &$data['$view_link']; $data['$view_button'] = &$data['$view_link']; @@ -813,4 +813,25 @@ html { return $dom->saveHTML(); } + + /** + * buildViewButton + * + * @param string $link + * @param string $text + * @return string + */ + private function buildViewButton(string $link, string $text): string + { + return ' + + + + +
+ '. $text .' +
+ '; + } + } diff --git a/resources/views/email/admin/download_credits.blade.php b/resources/views/email/admin/download_credits.blade.php index f82acaa78ca5..c9c9e4abb608 100644 --- a/resources/views/email/admin/download_credits.blade.php +++ b/resources/views/email/admin/download_credits.blade.php @@ -7,12 +7,11 @@ {{ ctrans('texts.download') }} --> - diff --git a/resources/views/email/admin/download_documents.blade.php b/resources/views/email/admin/download_documents.blade.php index 13300defede4..3c8da4cb4434 100644 --- a/resources/views/email/admin/download_documents.blade.php +++ b/resources/views/email/admin/download_documents.blade.php @@ -12,7 +12,7 @@ diff --git a/resources/views/email/admin/download_files.blade.php b/resources/views/email/admin/download_files.blade.php index f556c3a7dd49..035c303e0608 100644 --- a/resources/views/email/admin/download_files.blade.php +++ b/resources/views/email/admin/download_files.blade.php @@ -7,7 +7,7 @@ diff --git a/resources/views/email/admin/download_invoices.blade.php b/resources/views/email/admin/download_invoices.blade.php index 14bb01ade58b..600f04a4346a 100644 --- a/resources/views/email/admin/download_invoices.blade.php +++ b/resources/views/email/admin/download_invoices.blade.php @@ -12,7 +12,7 @@ diff --git a/resources/views/email/admin/download_purchase_orders.blade.php b/resources/views/email/admin/download_purchase_orders.blade.php index 96e1a676ec8d..e8d1d089efef 100644 --- a/resources/views/email/admin/download_purchase_orders.blade.php +++ b/resources/views/email/admin/download_purchase_orders.blade.php @@ -12,7 +12,7 @@ diff --git a/resources/views/email/admin/download_quotes.blade.php b/resources/views/email/admin/download_quotes.blade.php index ee033e75a5d6..c54446e42487 100644 --- a/resources/views/email/admin/download_quotes.blade.php +++ b/resources/views/email/admin/download_quotes.blade.php @@ -11,7 +11,7 @@ diff --git a/resources/views/email/admin/generic.blade.php b/resources/views/email/admin/generic.blade.php index ddc4a2d12ccb..2f18f3d4b6c3 100644 --- a/resources/views/email/admin/generic.blade.php +++ b/resources/views/email/admin/generic.blade.php @@ -33,7 +33,7 @@ diff --git a/resources/views/email/admin/generic_email.blade.php b/resources/views/email/admin/generic_email.blade.php index 3813b3a42544..be32dcf1aa21 100644 --- a/resources/views/email/admin/generic_email.blade.php +++ b/resources/views/email/admin/generic_email.blade.php @@ -9,7 +9,7 @@
- {{ ctrans('texts.download') }} + {{ ctrans('texts.download') }}
- {{ ctrans('texts.download') }} + {{ ctrans('texts.download') }}
- {{ ctrans('texts.download') }} + {{ ctrans('texts.download') }}
- {{ ctrans('texts.download') }} + {{ ctrans('texts.download') }}
- {{ ctrans('texts.download') }} + {{ ctrans('texts.download') }}
- {{ ctrans('texts.download') }} + {{ ctrans('texts.download') }}
- {{ ctrans($button) }} + {{ ctrans($button) }}
- {{ $view_text }} + {{ $view_text }}
diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index 08fb36abe60c..d591dfc28d55 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -149,10 +149,13 @@ position: fixed; } - .new_button { + .new_button, a { background-color: {{ $primary_color }}; } + a:visited { + color:#ffffff !important; + } diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index 45262ba2a858..650b0b7f2ce6 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -119,6 +119,16 @@ .new_button { background-color: {{ $primary_color }}; + + } + } + + .new_button, { + background-color: {{ $primary_color }}; + } + + a:visited { + color:#ffffff !important; } From b8c7a0837a4753f7eb47c4b82dc9eafd624a261e Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 10:05:28 +1100 Subject: [PATCH 27/72] Updates for base email templates --- resources/views/email/template/admin.blade.php | 8 +++----- resources/views/email/template/client.blade.php | 6 +++--- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index d591dfc28d55..fda533695bcf 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -171,12 +171,10 @@
+
- - alt_text - + alt_text
- +
- + From 5324d78e86a109549caf1e4819934dc29382328c Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 10:10:15 +1100 Subject: [PATCH 28/72] Fixes for email designs and cross client compatibility --- resources/views/email/template/admin.blade.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index fda533695bcf..f00bfff65f19 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -167,12 +167,12 @@
- alt_text + alt_text
-
+
- - +
+
alt_text
From 9e88019fc593ebb5c91690dd55ae817584da029c Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 10:11:51 +1100 Subject: [PATCH 29/72] Fixes for email designs and cross client compatibility --- resources/views/email/template/client.blade.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index 6fe1f62058b9..2f0489226204 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -150,7 +150,7 @@
-
+
From 1d9f32a8a8d58aa57a32a6ee951e8778b7990012 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 10:12:00 +1100 Subject: [PATCH 30/72] Fixes for email designs and cross client compatibility --- resources/views/email/template/admin.blade.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index f00bfff65f19..d7826e51c952 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -167,7 +167,7 @@ -
+
From 4c77739bcda279ff193b9788dd4f407c902eb9c2 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 10:29:18 +1100 Subject: [PATCH 31/72] Fixes for email designs and cross client compatibility --- resources/views/email/template/admin.blade.php | 7 +------ resources/views/email/template/client.blade.php | 11 +++-------- 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index d7826e51c952..34f9de1e7858 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -166,14 +166,9 @@
- -
- -
- diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index 2f0489226204..7bb1ec595313 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -150,21 +150,16 @@
-
+
alt_text
-
- - - -
-
- +
+
alt_text
+
-
{{ $slot ?? '' }} {!! $body ?? '' !!} From f3fe723bfd4a842305fcccc93df436207027b5f0 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 10:48:21 +1100 Subject: [PATCH 32/72] Fixes for email designs and cross client compatibility --- resources/views/email/template/client.blade.php | 6 ------ 1 file changed, 6 deletions(-) diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index 7bb1ec595313..d306540f7b92 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -117,12 +117,6 @@ color: inherit !important; } - .new_button { - background-color: {{ $primary_color }}; - - } - } - .new_button, { background-color: {{ $primary_color }}; } From 78fadf49e3517270a1472bdc2a8683f7c26fc69f Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 10:59:31 +1100 Subject: [PATCH 33/72] Fixes for email designs and cross client compatibility --- app/Utils/HtmlEngine.php | 1 - app/Utils/VendorHtmlEngine.php | 2 -- resources/views/email/template/client.blade.php | 4 ++-- 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/app/Utils/HtmlEngine.php b/app/Utils/HtmlEngine.php index c39afbdc67b8..aea963783fa1 100644 --- a/app/Utils/HtmlEngine.php +++ b/app/Utils/HtmlEngine.php @@ -940,7 +940,6 @@ html { '; $css .= 'font-size:'.$this->settings->font_size.'px;'; -// $css .= 'font-size:14px;'; $css .= '}'; diff --git a/app/Utils/VendorHtmlEngine.php b/app/Utils/VendorHtmlEngine.php index f4b3239158a3..c57d79d44870 100644 --- a/app/Utils/VendorHtmlEngine.php +++ b/app/Utils/VendorHtmlEngine.php @@ -773,8 +773,6 @@ html { '; $css .= 'font-size:'.$this->settings->font_size.'px;'; -// $css .= 'font-size:14px;'; - $css .= '}'; return $css; diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index d306540f7b92..d5b3871ad519 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -117,8 +117,8 @@ color: inherit !important; } - .new_button, { - background-color: {{ $primary_color }}; + .new_button, a { + background-color: {{ $primary_color }} !important; } a:visited { From a25daa814441f2409f32935dfbaa2949e7483c9a Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 12:31:13 +1100 Subject: [PATCH 34/72] update composer requirements" " --- app/Services/Email/MailEntity.php | 10 +- composer.json | 1 + composer.lock | 233 +++++++++++++++++++++++++++++- 3 files changed, 242 insertions(+), 2 deletions(-) diff --git a/app/Services/Email/MailEntity.php b/app/Services/Email/MailEntity.php index f0e24133f7e3..3ba13719f267 100644 --- a/app/Services/Email/MailEntity.php +++ b/app/Services/Email/MailEntity.php @@ -53,7 +53,15 @@ class MailEntity implements ShouldQueue public int $tries = 4; public $deleteWhenMissingModels = true; - + + /** + * __construct + * + * @param mixed $invitation + * @param mixed $db + * @param mixed $mail_object + * @return void + */ public function __construct(public mixed $invitation, private ?string $db, public MailObject $mail_object){} /** diff --git a/composer.json b/composer.json index a9fd6cad3f2d..ca7e50171d8c 100644 --- a/composer.json +++ b/composer.json @@ -101,6 +101,7 @@ "darkaonline/l5-swagger": "8.1.0", "fakerphp/faker": "^1.14", "filp/whoops": "^2.7", + "friendsofphp/php-cs-fixer": "^3.14", "laracasts/cypress": "^3.0", "laravel/dusk": "^6.15", "mockery/mockery": "^1.4.4", diff --git a/composer.lock b/composer.lock index 5381e6ec4340..399e21c705f2 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "0c7d0b98049debcdc39406241b36770a", + "content-hash": "dfdb363c199d15bed79f289c88ddd67e", "packages": [ { "name": "afosto/yaac", @@ -13861,6 +13861,96 @@ ], "time": "2022-11-02T16:23:29+00:00" }, + { + "name": "friendsofphp/php-cs-fixer", + "version": "v3.14.2", + "source": { + "type": "git", + "url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git", + "reference": "14f0541651841b63640e7aafad041ad55dc7aa88" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/14f0541651841b63640e7aafad041ad55dc7aa88", + "reference": "14f0541651841b63640e7aafad041ad55dc7aa88", + "shasum": "" + }, + "require": { + "composer/semver": "^3.3", + "composer/xdebug-handler": "^3.0.3", + "doctrine/annotations": "^1.14.2 || ^2", + "doctrine/lexer": "^2", + "ext-json": "*", + "ext-tokenizer": "*", + "php": "^7.4 || ^8.0", + "sebastian/diff": "^4.0", + "symfony/console": "^5.4 || ^6.0", + "symfony/event-dispatcher": "^5.4 || ^6.0", + "symfony/filesystem": "^5.4 || ^6.0", + "symfony/finder": "^5.4 || ^6.0", + "symfony/options-resolver": "^5.4 || ^6.0", + "symfony/polyfill-mbstring": "^1.27", + "symfony/polyfill-php80": "^1.27", + "symfony/polyfill-php81": "^1.27", + "symfony/process": "^5.4 || ^6.0", + "symfony/stopwatch": "^5.4 || ^6.0" + }, + "require-dev": { + "justinrainbow/json-schema": "^5.2", + "keradus/cli-executor": "^2.0", + "mikey179/vfsstream": "^1.6.11", + "php-coveralls/php-coveralls": "^2.5.3", + "php-cs-fixer/accessible-object": "^1.1", + "php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.2", + "php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.2.1", + "phpspec/prophecy": "^1.16", + "phpspec/prophecy-phpunit": "^2.0", + "phpunit/phpunit": "^9.5", + "phpunitgoodpractices/polyfill": "^1.6", + "phpunitgoodpractices/traits": "^1.9.2", + "symfony/phpunit-bridge": "^6.2.3", + "symfony/yaml": "^5.4 || ^6.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "support": { + "issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues", + "source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.14.2" + }, + "funding": [ + { + "url": "https://github.com/keradus", + "type": "github" + } + ], + "time": "2023-01-29T23:47:01+00:00" + }, { "name": "hamcrest/hamcrest-php", "version": "v2.0.1", @@ -16515,6 +16605,147 @@ }, "time": "2021-10-14T14:25:14+00:00" }, + { + "name": "symfony/polyfill-php81", + "version": "v1.27.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php81.git", + "reference": "707403074c8ea6e2edaf8794b0157a0bfa52157a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php81/zipball/707403074c8ea6e2edaf8794b0157a0bfa52157a", + "reference": "707403074c8ea6e2edaf8794b0157a0bfa52157a", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.27-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php81\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php81/tree/v1.27.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-11-03T14:55:06+00:00" + }, + { + "name": "symfony/stopwatch", + "version": "v6.2.5", + "source": { + "type": "git", + "url": "https://github.com/symfony/stopwatch.git", + "reference": "00b6ac156aacffc53487c930e0ab14587a6607f6" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/00b6ac156aacffc53487c930e0ab14587a6607f6", + "reference": "00b6ac156aacffc53487c930e0ab14587a6607f6", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony/service-contracts": "^1|^2|^3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Stopwatch\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides a way to profile code", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/stopwatch/tree/v6.2.5" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2023-01-01T08:36:55+00:00" + }, { "name": "symfony/yaml", "version": "v5.4.19", From 4babfbb6511f6eb4a2f62b77aa4c1bd458564b20 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 12:36:09 +1100 Subject: [PATCH 35/72] php-cs-fixer --- .php_cs | 19 - app/Console/Commands/BackupUpdate.php | 48 +- app/Console/Commands/CheckData.php | 346 +++---- app/Console/Commands/CheckDb.php | 9 - app/Console/Commands/CreateAccount.php | 23 - app/Console/Commands/CreateSingleAccount.php | 49 +- app/Console/Commands/CreateTestData.php | 1 - app/Console/Commands/DemoMode.php | 1 - app/Console/Commands/DesignUpdate.php | 1 - app/Console/Commands/HostedMigrations.php | 8 - app/Console/Commands/HostedUsers.php | 2 - app/Console/Commands/MobileLocalization.php | 2 - app/Console/Commands/OpenApiYaml.php | 21 +- app/Console/Commands/PostUpdate.php | 1 - app/Console/Commands/ReactBuilder.php | 5 - app/Console/Commands/SendRemindersCron.php | 2 - app/Console/Commands/SendTestEmails.php | 8 - app/Console/Commands/TranslationsExport.php | 28 +- app/Console/Commands/TypeCheck.php | 6 - app/Console/Kernel.php | 9 +- app/DataMapper/BaseSettings.php | 1 - app/DataMapper/CompanySettings.php | 1 - app/DataMapper/EmailTemplateDefaults.php | 4 +- app/DataMapper/Schedule/ClientStatement.php | 20 +- .../Transactions/ClientStatusTransaction.php | 4 - .../GatewayPaymentMadeTransaction.php | 4 - .../InvoiceCancelledTransaction.php | 4 - .../InvoiceDeletedTransaction.php | 4 - .../InvoiceFeeAppliedTransaction.php | 4 - .../InvoicePaymentTransaction.php | 4 - .../InvoiceReversalTransaction.php | 4 - .../InvoiceUpdatedTransaction.php | 4 - .../Transactions/MarkPaidTransaction.php | 4 - .../PaymentAppliedTransaction.php | 4 - .../PaymentDeletedTransaction.php | 4 - .../Transactions/PaymentFailedTransaction.php | 4 - .../Transactions/PaymentMadeTransaction.php | 4 - .../PaymentRefundedTransaction.php | 4 - .../PurchaseOrderWasAccepted.php | 1 - .../Subscription/SubscriptionWasCreated.php | 3 - app/Exceptions/Handler.php | 16 +- app/Exceptions/PaymentFailed.php | 3 +- app/Exceptions/PaymentRefundFailed.php | 1 - app/Exceptions/YodleeApiException.php | 1 - app/Export/CSV/BaseExport.php | 2 - app/Export/CSV/ClientExport.php | 7 +- app/Export/CSV/CreditExport.php | 1 - app/Export/CSV/DocumentExport.php | 2 - app/Export/CSV/ExpenseExport.php | 1 - app/Export/CSV/InvoiceExport.php | 1 - app/Export/CSV/InvoiceItemExport.php | 63 +- app/Export/CSV/PaymentExport.php | 2 - app/Export/CSV/ProductExport.php | 2 - app/Export/CSV/ProductSalesExport.php | 13 +- app/Export/CSV/QuoteExport.php | 1 - app/Export/CSV/QuoteItemExport.php | 1 - app/Export/CSV/RecurringInvoiceExport.php | 1 - app/Export/CSV/TaskExport.php | 1 - app/Factory/BankIntegrationFactory.php | 1 - app/Factory/BankTransactionFactory.php | 1 - app/Factory/BankTransactionRuleFactory.php | 1 - app/Factory/ClientGatewayTokenFactory.php | 1 - app/Factory/CompanyGatewayFactory.php | 1 - app/Factory/PurchaseOrderFactory.php | 1 - .../PurchaseOrderInvitationFactory.php | 1 - .../RecurringExpenseToExpenseFactory.php | 16 +- app/Factory/UserFactory.php | 1 - app/Filters/BankIntegrationFilters.php | 2 - app/Filters/BankTransactionFilters.php | 21 +- app/Filters/BankTransactionRuleFilters.php | 1 - app/Filters/ClientFilters.php | 8 +- app/Filters/CreditFilters.php | 12 +- app/Filters/DesignFilters.php | 6 +- app/Filters/DocumentFilters.php | 9 +- app/Filters/ExpenseCategoryFilters.php | 4 +- app/Filters/ExpenseFilters.php | 34 +- app/Filters/InvoiceFilters.php | 39 +- app/Filters/PaymentFilters.php | 11 +- app/Filters/ProjectFilters.php | 3 +- app/Filters/PurchaseOrderFilters.php | 17 +- app/Filters/QueryFilters.php | 30 +- app/Filters/QuoteFilters.php | 39 +- app/Filters/RecurringInvoiceFilters.php | 13 +- app/Filters/TaskFilters.php | 1 - app/Filters/UserFilters.php | 10 +- .../Bank/AccountTransformerInterface.php | 2 +- app/Helpers/Bank/BankExpenseInterface.php | 1 - .../Yodlee/Transformer/AccountTransformer.php | 15 +- .../Yodlee/Transformer/ExpenseTransformer.php | 5 +- .../Yodlee/Transformer/IncomeTransformer.php | 30 +- app/Helpers/Bank/Yodlee/Yodlee.php | 143 ++- app/Helpers/ClientPortal.php | 4 +- app/Helpers/Epc/EpcQrGenerator.php | 38 +- app/Helpers/Generic.php | 2 +- app/Helpers/Invoice/InvoiceItemSum.php | 2 - app/Helpers/Invoice/InvoiceSum.php | 3 - app/Helpers/Invoice/ProRata.php | 2 - app/Helpers/Mail/GmailTransport.php | 24 +- app/Helpers/Mail/Office365MailTransport.php | 17 +- .../Subscription/SubscriptionCalculator.php | 1 - app/Helpers/SwissQr/SwissQrGenerator.php | 232 ++--- app/Http/Controllers/ActivityController.php | 7 +- .../Auth/ContactForgotPasswordController.php | 1 - .../Auth/ContactLoginController.php | 10 +- .../Auth/ContactRegisterController.php | 3 +- app/Http/Controllers/Auth/LoginController.php | 25 +- .../Auth/VendorContactLoginController.php | 11 - .../Controllers/Bank/YodleeController.php | 52 +- .../Controllers/BankIntegrationController.php | 40 +- .../Controllers/BankTransactionController.php | 30 +- .../BankTransactionRuleController.php | 22 +- app/Http/Controllers/BaseController.php | 230 ++--- app/Http/Controllers/ClientController.php | 22 +- .../ClientGatewayTokenController.php | 6 - .../ClientPortal/ApplePayDomainController.php | 3 - .../ClientPortal/DocumentController.php | 2 +- .../ClientPortal/InvitationController.php | 98 +- .../ClientPortal/InvoiceController.php | 5 +- .../ClientPortal/NinjaPlanController.php | 7 +- .../ClientPortal/PaymentController.php | 29 +- .../ClientPortal/PaymentMethodController.php | 1 - .../ClientPortal/QuoteController.php | 18 +- .../RecurringInvoiceController.php | 9 +- .../ClientPortal/SubscriptionController.php | 4 +- .../SubscriptionPlanSwitchController.php | 6 +- .../SubscriptionPurchaseController.php | 12 +- .../ClientPortal/SwitchCompanyController.php | 1 - .../Controllers/ClientStatementController.php | 17 +- app/Http/Controllers/CompanyController.php | 5 - .../Controllers/CompanyGatewayController.php | 5 +- .../ConnectedAccountController.php | 14 +- .../Controllers/Contact/LoginController.php | 2 - app/Http/Controllers/CreditController.php | 22 +- app/Http/Controllers/DesignController.php | 1 - app/Http/Controllers/DocumentController.php | 1 - app/Http/Controllers/EmailController.php | 13 +- app/Http/Controllers/ExpenseController.php | 1 - app/Http/Controllers/FilterController.php | 4 - .../Gateways/Mollie3dsController.php | 1 - .../Controllers/GroupSettingController.php | 1 - .../Controllers/HostedMigrationController.php | 3 - app/Http/Controllers/ImportController.php | 5 +- app/Http/Controllers/ImportJsonController.php | 6 - .../InAppPurchase/AppleController.php | 1 - app/Http/Controllers/InvoiceController.php | 31 +- app/Http/Controllers/LicenseController.php | 1 - app/Http/Controllers/LogoutController.php | 2 - .../Controllers/OneTimeTokenController.php | 1 - .../OpenAPI/BankTransactionRule.php | 2 +- app/Http/Controllers/PaymentController.php | 6 +- .../PaymentNotificationWebhookController.php | 2 - .../Controllers/PaymentWebhookController.php | 3 +- app/Http/Controllers/PostMarkController.php | 12 - app/Http/Controllers/PreviewController.php | 83 +- .../PreviewPurchaseOrderController.php | 84 +- app/Http/Controllers/ProductController.php | 1 - app/Http/Controllers/ProjectController.php | 1 - .../Controllers/PurchaseOrderController.php | 49 +- app/Http/Controllers/QuoteController.php | 29 +- .../RecurringExpenseController.php | 1 - .../RecurringInvoiceController.php | 1 - .../Reports/ProductSalesReportController.php | 2 - .../Reports/ProfitAndLossController.php | 1 - app/Http/Controllers/SetupController.php | 4 - app/Http/Controllers/StaticController.php | 6 - .../Controllers/StripeConnectController.php | 8 +- app/Http/Controllers/StripeController.php | 1 - app/Http/Controllers/TaskController.php | 1 - .../Controllers/TaskSchedulerController.php | 10 +- app/Http/Controllers/TaskStatusController.php | 6 +- app/Http/Controllers/TaxRateController.php | 1 - app/Http/Controllers/TemplateController.php | 3 - app/Http/Controllers/TokenController.php | 1 - app/Http/Controllers/TwilioController.php | 38 +- app/Http/Controllers/TwoFactorController.php | 1 - app/Http/Controllers/UserController.php | 22 +- app/Http/Controllers/VendorController.php | 1 - .../VendorPortal/DocumentController.php | 4 +- .../VendorPortal/InvitationController.php | 56 +- .../VendorPortal/PurchaseOrderController.php | 4 +- .../VendorPortal/UploadController.php | 1 - .../VendorPortal/VendorContactController.php | 1 - .../VendorContactHashLoginController.php | 4 - app/Http/Controllers/WePayController.php | 1 - app/Http/Controllers/WebhookController.php | 1 - app/Http/Livewire/BillingPortalPurchase.php | 48 +- app/Http/Livewire/BillingPortalPurchasev2.php | 301 +++--- app/Http/Livewire/DocumentsTable.php | 2 +- app/Http/Livewire/PurchaseOrdersTable.php | 1 - app/Http/Livewire/QuotesTable.php | 6 +- .../RecurringInvoices/UpdateAutoBilling.php | 2 +- app/Http/Livewire/RequiredClientInfo.php | 13 +- app/Http/Livewire/SubscriptionPlanSwitch.php | 6 +- app/Http/Livewire/WepaySignup.php | 1 - app/Http/Middleware/ContactAccount.php | 1 - app/Http/Middleware/ContactKeyLogin.php | 12 +- app/Http/Middleware/Cors.php | 1 - app/Http/Middleware/Locale.php | 2 - app/Http/Middleware/PasswordProtection.php | 60 +- app/Http/Middleware/QueryLogging.php | 3 +- .../Middleware/RedirectIfAuthenticated.php | 2 +- app/Http/Middleware/SessionDomains.php | 1 - app/Http/Middleware/SetInviteDb.php | 1 - app/Http/Middleware/StartupCheck.php | 1 - app/Http/Middleware/TokenAuth.php | 3 +- app/Http/Middleware/UserVerified.php | 2 - app/Http/Middleware/VendorContactKeyLogin.php | 3 - app/Http/Middleware/VendorLocale.php | 1 - app/Http/Middleware/VerifyHash.php | 11 +- .../Requests/Account/UpdateAccountRequest.php | 4 - .../AdminBankIntegrationRequest.php | 1 - .../BulkBankIntegrationRequest.php | 2 - .../StoreBankIntegrationRequest.php | 5 +- .../UpdateBankIntegrationRequest.php | 1 - .../AdminBankTransactionRequest.php | 1 - .../BulkBankTransactionRequest.php | 2 - .../ImportBankTransactionsRequest.php | 17 +- .../MatchBankTransactionRequest.php | 29 +- .../StoreBankTransactionRequest.php | 12 +- .../UpdateBankTransactionRequest.php | 39 +- .../BulkBankTransactionRuleRequest.php | 2 - .../StoreBankTransactionRuleRequest.php | 19 +- .../UpdateBankTransactionRuleRequest.php | 10 +- app/Http/Requests/Chart/ShowChartRequest.php | 1 - .../Client/AdjustClientLedgerRequest.php | 1 - .../Requests/Client/BulkClientRequest.php | 8 +- .../Requests/Client/StoreClientRequest.php | 15 +- .../CreateClientGatewayTokenRequest.php | 1 - .../ListClientGatewayTokenRequest.php | 1 - .../StoreClientGatewayTokenRequest.php | 6 - .../UpdateClientGatewayTokenRequest.php | 4 - .../Requests/ClientPortal/RegisterRequest.php | 1 - .../Subscriptions/ShowPlanSwitchRequest.php | 3 - .../Requests/Company/StoreCompanyRequest.php | 4 +- .../Requests/Company/UpdateCompanyRequest.php | 13 +- .../BulkCompanyGatewayRequest.php | 10 +- .../StoreCompanyGatewayRequest.php | 3 +- .../Requests/Credit/BulkCreditRequest.php | 6 +- .../Requests/Design/StoreDesignRequest.php | 5 +- app/Http/Requests/Email/SendEmailRequest.php | 6 +- .../Requests/Expense/StoreExpenseRequest.php | 9 +- .../Requests/Expense/UpdateExpenseRequest.php | 7 +- .../Gateways/Mollie/Mollie3dsRequest.php | 1 - .../GroupSetting/StoreGroupSettingRequest.php | 6 +- .../Requests/Invoice/ActionInvoiceRequest.php | 3 +- .../Requests/Invoice/BulkInvoiceRequest.php | 2 - .../Requests/Invoice/UpdateInvoiceRequest.php | 2 - app/Http/Requests/Login/LoginRequest.php | 1 - .../Requests/Payment/StorePaymentRequest.php | 6 +- .../PaymentNotificationWebhookRequest.php | 5 - .../Payments/PaymentWebhookRequest.php | 2 - .../Requests/Preview/DesignPreviewRequest.php | 10 +- .../Preview/PreviewInvoiceRequest.php | 2 - .../Preview/PreviewPurchaseOrderRequest.php | 8 +- .../BulkPurchaseOrderRequest.php | 2 - .../StorePurchaseOrderRequest.php | 5 +- .../UploadPurchaseOrderRequest.php | 9 +- .../StoreRecurringExpenseRequest.php | 1 - .../StoreRecurringInvoiceRequest.php | 3 +- .../UpdateRecurringInvoiceRequest.php | 3 +- .../StoreRecurringQuoteRequest.php | 1 - .../UpdateRecurringQuoteRequest.php | 1 - .../Requests/Report/GenericReportRequest.php | 4 +- .../Report/ProductSalesReportRequest.php | 5 +- app/Http/Requests/Request.php | 32 +- .../InitializeStripeConnectRequest.php | 1 - .../DestroySubscriptionRequest.php | 1 - .../Subscription/EditSubscriptionRequest.php | 1 - .../Subscription/ShowSubscriptionRequest.php | 1 - .../Subscription/StoreSubscriptionRequest.php | 6 +- .../UpdateSubscriptionRequest.php | 4 +- app/Http/Requests/Task/SortTaskRequest.php | 1 - app/Http/Requests/Task/StoreTaskRequest.php | 28 +- app/Http/Requests/Task/UpdateTaskRequest.php | 33 +- .../TaskScheduler/CreateSchedulerRequest.php | 1 - .../TaskScheduler/StoreSchedulerRequest.php | 9 +- .../TaskScheduler/UpdateSchedulerRequest.php | 8 +- .../TaskStatus/ActionTaskStatusRequest.php | 2 - .../Requests/Token/UpdateTokenRequest.php | 1 - .../Requests/Twilio/Confirm2faRequest.php | 7 +- .../Requests/Twilio/ConfirmSmsRequest.php | 4 - .../Requests/Twilio/Generate2faRequest.php | 8 +- .../Requests/Twilio/GenerateSmsRequest.php | 4 - .../TwoFactor/EnableTwoFactorRequest.php | 5 +- app/Http/Requests/User/BulkUserRequest.php | 1 - app/Http/Requests/User/StoreUserRequest.php | 6 +- app/Http/Requests/User/UpdateUserRequest.php | 10 +- .../Requests/Vendor/StoreVendorRequest.php | 6 +- .../Requests/Vendor/UpdateVendorRequest.php | 3 +- .../Requests/Webhook/StoreWebhookRequest.php | 9 +- .../Requests/Webhook/UpdateWebhookRequest.php | 5 +- .../Requests/Yodlee/YodleeAdminRequest.php | 4 +- .../Requests/Yodlee/YodleeAuthRequest.php | 6 +- .../ValidationRules/Account/BlackListRule.php | 1 - .../Account/EmailBlackListRule.php | 1 - .../Company/ValidCompanyQuantity.php | 1 - .../Credit/ValidCreditsRules.php | 3 +- .../ValidationRules/Ninja/CanAddUserRule.php | 1 - .../Ninja/CanRestoreUserRule.php | 1 - .../Scheduler/ValidClientIds.php | 2 - .../User/HasValidPhoneNumber.php | 49 +- app/Http/ValidationRules/ValidAmount.php | 1 - .../ValidRefundableInvoices.php | 1 - app/Http/ViewComposers/PortalComposer.php | 1 - app/Import/Definitions/BankTransactionMap.php | 2 +- app/Import/Providers/BaseImport.php | 22 +- app/Import/Providers/Csv.php | 16 +- app/Import/Providers/Freshbooks.php | 1 - app/Import/Providers/Invoice2Go.php | 4 - app/Import/Providers/Invoicely.php | 1 - app/Import/Providers/Wave.php | 5 +- app/Import/Providers/Zoho.php | 1 - .../Transformer/Bank/BankTransformer.php | 46 +- app/Import/Transformer/BaseTransformer.php | 30 +- .../Transformer/Csv/ExpenseTransformer.php | 4 +- .../Transformer/Csv/InvoiceTransformer.php | 3 +- .../Transformer/Csv/QuoteTransformer.php | 5 +- .../Freshbooks/InvoiceTransformer.php | 8 +- .../Invoice2Go/InvoiceTransformer.php | 1 - .../Transformer/Wave/ExpenseTransformer.php | 1 - .../Transformer/Zoho/InvoiceTransformer.php | 1 - app/Jobs/Account/CreateAccount.php | 16 +- app/Jobs/Bank/MatchBankTransactions.php | 170 ++-- app/Jobs/Bank/ProcessBankTransactions.php | 48 +- app/Jobs/Company/CompanyExport.php | 216 ++-- app/Jobs/Company/CompanyImport.php | 925 ++++++++---------- app/Jobs/Company/CreateCompany.php | 1 - app/Jobs/Credit/ApplyCreditPayment.php | 3 - app/Jobs/Credit/ZipCredits.php | 3 - app/Jobs/Cron/AutoBill.php | 2 +- app/Jobs/Cron/AutoBillCron.php | 26 +- app/Jobs/Cron/CompanyRecurringCron.php | 31 +- app/Jobs/Cron/RecurringExpensesCron.php | 38 +- app/Jobs/Cron/RecurringInvoicesCron.php | 2 - app/Jobs/Cron/SendCompanyRecurring.php | 57 +- app/Jobs/Cron/SubscriptionCron.php | 11 +- app/Jobs/Document/ZipDocuments.php | 7 +- app/Jobs/Entity/CreateEntityPdf.php | 3 - app/Jobs/Entity/CreateRawPdf.php | 4 - app/Jobs/Entity/EmailEntity.php | 1 - app/Jobs/Import/CSVIngest.php | 23 +- app/Jobs/Inventory/AdjustProductInventory.php | 24 +- app/Jobs/Invoice/BulkInvoiceJob.php | 14 - app/Jobs/Invoice/CheckGatewayFee.php | 13 +- app/Jobs/Invoice/InvoiceCheckLateWebhook.php | 48 +- app/Jobs/Invoice/ZipInvoices.php | 3 - app/Jobs/Ledger/ClientLedgerBalanceUpdate.php | 13 +- app/Jobs/Ledger/LedgerBalanceUpdate.php | 1 - app/Jobs/Mail/NinjaMailerJob.php | 236 ++--- app/Jobs/Mail/PaymentFailedMailer.php | 7 +- app/Jobs/Mail/PaymentFailureMailer.php | 6 - app/Jobs/Ninja/AdjustEmailQuota.php | 9 +- app/Jobs/Ninja/BankTransactionSync.php | 29 +- app/Jobs/Ninja/CheckCompanyData.php | 9 +- app/Jobs/Ninja/CompanySizeCheck.php | 57 +- app/Jobs/Ninja/QueueSize.php | 1 - app/Jobs/Ninja/SendReminders.php | 1 - app/Jobs/Ninja/SystemMaintenance.php | 3 - app/Jobs/Ninja/TaskScheduler.php | 10 +- app/Jobs/Payment/EmailPayment.php | 2 - app/Jobs/Payment/EmailRefundPayment.php | 2 - app/Jobs/Payment/PaymentNotification.php | 1 - app/Jobs/PostMark/ProcessPostmarkWebhook.php | 64 +- app/Jobs/Product/UpdateOrCreateProduct.php | 32 +- app/Jobs/PurchaseOrder/PurchaseOrderEmail.php | 9 +- app/Jobs/PurchaseOrder/ZipPurchaseOrders.php | 5 - app/Jobs/Quote/QuoteCheckExpired.php | 68 +- app/Jobs/Quote/ZipQuotes.php | 5 - app/Jobs/RecurringInvoice/SendRecurring.php | 24 +- app/Jobs/Report/SendToAdmin.php | 1 - .../Subscription/CleanStaleInvoiceOrder.php | 21 +- app/Jobs/User/CreateUser.php | 2 - app/Jobs/User/UserEmailChanged.php | 1 - app/Jobs/User/VerifyPhone.php | 68 +- app/Jobs/Util/ApplePayDomain.php | 3 - app/Jobs/Util/DiskCleanup.php | 3 - app/Jobs/Util/Import.php | 347 ++++--- app/Jobs/Util/RefreshPdfs.php | 5 - app/Jobs/Util/ReminderJob.php | 97 +- app/Jobs/Util/SchedulerCheck.php | 4 +- app/Jobs/Util/UpdateExchangeRates.php | 27 +- app/Jobs/Util/VersionCheck.php | 1 - app/Jobs/Util/WebhookHandler.php | 15 +- app/Jobs/Util/WebhookSingle.php | 57 +- app/Jobs/Vendor/CreatePurchaseOrderPdf.php | 46 +- app/Libraries/MultiDB.php | 7 +- .../Activity/RestoreClientActivity.php | 1 - .../Credit/CreditCreatedNotification.php | 1 - app/Listeners/Invoice/CreateInvoicePdf.php | 1 - .../Invoice/InvoiceCreatedNotification.php | 1 - .../Invoice/InvoiceEmailFailedActivity.php | 1 - .../Invoice/InvoiceEmailedNotification.php | 1 - .../InvoiceFailedEmailNotification.php | 3 - app/Listeners/Invoice/InvoicePaidActivity.php | 4 +- app/Listeners/Mail/MailSentListener.php | 36 +- .../Misc/InvitationViewedListener.php | 2 - app/Listeners/Payment/PaymentNotification.php | 7 +- .../PurchaseOrderAcceptedListener.php | 3 - .../PurchaseOrderCreatedListener.php | 2 - .../PurchaseOrderEmailedNotification.php | 1 - .../Quote/QuoteApprovedNotification.php | 3 - .../Quote/QuoteCreatedNotification.php | 1 - .../SendVerificationNotification.php | 3 - .../AppStoreRenewSubscription.php | 12 +- app/Listeners/User/UpdateUserLastLogin.php | 1 - app/Mail/Admin/AutoBillingFailureObject.php | 1 - app/Mail/Admin/EntityCreatedObject.php | 60 +- app/Mail/Admin/EntityFailedSendObject.php | 2 +- app/Mail/Admin/EntitySentObject.php | 42 +- .../Admin/InventoryNotificationObject.php | 2 - app/Mail/Admin/PaymentFailureObject.php | 4 +- app/Mail/BouncedEmail.php | 4 - app/Mail/Client/ClientStatement.php | 16 +- app/Mail/ContactPasswordlessLogin.php | 3 - app/Mail/DownloadBackup.php | 2 - app/Mail/DownloadReport.php | 1 - app/Mail/Engine/CreditEmailEngine.php | 43 +- app/Mail/Engine/InvoiceEmailEngine.php | 75 +- app/Mail/Engine/PaymentEmailEngine.php | 39 +- app/Mail/Engine/PurchaseOrderEmailEngine.php | 41 +- app/Mail/Engine/QuoteEmailEngine.php | 40 +- app/Mail/Import/CsvImportCompleted.php | 2 +- app/Mail/MigrationCompleted.php | 1 - app/Mail/MigrationFailed.php | 3 +- app/Mail/Ninja/EmailQuotaExceeded.php | 2 - app/Mail/Ninja/GmailTokenInvalid.php | 2 - ...ClientContactRequestCancellationObject.php | 8 +- app/Mail/SupportMessageSent.php | 5 +- app/Mail/TemplateEmail.php | 26 +- app/Mail/VendorTemplateEmail.php | 29 +- app/Models/Account.php | 82 +- app/Models/Activity.php | 4 +- app/Models/Backup.php | 9 +- app/Models/BankIntegration.php | 4 +- app/Models/BankTransaction.php | 17 +- app/Models/BankTransactionRule.php | 6 +- app/Models/BaseModel.php | 14 +- app/Models/Client.php | 8 +- app/Models/ClientContact.php | 4 - app/Models/ClientGatewayToken.php | 2 - app/Models/Company.php | 12 +- app/Models/CompanyGateway.php | 94 +- app/Models/Country.php | 8 +- app/Models/Credit.php | 1 - app/Models/Document.php | 1 - app/Models/ExpenseCategory.php | 1 - app/Models/GroupSetting.php | 5 +- app/Models/Invoice.php | 26 +- app/Models/Payment.php | 2 - app/Models/PaymentTerm.php | 1 - app/Models/Paymentable.php | 1 - app/Models/Presenters/CompanyPresenter.php | 37 +- app/Models/Presenters/EntityPresenter.php | 1 - .../Presenters/RecurringInvoicePresenter.php | 4 - .../Presenters/RecurringQuotePresenter.php | 4 - app/Models/PurchaseOrder.php | 21 +- app/Models/Quote.php | 3 - app/Models/RecurringExpense.php | 2 - app/Models/RecurringInvoice.php | 9 +- app/Models/RecurringQuote.php | 3 - app/Models/RecurringQuoteInvitation.php | 1 - app/Models/StaticModel.php | 2 - app/Models/Subscription.php | 4 - app/Models/TaskStatus.php | 1 - app/Models/TaxRate.php | 1 - app/Models/Traits/Excludable.php | 13 +- app/Models/User.php | 72 +- app/Models/Vendor.php | 3 - app/Models/VendorContact.php | 2 - .../Admin/EntitySentNotification.php | 5 - .../Admin/EntityViewedNotification.php | 5 - .../Admin/NewPaymentNotification.php | 5 - app/Notifications/BaseNotification.php | 1 - .../ClientContactRequestCancellation.php | 1 - app/Notifications/NewAccountCreated.php | 1 - .../Ninja/ClientAccountNotFound.php | 14 +- .../Ninja/DomainFailureNotification.php | 12 +- .../DomainRenewalFailureNotification.php | 12 +- .../Ninja/EmailBounceNotification.php | 5 - .../Ninja/EmailQualityNotification.php | 9 +- .../Ninja/EmailQuotaNotification.php | 5 - .../Ninja/EmailSpamNotification.php | 5 - .../Ninja/GmailCredentialNotification.php | 5 - app/Notifications/Ninja/NewAccountCreated.php | 1 - .../Ninja/NewAccountNotification.php | 8 +- .../Ninja/RenewalFailureNotification.php | 12 +- app/Notifications/Ninja/SpamNotification.php | 46 +- .../Ninja/UserQualityNotification.php | 9 +- app/Notifications/Ninja/VerifyUser.php | 1 - .../Ninja/WePayFailureNotification.php | 5 - app/Observers/ClientContactObserver.php | 36 +- app/Observers/ClientObserver.php | 26 +- app/Observers/CompanyGatewayObserver.php | 1 - app/Observers/CreditObserver.php | 21 +- app/Observers/ExpenseObserver.php | 23 +- app/Observers/InvoiceObserver.php | 18 +- app/Observers/PaymentObserver.php | 19 +- app/Observers/ProductObserver.php | 23 +- app/Observers/ProjectObserver.php | 24 +- app/Observers/PurchaseOrderObserver.php | 26 +- app/Observers/QuoteObserver.php | 26 +- app/Observers/TaskObserver.php | 23 +- app/Observers/UserObserver.php | 6 +- app/Observers/VendorContactObserver.php | 13 +- app/Observers/VendorObserver.php | 20 +- .../Authorize/AuthorizeCreateCustomer.php | 5 - .../Authorize/AuthorizeCreditCard.php | 20 +- .../Authorize/AuthorizeCustomer.php | 5 - app/PaymentDrivers/AuthorizePaymentDriver.php | 10 - app/PaymentDrivers/BaseDriver.php | 24 +- app/PaymentDrivers/Braintree/CreditCard.php | 1 - app/PaymentDrivers/Braintree/PayPal.php | 5 +- app/PaymentDrivers/BraintreePaymentDriver.php | 22 +- app/PaymentDrivers/CheckoutCom/CreditCard.php | 67 +- app/PaymentDrivers/CheckoutCom/Utilities.php | 6 +- .../CheckoutComPaymentDriver.php | 107 +- app/PaymentDrivers/CustomPaymentDriver.php | 1 - app/PaymentDrivers/Eway/CreditCard.php | 7 - app/PaymentDrivers/Eway/Token.php | 8 - app/PaymentDrivers/EwayPaymentDriver.php | 8 - app/PaymentDrivers/Forte/ACH.php | 21 +- app/PaymentDrivers/Forte/CreditCard.php | 40 +- app/PaymentDrivers/FortePaymentDriver.php | 25 +- app/PaymentDrivers/GoCardless/ACH.php | 1 - app/PaymentDrivers/GoCardless/DirectDebit.php | 1 - app/PaymentDrivers/GoCardless/SEPA.php | 1 - .../GoCardlessPaymentDriver.php | 23 +- app/PaymentDrivers/Mollie/CreditCard.php | 15 +- app/PaymentDrivers/MolliePaymentDriver.php | 1 - app/PaymentDrivers/PayFast/CreditCard.php | 2 - app/PaymentDrivers/PayFast/Token.php | 17 +- app/PaymentDrivers/PayTrace/CreditCard.php | 5 - app/PaymentDrivers/PaytracePaymentDriver.php | 1 - app/PaymentDrivers/Razorpay/Hosted.php | 1 - app/PaymentDrivers/Sample/CreditCard.php | 8 - app/PaymentDrivers/Square/CreditCard.php | 1 - app/PaymentDrivers/SquarePaymentDriver.php | 1 - app/PaymentDrivers/Stripe/ACH.php | 30 +- app/PaymentDrivers/Stripe/ACSS.php | 2 +- app/PaymentDrivers/Stripe/ApplePay.php | 5 - app/PaymentDrivers/Stripe/BECS.php | 2 +- app/PaymentDrivers/Stripe/Bancontact.php | 4 +- app/PaymentDrivers/Stripe/Charge.php | 34 +- app/PaymentDrivers/Stripe/Connect/Verify.php | 15 - app/PaymentDrivers/Stripe/CreditCard.php | 15 +- app/PaymentDrivers/Stripe/EPS.php | 4 +- app/PaymentDrivers/Stripe/FPX.php | 4 +- app/PaymentDrivers/Stripe/GIROPAY.php | 4 +- app/PaymentDrivers/Stripe/ImportCustomers.php | 17 +- .../Jobs/PaymentIntentFailureWebhook.php | 16 +- .../Jobs/PaymentIntentProcessingWebhook.php | 94 +- .../Stripe/Jobs/PaymentIntentWebhook.php | 111 +-- .../Stripe/Jobs/StripeWebhook.php | 8 - .../Stripe/Jobs/UpdateCustomer.php | 13 +- app/PaymentDrivers/Stripe/Klarna.php | 6 +- app/PaymentDrivers/Stripe/PRZELEWY24.php | 4 +- app/PaymentDrivers/Stripe/SEPA.php | 2 +- app/PaymentDrivers/Stripe/SOFORT.php | 5 +- .../Stripe/UpdatePaymentMethods.php | 21 +- app/PaymentDrivers/Stripe/iDeal.php | 4 +- .../StripeConnectPaymentDriver.php | 26 - app/PaymentDrivers/StripePaymentDriver.php | 70 +- app/PaymentDrivers/WePay/ACH.php | 2 - app/PaymentDrivers/WePay/CreditCard.php | 2 - app/PaymentDrivers/WePay/Setup.php | 1 - app/PaymentDrivers/WePayPaymentDriver.php | 8 - app/Policies/EntityPolicy.php | 2 +- app/Policies/WebhookPolicy.php | 1 - app/Providers/AppServiceProvider.php | 6 - app/Providers/EventServiceProvider.php | 8 +- .../MailCssInlinerServiceProvider.php | 2 - .../NinjaTranslationServiceProvider.php | 1 - app/Providers/RouteServiceProvider.php | 4 - app/Repositories/ActivityRepository.php | 2 +- .../BankIntegrationRepository.php | 5 - .../BankTransactionRepository.php | 15 +- .../BankTransactionRuleRepository.php | 6 - app/Repositories/BaseRepository.php | 125 ++- app/Repositories/ClientContactRepository.php | 12 +- app/Repositories/ClientRepository.php | 5 +- app/Repositories/CreditRepository.php | 2 - app/Repositories/DocumentRepository.php | 2 - app/Repositories/ExpenseRepository.php | 22 +- .../Migration/InvoiceMigrationRepository.php | 1 - .../Migration/PaymentMigrationRepository.php | 1 - app/Repositories/PaymentRepository.php | 67 +- app/Repositories/PurchaseOrderRepository.php | 1 - .../RecurringInvoiceRepository.php | 1 - app/Repositories/SchedulerRepository.php | 6 +- app/Repositories/SubscriptionRepository.php | 23 +- app/Repositories/TaskRepository.php | 20 +- app/Repositories/TaskStatusRepository.php | 15 +- app/Repositories/UserRepository.php | 31 +- app/Services/Bank/BankMatchingService.php | 23 +- app/Services/Bank/BankService.php | 15 +- app/Services/Bank/ProcessBankRules.php | 76 +- app/Services/Chart/ChartQueries.php | 3 - app/Services/Chart/ChartService.php | 2 - app/Services/Client/ClientService.php | 49 +- app/Services/Client/Merge.php | 6 - app/Services/Client/PaymentMethod.php | 4 - app/Services/Client/Statement.php | 4 +- app/Services/ClientPortal/InstantPayment.php | 25 +- app/Services/Credit/ApplyPayment.php | 1 - app/Services/Credit/CreditService.php | 3 - app/Services/Credit/GetCreditPdf.php | 2 - app/Services/Credit/MarkSent.php | 2 - app/Services/Credit/SendEmail.php | 2 - app/Services/Credit/TriggeredActions.php | 4 +- app/Services/Email/EmailDefaults.php | 93 +- app/Services/Email/EmailMailable.php | 17 +- app/Services/Email/EmailMailer.php | 183 ++-- app/Services/Email/EmailObject.php | 63 +- app/Services/Email/EmailService.php | 67 +- app/Services/Email/MailBuild.php | 233 ++--- app/Services/Email/MailEntity.php | 240 ++--- app/Services/Email/MailMailable.php | 17 +- app/Services/Email/MailObject.php | 76 +- app/Services/Invoice/AddGatewayFee.php | 2 - app/Services/Invoice/ApplyNumber.php | 21 +- app/Services/Invoice/ApplyPayment.php | 1 - app/Services/Invoice/ApplyPaymentAmount.php | 4 +- app/Services/Invoice/AutoBillInvoice.php | 12 +- app/Services/Invoice/GetInvoicePdf.php | 1 - app/Services/Invoice/HandleRestore.php | 45 +- app/Services/Invoice/HandleReversal.php | 1 - app/Services/Invoice/InvoiceService.php | 21 +- app/Services/Invoice/MarkInvoiceDeleted.php | 34 +- app/Services/Invoice/MarkPaid.php | 13 +- app/Services/Invoice/MarkSent.php | 5 +- app/Services/Invoice/TriggeredActions.php | 7 +- app/Services/Invoice/UpdateReminder.php | 2 +- app/Services/Ledger/LedgerService.php | 7 +- app/Services/Payment/DeletePayment.php | 32 +- app/Services/Payment/PaymentService.php | 35 +- app/Services/Payment/RefundPayment.php | 11 - app/Services/Payment/SendEmail.php | 13 +- app/Services/Payment/UpdateInvoicePayment.php | 28 +- app/Services/PdfMaker/Design.php | 31 +- app/Services/PdfMaker/PdfMerge.php | 10 +- .../PurchaseOrder/GetPurchaseOrderPdf.php | 1 - app/Services/PurchaseOrder/MarkSent.php | 3 - .../PurchaseOrder/PurchaseOrderExpense.php | 9 +- .../PurchaseOrder/PurchaseOrderInventory.php | 17 +- .../PurchaseOrder/PurchaseOrderService.php | 39 +- .../PurchaseOrder/TriggeredActions.php | 9 +- app/Services/Quote/GetQuotePdf.php | 1 - app/Services/Quote/MarkSent.php | 2 - app/Services/Quote/QuoteService.php | 4 +- app/Services/Quote/SendEmail.php | 3 +- app/Services/Quote/TriggeredActions.php | 4 +- .../Recurring/CreateRecurringInvitations.php | 5 +- app/Services/Recurring/GetInvoicePdf.php | 2 - app/Services/Recurring/RecurringService.php | 23 +- app/Services/Report/ProfitLoss.php | 13 +- app/Services/Scheduler/SchedulerService.php | 55 +- .../Subscription/SubscriptionService.php | 541 +++++----- .../TaskScheduler/TaskSchedulerService.php | 12 +- app/Services/User/UserService.php | 1 - app/Transformers/AccountTransformer.php | 1 - app/Transformers/ActivityTransformer.php | 3 - .../BankIntegrationTransformer.php | 1 - .../BankTransactionRuleTransformer.php | 16 +- .../BankTransactionTransformer.php | 3 - .../CompanyGatewayTransformer.php | 1 - app/Transformers/CompanyTransformer.php | 5 - app/Transformers/CreditTransformer.php | 1 - app/Transformers/GroupSettingTransformer.php | 1 - app/Transformers/InvoiceTransformer.php | 1 - app/Transformers/PurchaseOrderTransformer.php | 3 - app/Transformers/QuoteTransformer.php | 1 - .../RecurringInvoiceTransformer.php | 4 - .../RecurringQuoteTransformer.php | 3 - app/Transformers/TaskTransformer.php | 7 +- app/Utils/Helpers.php | 36 +- app/Utils/HtmlEngine.php | 69 +- app/Utils/Ninja.php | 3 +- app/Utils/Number.php | 5 +- app/Utils/PhantomJS/Phantom.php | 4 +- app/Utils/Statics.php | 1 - app/Utils/SystemHealth.php | 39 +- app/Utils/TemplateEngine.php | 29 +- app/Utils/Traits/AppSetup.php | 3 - app/Utils/Traits/CleanLineItems.php | 1 - app/Utils/Traits/ClientGroupSettingsSaver.php | 3 +- .../CompanyGatewayFeesAndLimitsSaver.php | 4 +- app/Utils/Traits/CompanySettingsSaver.php | 9 +- app/Utils/Traits/DesignCalculator.php | 16 +- .../Traits/GeneratesConvertedQuoteCounter.php | 21 +- app/Utils/Traits/GeneratesCounter.php | 40 +- app/Utils/Traits/Inviteable.php | 7 +- app/Utils/Traits/MakesInvoiceHtml.php | 2 - app/Utils/Traits/MakesInvoiceValues.php | 6 +- app/Utils/Traits/MakesReminders.php | 3 +- app/Utils/Traits/MakesTemplateData.php | 3 +- .../Traits/Notifications/UserNotifies.php | 10 +- app/Utils/Traits/NumberFormatter.php | 2 - app/Utils/Traits/Pdf/PageNumbering.php | 1 - app/Utils/Traits/SavesDocuments.php | 3 +- app/Utils/Traits/SettingsSaver.php | 12 +- app/Utils/Traits/SubscriptionHooker.php | 24 +- app/Utils/Traits/Uploadable.php | 2 +- app/Utils/VendorHtmlEngine.php | 51 +- config/flare.php | 4 +- config/ninja.php | 16 +- config/purchase.php | 2 +- config/services.php | 6 +- database/factories/AccountFactory.php | 1 - database/factories/BankIntegrationFactory.php | 4 +- database/factories/BankTransactionFactory.php | 6 +- .../factories/BankTransactionRuleFactory.php | 6 +- database/factories/ClientContactFactory.php | 1 - database/factories/ClientFactory.php | 1 - database/factories/CompanyFactory.php | 1 - .../factories/CreditInvitationFactory.php | 1 - database/factories/DocumentFactory.php | 2 - database/factories/ExpenseCategoryFactory.php | 1 - database/factories/ExpenseFactory.php | 1 - database/factories/GatewayFactory.php | 1 - .../factories/InvoiceInvitationFactory.php | 1 - database/factories/ProductFactory.php | 3 +- database/factories/ProjectFactory.php | 1 - database/factories/PurchaseOrderFactory.php | 2 +- .../PurchaseOrderInvitationFactory.php | 1 - database/factories/QuoteInvitationFactory.php | 1 - .../factories/RecurringExpenseFactory.php | 1 - database/factories/SchedulerFactory.php | 9 +- database/factories/SubscriptionFactory.php | 1 - database/factories/TaskFactory.php | 1 - database/factories/TaskStatusFactory.php | 1 - database/factories/TaxRateFactory.php | 2 - database/factories/UserFactory.php | 1 - database/factories/VendorContactFactory.php | 1 - database/factories/VendorFactory.php | 1 - .../2021_03_08_205030_add_russian_lang.php | 1 - ...add_unique_constraints_on_all_entities.php | 2 - ...21_04_12_095424_stripe_connect_gateway.php | 2 - ...dd_property_to_checkout_gateway_config.php | 2 - ...152940_make_braintree_provider_visible.php | 2 - .../2021_05_05_014713_activate_we_pay.php | 2 - ...085821_activate_payfast_payment_driver.php | 2 - ...95537_activate_paytrace_payment_driver.php | 2 - ...213344_change_english_languages_tables.php | 2 - ...21_234227_activate_eway_payment_driver.php | 2 - ..._115024_activate_mollie_payment_driver.php | 2 - ...21_08_05_235942_add_zelle_payment_type.php | 2 - .../2021_08_10_034407_add_more_languages.php | 2 - ...021_08_14_054458_square_payment_driver.php | 2 - ..._09_05_101209_update_braintree_gateway.php | 2 - ...20_233053_set_square_test_mode_boolean.php | 2 - .../2021_09_23_100629_add_currencies.php | 2 - ..._09_24_211504_add_kbc_to_payment_types.php | 2 - ...213858_add_bancontact_to_payment_types.php | 2 - ...044800_updated_bold_and_modern_designs.php | 2 - ...11_11_163121_add_instant_bank_transfer.php | 2 - ...5542_add_serbian_language_translations.php | 2 - .../2022_01_02_022421_add_slovak_language.php | 2 - ...31_add_app_domain_id_to_gateways_table.php | 2 - ...022_01_18_004856_add_estonian_language.php | 2 - .../2022_01_19_232436_add_kyd_currency.php | 2 - ...5411_update_stripe_apple_domain_config.php | 2 - ...014025_reverse_apple_domain_for_hosted.php | 2 - ...022_04_14_121548_forte_payment_gateway.php | 7 +- ...115838_client_settings_parse_for_types.php | 2 - ...tom_fields_column_from_varchar_to_text.php | 1 - ...4937_heal_stripe_gateway_configuration.php | 2 - .../2022_05_12_56879_add_stripe_klarna.php | 11 +- ...2_05_18_162443_create_schedulers_table.php | 1 - ...05_30_181109_drop_scheduled_jobs_table.php | 1 - ..._215859_set_recurring_client_timestamp.php | 1 - ...6_10_030503_set_account_flag_for_react.php | 2 - ...0_fixes_for_description_in_pdf_designs.php | 3 - ...06_24_141018_upgrade_failed_jobs_table.php | 3 +- ...6_30_000126_add_flag_to_accounts_table.php | 1 - ...6_080127_add_purchase_order_to_expense.php | 5 +- ...07_09_235510_add_index_to_payment_hash.php | 2 +- .../2022_07_12_45766_add_matomo.php | 8 +- ...756_fixes_for_date_formats_table_react.php | 14 +- .../2022_07_21_023805_add_hebrew_language.php | 23 +- ...add_sms_verification_to_hosted_account.php | 5 +- ...d_expense_tax_rates_to_companies_table.php | 8 +- ...5_correction_for_companies_table_types.php | 7 +- .../2022_08_05_023357_bank_integration.php | 17 +- ...11_011534_licenses_table_for_self_host.php | 3 +- ...7_invoice_task_project_companies_table.php | 3 +- ...mn_to_purchase_order_invitations_table.php | 8 +- ..._28_210111_add_index_to_payments_table.php | 4 +- ...24719_update_designs_for_tech_template.php | 5 +- ...dd_reporting_option_to_companies_table.php | 3 +- ..._09_21_012417_add_threeds_to_braintree.php | 14 +- ...235337_add_idempotency_key_to_payments.php | 5 +- ...0_05_205645_add_indexes_to_client_hash.php | 4 +- .../2022_10_06_011344_add_key_to_products.php | 5 +- ...065455_add_key_to_company_tokens_table.php | 4 +- ...22_10_10_070137_add_documentable_index.php | 20 +- ..._044909_add_user_sms_verification_code.php | 5 +- ...dd_verified_number_flag_to_users_table.php | 3 +- ...abled_upstream_bank_integrations_table.php | 5 +- ...html_backups_column_from_backups_table.php | 14 +- ...13_034143_bank_transaction_rules_table.php | 8 +- .../2022_11_16_093535_calmness_design.php | 8 +- ..._11_22_215618_lock_tasks_when_invoiced.php | 21 +- ...d_payment_id_to_bank_transaction_table.php | 6 +- ...4625_add_properties_to_companies_table.php | 4 +- ...12_20_063038_set_proforma_invoice_type.php | 11 +- ...t_auto_bill_on_regular_invoice_setting.php | 21 +- ...3_01_27_023127_update_design_templates.php | 5 +- ...dd_additional_required_fields_gateways.php | 9 +- ...7_114011_add_additional_product_fields.php | 25 +- ...act_settings_column_company_user_table.php | 6 +- database/seeders/LanguageSeeder.php | 20 +- database/seeders/PaymentLibrariesSeeder.php | 2 +- database/seeders/RandomDataSeeder.php | 2 - lang/ar/texts.php | 8 +- lang/bg/texts.php | 8 +- lang/ca/texts.php | 8 +- lang/cs/texts.php | 8 +- lang/da/texts.php | 8 +- lang/de/texts.php | 8 +- lang/el/texts.php | 8 +- lang/en/texts.php | 8 +- lang/en_GB/texts.php | 8 +- lang/es/texts.php | 8 +- lang/es_ES/texts.php | 8 +- lang/et/texts.php | 8 +- lang/fa/texts.php | 8 +- lang/fi/texts.php | 8 +- lang/fr/texts.php | 8 +- lang/fr_CA/texts.php | 8 +- lang/he/texts.php | 8 +- lang/hr/texts.php | 8 +- lang/it/texts.php | 8 +- lang/ja/texts.php | 8 +- lang/lt/texts.php | 8 +- lang/lv_LV/texts.php | 8 +- lang/mk_MK/texts.php | 8 +- lang/nb_NO/texts.php | 8 +- lang/nl/texts.php | 8 +- lang/pl/texts.php | 8 +- lang/pt_BR/texts.php | 8 +- lang/pt_PT/texts.php | 8 +- lang/ro/texts.php | 8 +- lang/ru_RU/texts.php | 8 +- lang/sk/texts.php | 8 +- lang/sl/texts.php | 8 +- lang/sq/texts.php | 8 +- lang/sr/texts.php | 8 +- lang/sv/texts.php | 8 +- lang/th/texts.php | 8 +- lang/tr_TR/texts.php | 8 +- lang/zh_TW/texts.php | 8 +- preload.php | 2 +- routes/api.php | 5 +- routes/client.php | 6 +- routes/web.php | 4 +- .../Gateways/Braintree/ACHTest.php | 1 - .../Gateways/Braintree/CreditCardTest.php | 1 - .../Gateways/Stripe/AlipayTest.php | 1 - tests/Browser/ClientPortal/LoginTest.php | 1 - tests/Browser/ClientPortal/QuotesTest.php | 1 - tests/DuskTestCase.php | 3 +- .../Feature/Account/AccountEmailQuotaTest.php | 9 - tests/Feature/ActivityApiTest.php | 1 - .../Feature/ApplePayDomainMerchantUrlTest.php | 2 +- .../Feature/Bank/BankTransactionRuleTest.php | 127 +-- tests/Feature/Bank/BankTransactionTest.php | 19 +- tests/Feature/Bank/YodleeApiTest.php | 35 +- .../Bank/YodleeBankTransactionTest.php | 59 +- tests/Feature/BankIntegrationApiTest.php | 1 - tests/Feature/BankTransactionRuleApiTest.php | 11 +- tests/Feature/BaseApiTest.php | 108 +- tests/Feature/Client/ClientMergeTest.php | 5 - tests/Feature/ClientApiTest.php | 92 +- .../ClientDeletedInvoiceCreationTest.php | 2 - tests/Feature/ClientGatewayTokenApiTest.php | 1 - tests/Feature/ClientModelTest.php | 1 - tests/Feature/ClientPortal/InvoicesTest.php | 1 - tests/Feature/ClientTest.php | 5 +- tests/Feature/CompanyGatewayApiTest.php | 3 +- .../Feature/CompanyGatewayResolutionTest.php | 2 +- tests/Feature/CompanyGatewayTest.php | 4 - tests/Feature/CompanySettingsTest.php | 10 +- tests/Feature/CompanyTest.php | 10 +- tests/Feature/CreditTest.php | 3 - tests/Feature/DeleteInvoiceTest.php | 1 - tests/Feature/DesignApiTest.php | 1 - tests/Feature/Email/EmailServiceTest.php | 50 +- tests/Feature/EntityPaidToDateTest.php | 10 - tests/Feature/ExpenseApiTest.php | 2 - tests/Feature/Export/ClientCsvTest.php | 3 - tests/Feature/Export/ExportCompanyTest.php | 3 - .../Feature/Export/ProductSalesReportTest.php | 17 +- .../Export/ProfitAndLossReportTest.php | 6 - .../GoCardlessInstantBankPaymentTest.php | 144 ++- .../Import/CSV/BaseTransformerTest.php | 6 - tests/Feature/Import/CSV/CsvImportTest.php | 10 +- .../Import/Freshbooks/FreshbooksTest.php | 4 - tests/Feature/Import/ImportCompanyTest.php | 192 ++-- .../Import/Invoice2Go/Invoice2GoTest.php | 5 - .../Import/Invoicely/InvoicelyTest.php | 4 - tests/Feature/Import/Wave/WaveTest.php | 1 - tests/Feature/Import/Zoho/ZohoTest.php | 3 - .../Inventory/InventoryManagementTest.php | 9 +- tests/Feature/InvitationTest.php | 3 - tests/Feature/InvoiceTest.php | 8 +- tests/Feature/LiveDesignTest.php | 15 +- tests/Feature/LoadTest.php | 4 - tests/Feature/MultiPaymentDeleteTest.php | 2 - tests/Feature/Notify/NotificationTest.php | 16 +- tests/Feature/PaymentTest.php | 6 - tests/Feature/Payments/CreditPaymentTest.php | 7 - .../Payments/StorePaymentValidationTest.php | 14 - .../Payments/UnappliedPaymentDeleteTest.php | 1 - .../Payments/UnappliedPaymentRefundTest.php | 1 - tests/Feature/PurchaseOrderTest.php | 3 - tests/Feature/QuoteTest.php | 5 +- tests/Feature/RecurringInvoiceTest.php | 1 - tests/Feature/RecurringInvoicesCronTest.php | 1 - tests/Feature/RecurringQuoteTest.php | 3 +- tests/Feature/ReminderTest.php | 4 - tests/Feature/Scheduler/SchedulerTest.php | 56 +- tests/Feature/SubscriptionApiTest.php | 5 - tests/Feature/SystemLogApiTest.php | 5 +- tests/Feature/TaskApiTest.php | 69 +- tests/Feature/UpdatePaymentTest.php | 9 - tests/Feature/UserTest.php | 6 - tests/Feature/WebhookAPITest.php | 5 - tests/Integration/CheckRemindersTest.php | 1 - tests/Integration/CompanyLedgerTest.php | 3 - .../DownloadHistoricalInvoiceTest.php | 2 - tests/Integration/EventTest.php | 129 ++- tests/Integration/MultiDBUserTest.php | 3 +- tests/Integration/PostmarkWebhookTest.php | 1 - tests/MockAccountData.php | 4 - tests/Unit/AutoBillInvoiceTest.php | 2 - tests/Unit/CentConversionTest.php | 1 - tests/Unit/Chart/ChartCurrencyTest.php | 1 - tests/Unit/ClientSettingsTest.php | 2 - tests/Unit/CollectionMergingTest.php | 2 - tests/Unit/CompanyDocumentsTest.php | 3 +- tests/Unit/CompareCollectionTest.php | 12 +- tests/Unit/CreditBalanceTest.php | 9 +- tests/Unit/DatesTest.php | 1 - tests/Unit/EntityTranslationTest.php | 2 - .../GeneratesConvertedQuoteCounterTest.php | 8 - tests/Unit/GeneratesCounterTest.php | 1 - tests/Unit/InvitationTest.php | 1 - tests/Unit/InvoiceStatusTest.php | 2 - tests/Unit/InvoiceTest.php | 1 - tests/Unit/LateFeeTest.php | 4 - tests/Unit/NumberTest.php | 3 - tests/Unit/PermissionsTest.php | 28 +- tests/Unit/RangeDetectionTest.php | 1 - tests/Unit/RecurringDateTest.php | 2 - tests/Unit/RecurringExpenseCloneTest.php | 2 - tests/Unit/RedisVsDatabaseTest.php | 3 - tests/Unit/RefundUnitTest.php | 1 - tests/Unit/RelationExistsTest.php | 1 - tests/Unit/S3CleanupTest.php | 1 - tests/Unit/SettingsSaverTest.php | 1 - tests/Unit/SubscriptionsCalcTest.php | 7 - .../BlacklistValidationTest.php | 3 - .../EmailBlacklistValidationTest.php | 4 - .../UniqueInvoiceNumberValidationTest.php | 2 - tests/Unit/ZeroDecimalTest.php | 7 - 965 files changed, 5565 insertions(+), 9452 deletions(-) delete mode 100644 .php_cs diff --git a/.php_cs b/.php_cs deleted file mode 100644 index 33c6ee25511b..000000000000 --- a/.php_cs +++ /dev/null @@ -1,19 +0,0 @@ -notPath('vendor') - ->notPath('bootstrap') - ->notPath('storage') - ->notPath('node_modules') - ->in(__DIR__) - ->name('*.php') - ->notName('*.blade.php'); - -return PhpCsFixer\Config::create() - ->setRules([ - '@PSR2' => true, - 'array_syntax' => ['syntax' => 'short'], - 'ordered_imports' => ['sortAlgorithm' => 'alpha'], - 'no_unused_imports' => true, - ]) - ->setFinder($finder); \ No newline at end of file diff --git a/app/Console/Commands/BackupUpdate.php b/app/Console/Commands/BackupUpdate.php index c96330cd6dcb..720418c930d6 100644 --- a/app/Console/Commands/BackupUpdate.php +++ b/app/Console/Commands/BackupUpdate.php @@ -14,11 +14,9 @@ namespace App\Console\Commands; use App\Libraries\MultiDB; use App\Models\Backup; use App\Models\Company; -use App\Models\Design; use App\Models\Document; use Illuminate\Console\Command; use Illuminate\Support\Facades\Storage; -use stdClass; class BackupUpdate extends Command { @@ -60,7 +58,6 @@ class BackupUpdate extends Command if (! config('ninja.db.multi_db_enabled')) { $this->handleOnDb(); } else { - //multiDB environment, need to foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); @@ -78,50 +75,43 @@ class BackupUpdate extends Command //logos Company::cursor() - ->each(function ($company){ + ->each(function ($company) { + $company_logo = $company->present()->logo(); - $company_logo = $company->present()->logo(); + if ($company_logo == 'https://invoicing.co/images/new_logo.png') { + return; + } - if($company_logo == 'https://invoicing.co/images/new_logo.png') - return; + $logo = @file_get_contents($company_logo); - $logo = @file_get_contents($company_logo); - - if($logo){ - - $path = str_replace("https://objects.invoicing.co/", "", $company->present()->logo()); - $path = str_replace("https://v5-at-backup.us-southeast-1.linodeobjects.com/", "", $path); - - Storage::disk($this->option('disk'))->put($path, $logo); - } + if ($logo) { + $path = str_replace("https://objects.invoicing.co/", "", $company->present()->logo()); + $path = str_replace("https://v5-at-backup.us-southeast-1.linodeobjects.com/", "", $path); + Storage::disk($this->option('disk'))->put($path, $logo); + } }); //documents Document::cursor() - ->each(function ($document){ - + ->each(function ($document) { $doc_bin = $document->getFile(); - if($doc_bin) + if ($doc_bin) { Storage::disk($this->option('disk'))->put($document->url, $doc_bin); - + } }); - //backups + //backups Backup::cursor() - ->each(function ($backup){ + ->each(function ($backup) { + $backup_bin = Storage::disk('s3')->get($backup->filename); - $backup_bin = Storage::disk('s3')->get($backup->filename); - - if($backup_bin) + if ($backup_bin) { Storage::disk($this->option('disk'))->put($backup->filename, $backup_bin); - + } }); - - - } } diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php index 1c47c4b6d920..01a5e9e06e7e 100644 --- a/app/Console/Commands/CheckData.php +++ b/app/Console/Commands/CheckData.php @@ -28,9 +28,7 @@ use App\Models\CreditInvitation; use App\Models\Invoice; use App\Models\InvoiceInvitation; use App\Models\Payment; -use App\Models\Paymentable; use App\Models\PurchaseOrder; -use App\Models\PurchaseOrderInvitation; use App\Models\Quote; use App\Models\QuoteInvitation; use App\Models\RecurringInvoiceInvitation; @@ -102,7 +100,7 @@ class CheckData extends Command public function handle() { - $time_start = microtime(true); + $time_start = microtime(true); $database_connection = $this->option('database') ? $this->option('database') : 'Connected to Default DB'; $fix_status = $this->option('fix') ? "Fixing Issues" : "Just checking issues "; @@ -113,8 +111,8 @@ class CheckData extends Command config(['database.default' => $database]); } - $this->checkInvoiceBalances(); - $this->checkClientBalanceEdgeCases(); + $this->checkInvoiceBalances(); + $this->checkClientBalanceEdgeCases(); $this->checkPaidToDatesNew(); $this->checkContacts(); $this->checkVendorContacts(); @@ -128,7 +126,7 @@ class CheckData extends Command $this->checkCompanyTokens(); $this->checkUserState(); - if(Ninja::isHosted()){ + if (Ninja::isHosted()) { $this->checkAccountStatuses(); $this->checkNinjaPortalUrls(); } @@ -162,44 +160,35 @@ class CheckData extends Command private function checkCompanyTokens() { - - CompanyUser::doesnthave('token')->cursor()->each(function ($cu){ - - if($cu->user){ + CompanyUser::doesnthave('token')->cursor()->each(function ($cu) { + if ($cu->user) { $this->logMessage("Creating missing company token for user # {$cu->user->id} for company id # {$cu->company->id}"); (new CreateCompanyToken($cu->company, $cu->user, 'System'))->handle(); - } - else { + } else { $this->logMessage("Dangling User ID # {$cu->id}"); } - }); - } private function checkOauthSanity() { - User::where('oauth_provider_id', '1')->cursor()->each(function ($user){ - + User::where('oauth_provider_id', '1')->cursor()->each(function ($user) { $this->logMessage("Invalid provider ID for user id# {$user->id}"); - }); } private function checkDuplicateRecurringInvoices() { - - if(Ninja::isHosted()) - { + if (Ninja::isHosted()) { $c = Client::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id')) ->with('recurring_invoices') ->cursor() - ->each(function ($client){ - if($client->recurring_invoices()->where('is_deleted', 0)->where('deleted_at', null)->count() > 1) - $this->logMessage("Duplicate Recurring Invoice => {$client->custom_value1}"); + ->each(function ($client) { + if ($client->recurring_invoices()->where('is_deleted', 0)->where('deleted_at', null)->count() > 1) { + $this->logMessage("Duplicate Recurring Invoice => {$client->custom_value1}"); + } }); } - } @@ -302,7 +291,6 @@ class CheckData extends Command $new_contact->save(); } } - } private function checkVendorContacts() @@ -350,7 +338,6 @@ class CheckData extends Command } if ($this->option('fix') == 'true') { - $vendors = Vendor::withTrashed()->doesntHave('contacts')->get(); foreach ($vendors as $vendor) { @@ -363,7 +350,6 @@ class CheckData extends Command $new_contact->save(); } } - } @@ -418,27 +404,22 @@ class CheckData extends Command User::withTrashed() ->where('deleted_at', '0000-00-00 00:00:00.000000') ->cursor() - ->each(function ($user){ + ->each(function ($user) { $user->restore(); }); } private function checkEntityInvitations() { - - RecurringInvoiceInvitation::where('deleted_at',"0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]); - InvoiceInvitation::where('deleted_at',"0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]); - QuoteInvitation::where('deleted_at',"0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]); - CreditInvitation::where('deleted_at',"0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]); + RecurringInvoiceInvitation::where('deleted_at', "0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]); + InvoiceInvitation::where('deleted_at', "0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]); + QuoteInvitation::where('deleted_at', "0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]); + CreditInvitation::where('deleted_at', "0000-00-00 00:00:00.000000")->withTrashed()->update(['deleted_at' => null]); - collect([Invoice::class, Quote::class, Credit::class, PurchaseOrder::class])->each(function ($entity){ - - if($entity::doesntHave('invitations')->count() > 0) - { - + collect([Invoice::class, Quote::class, Credit::class, PurchaseOrder::class])->each(function ($entity) { + if ($entity::doesntHave('invitations')->count() > 0) { $entity::doesntHave('invitations')->cursor()->each(function ($entity) { - $client_vendor_key = 'client_id'; $contact_id = 'client_contact_id'; $contact_class = ClientContact::class; @@ -446,55 +427,47 @@ class CheckData extends Command $entity_key = \Illuminate\Support\Str::of(class_basename($entity))->snake()->append('_id')->value; $entity_obj = get_class($entity).'Invitation'; - if($entity instanceof PurchaseOrder){ + if ($entity instanceof PurchaseOrder) { $client_vendor_key = 'vendor_id'; $contact_id = 'vendor_contact_id'; $contact_class = VendorContact::class; } - $invitation = false; + $invitation = false; - //check contact exists! - if($contact_class::where('company_id', $entity->company_id)->where($client_vendor_key,$entity->{$client_vendor_key})->exists()) - { + //check contact exists! + if ($contact_class::where('company_id', $entity->company_id)->where($client_vendor_key, $entity->{$client_vendor_key})->exists()) { + $contact = $contact_class::where('company_id', $entity->company_id)->where($client_vendor_key, $entity->{$client_vendor_key})->first(); - $contact = $contact_class::where('company_id', $entity->company_id)->where($client_vendor_key,$entity->{$client_vendor_key})->first(); - - //double check if an archived invite exists - if($contact && $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->count() != 0) { - $i = $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->first(); - $i->restore(); - $this->logMessage("Found a valid contact and invitation restoring for {$entity_key} - {$entity->id}"); - } - else { - $invitation = new $entity_obj(); - $invitation->company_id = $entity->company_id; - $invitation->user_id = $entity->user_id; - $invitation->{$entity_key} = $entity->id; - $invitation->{$contact_id} = $contact->id; - $invitation->key = Str::random(config('ninja.key_length')); - $this->logMessage("Add invitation for {$entity_key} - {$entity->id}"); - } + //double check if an archived invite exists + if ($contact && $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->count() != 0) { + $i = $entity_obj::withTrashed()->where($entity_key, $entity->id)->where($contact_id, $contact->id)->first(); + $i->restore(); + $this->logMessage("Found a valid contact and invitation restoring for {$entity_key} - {$entity->id}"); + } else { + $invitation = new $entity_obj(); + $invitation->company_id = $entity->company_id; + $invitation->user_id = $entity->user_id; + $invitation->{$entity_key} = $entity->id; + $invitation->{$contact_id} = $contact->id; + $invitation->key = Str::random(config('ninja.key_length')); + $this->logMessage("Add invitation for {$entity_key} - {$entity->id}"); } - else - $this->logMessage("No contact present, so cannot add invitation for {$entity_key} - {$entity->id}"); - - try{ - - if($invitation) - $invitation->save(); + } else { + $this->logMessage("No contact present, so cannot add invitation for {$entity_key} - {$entity->id}"); } - catch(\Exception $e){ + + try { + if ($invitation) { + $invitation->save(); + } + } catch(\Exception $e) { $this->logMessage($e->getMessage()); $invitation = null; } - }); - } - }); - } private function fixInvitations($entities, $entity) @@ -503,8 +476,7 @@ class CheckData extends Command $entity_obj = 'App\Models\\'.ucfirst(Str::camel($entity)).'Invitation'; - foreach($entities as $entity) - { + foreach ($entities as $entity) { $invitation = new $entity_obj(); $invitation->company_id = $entity->company_id; $invitation->user_id = $entity->user_id; @@ -512,20 +484,17 @@ class CheckData extends Command $invitation->client_contact_id = ClientContact::whereClientId($entity->client_id)->first()->id; $invitation->key = Str::random(config('ninja.key_length')); - try{ + try { $invitation->save(); - } - catch(\Exception $e){ + } catch(\Exception $e) { $invitation = null; } - } - } private function clientPaidToDateQuery() { - $results = \DB::select( \DB::raw(" + $results = \DB::select(\DB::raw(" SELECT clients.id as client_id, clients.paid_to_date as client_paid_to_date, @@ -540,14 +509,14 @@ class CheckData extends Command GROUP BY clients.id HAVING payments_applied != client_paid_to_date ORDER BY clients.id; - ") ); + ")); return $results; } private function clientCreditPaymentables($client) { - $results = \DB::select( \DB::raw(" + $results = \DB::select(\DB::raw(" SELECT SUM(paymentables.amount - paymentables.refunded) as credit_payment FROM payments @@ -559,7 +528,7 @@ class CheckData extends Command AND paymentables.amount > 0 AND payments.is_deleted = 0 AND payments.client_id = ?; - "), [App\Models\Credit::class, $client->id] ); + "), [App\Models\Credit::class, $client->id]); return $results; } @@ -570,8 +539,7 @@ class CheckData extends Command $this->wrong_paid_to_dates = 0; - foreach($clients_to_check as $_client) - { + foreach ($clients_to_check as $_client) { $client = Client::withTrashed()->find($_client->client_id); $credits_from_reversal = Credit::withTrashed()->where('client_id', $client->id)->where('is_deleted', 0)->whereNotNull('invoice_id')->sum('amount'); @@ -580,26 +548,22 @@ class CheckData extends Command $total_paid_to_date = $_client->payments_applied + $credits_used_for_payments[0]->credit_payment - $credits_from_reversal; - if(round($total_paid_to_date,2) != round($_client->client_paid_to_date,2)){ - + if (round($total_paid_to_date, 2) != round($_client->client_paid_to_date, 2)) { $this->wrong_paid_to_dates++; $this->logMessage($client->present()->name().' id = # '.$client->id." - Client Paid To Date = {$client->paid_to_date} != Invoice Payments = {$total_paid_to_date} - {$_client->payments_applied} + {$credits_used_for_payments[0]->credit_payment}"); $this->isValid = false; - if($this->option('paid_to_date')){ + if ($this->option('paid_to_date')) { $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->paid_to_date} to {$total_paid_to_date}"); $client->paid_to_date = $total_paid_to_date; $client->save(); } - } - } $this->logMessage("{$this->wrong_paid_to_dates} clients with incorrect paid to dates"); - } private function checkPaidToDates() @@ -608,12 +572,12 @@ class CheckData extends Command $credit_total_applied = 0; $clients = DB::table('clients') - ->leftJoin('payments', function($join) { + ->leftJoin('payments', function ($join) { $join->on('payments.client_id', '=', 'clients.id') ->where('payments.is_deleted', 0) - ->whereIn('payments.status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]); + ->whereIn('payments.status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]); }) - ->where('clients.is_deleted',0) + ->where('clients.is_deleted', 0) ->where('clients.updated_at', '>', now()->subDays(2)) ->groupBy('clients.id') ->havingRaw('clients.paid_to_date != sum(coalesce(payments.amount - payments.refunded, 0))') @@ -621,32 +585,28 @@ class CheckData extends Command /* Due to accounting differences we need to perform a second loop here to ensure there actually is an issue */ $clients->each(function ($client_record) use ($credit_total_applied) { - $client = Client::withTrashed()->find($client_record->id); $total_invoice_payments = 0; foreach ($client->invoices()->where('is_deleted', false)->where('status_id', '>', 1)->get() as $invoice) { - $total_invoice_payments += $invoice->payments() - ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) + ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) ->selectRaw('sum(paymentables.amount - paymentables.refunded) as p') ->pluck('p') ->first(); - } //commented IN 27/06/2021 - sums ALL client payments AND the unapplied amounts to match the client paid to date $p = Payment::where('client_id', $client->id) ->where('is_deleted', 0) - ->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) + ->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) ->sum(DB::Raw('amount - applied')); $total_invoice_payments += $p; // 10/02/21 foreach ($client->payments as $payment) { - $credit_total_applied += $payment->paymentables() ->where('paymentable_type', App\Models\Credit::class) ->selectRaw('sum(paymentables.amount - paymentables.refunded) as p') @@ -656,7 +616,7 @@ class CheckData extends Command if ($credit_total_applied < 0) { $total_invoice_payments += $credit_total_applied; - } + } if (round($total_invoice_payments, 2) != round($client->paid_to_date, 2)) { $this->wrong_paid_to_dates++; @@ -665,7 +625,7 @@ class CheckData extends Command $this->isValid = false; - if($this->option('paid_to_date')){ + if ($this->option('paid_to_date')) { $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->paid_to_date} to {$total_invoice_payments}"); $client->paid_to_date = $total_invoice_payments; $client->save(); @@ -681,11 +641,9 @@ class CheckData extends Command $this->wrong_balances = 0; Client::cursor()->where('is_deleted', 0)->where('clients.updated_at', '>', now()->subDays(2))->each(function ($client) { - $client->invoices->where('is_deleted', false)->whereIn('status_id', '!=', Invoice::STATUS_DRAFT)->each(function ($invoice) use ($client) { - $total_paid = $invoice->payments() - ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) + ->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED]) ->selectRaw('sum(paymentables.amount - paymentables.refunded) as p') ->pluck('p') ->first(); @@ -702,7 +660,6 @@ class CheckData extends Command $this->isValid = false; } }); - }); $this->logMessage("{$this->wrong_balances} clients with incorrect invoice balances"); @@ -710,7 +667,7 @@ class CheckData extends Command private function clientBalanceQuery() { - $results = \DB::select( \DB::raw(" + $results = \DB::select(\DB::raw(" SELECT SUM(invoices.balance) as invoice_balance, clients.id as client_id, @@ -724,7 +681,7 @@ class CheckData extends Command GROUP BY clients.id HAVING invoice_balance != clients.balance ORDER BY clients.id; - ") ); + ")); return $results; } @@ -736,8 +693,7 @@ class CheckData extends Command $clients = $this->clientBalanceQuery(); - foreach($clients as $client) - { + foreach ($clients as $client) { $client = (array)$client; if ((string) $client['invoice_balance'] != (string) $client['client_balance']) { @@ -747,18 +703,14 @@ class CheckData extends Command $this->logMessage($client_object->present()->name().' - '.$client_object->id." - calculated client balances do not match Invoice Balances = ". $client['invoice_balance'] ." - Client Balance = ".rtrim($client['client_balance'], '0')); - if($this->option('client_balance')){ - + if ($this->option('client_balance')) { $this->logMessage("# {$client_object->id} " . $client_object->present()->name().' - '.$client_object->number." Fixing {$client_object->balance} to " . $client['invoice_balance']); $client_object->balance = $client['invoice_balance']; $client_object->save(); - } - $this->isValid = false; - + $this->isValid = false; } - } $this->logMessage("{$this->wrong_paid_to_dates} clients with incorrect client balances"); @@ -767,58 +719,46 @@ class CheckData extends Command private function checkClientBalanceEdgeCases() { Client::query() - ->where('is_deleted',false) + ->where('is_deleted', false) ->where('balance', '!=', 0) ->cursor() - ->each(function ($client){ + ->each(function ($client) { + $count = Invoice::withTrashed() + ->where('client_id', $client->id) + ->where('is_deleted', false) + ->whereIn('status_id', [2,3]) + ->count(); - $count = Invoice::withTrashed() - ->where('client_id', $client->id) - ->where('is_deleted',false) - ->whereIn('status_id', [2,3]) - ->count(); + if ($count == 0) { + //factor in over payments to the client balance + $over_payment = Payment::where('client_id', $client->id) + ->where('is_deleted', 0) + ->whereIn('status_id', [1,4]) + ->selectRaw('sum(amount - applied) as p') + ->pluck('p') + ->first(); - if($count == 0){ - - //factor in over payments to the client balance - $over_payment = Payment::where('client_id', $client->id) - ->where('is_deleted', 0) - ->whereIn('status_id', [1,4]) - ->selectRaw('sum(amount - applied) as p') - ->pluck('p') - ->first(); + $over_payment = $over_payment*-1; - $over_payment = $over_payment*-1; - - if(floatval($over_payment) == floatval($client->balance)){ - - } - else { - - $this->logMessage("# {$client->id} # {$client->name} {$client->balance} is invalid should be {$over_payment}"); - - } + if (floatval($over_payment) == floatval($client->balance)) { + } else { + $this->logMessage("# {$client->id} # {$client->name} {$client->balance} is invalid should be {$over_payment}"); + } - if($this->option('client_balance') && (floatval($over_payment) != floatval($client->balance) )){ - - $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to 0"); - - $client->balance = $over_payment; - $client->save(); - - } - - - } + if ($this->option('client_balance') && (floatval($over_payment) != floatval($client->balance))) { + $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to 0"); + $client->balance = $over_payment; + $client->save(); + } + } }); - } private function invoiceBalanceQuery() { - $results = \DB::select( \DB::raw(" + $results = \DB::select(\DB::raw(" SELECT clients.id, clients.balance, @@ -832,7 +772,7 @@ class CheckData extends Command GROUP BY clients.id HAVING(invoices_balance != clients.balance) ORDER BY clients.id; - ") ); + ")); return $results; } @@ -844,8 +784,7 @@ class CheckData extends Command $_clients = $this->invoiceBalanceQuery(); - foreach($_clients as $_client) - { + foreach ($_clients as $_client) { $client = Client::withTrashed()->find($_client->id); $invoice_balance = $client->invoices()->where('is_deleted', false)->whereIn('status_id', [2,3])->sum('balance'); @@ -860,27 +799,22 @@ class CheckData extends Command $this->isValid = false; - if($this->option('client_balance')){ - + if ($this->option('client_balance')) { $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to {$invoice_balance}"); $client->balance = $invoice_balance; $client->save(); - } - if($ledger && (number_format($invoice_balance, 4) != number_format($ledger->balance, 4))) - { + if ($ledger && (number_format($invoice_balance, 4) != number_format($ledger->balance, 4))) { $ledger->adjustment = $invoice_balance; $ledger->balance = $invoice_balance; $ledger->notes = 'Ledger Adjustment'; $ledger->save(); } - } } $this->logMessage("{$this->wrong_balances} clients with incorrect balances"); - } private function checkLedgerBalances() @@ -899,8 +833,7 @@ class CheckData extends Command $this->isValid = false; - if($this->option('ledger_balance')){ - + if ($this->option('ledger_balance')) { $this->logMessage("# {$client->id} " . $client->present()->name().' - '.$client->number." Fixing {$client->balance} to {$invoice_balance}"); $client->balance = $invoice_balance; $client->save(); @@ -910,7 +843,6 @@ class CheckData extends Command $ledger->notes = 'Ledger Adjustment'; $ledger->save(); } - } } @@ -1002,31 +934,27 @@ class CheckData extends Command public function checkAccountStatuses() { - Account::where('plan_expires', '<=', now()->subDays(2))->cursor()->each(function ($account){ - + Account::where('plan_expires', '<=', now()->subDays(2))->cursor()->each(function ($account) { $client = Client::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))->where('custom_value2', $account->key)->first(); - if($client){ + if ($client) { $payment = Payment::on('db-ninja-01') ->where('company_id', config('ninja.ninja_default_company_id')) ->where('client_id', $client->id) ->where('date', '>=', now()->subDays(2)) ->exists(); - if($payment) + if ($payment) { $this->logMessage("I found a payment for {$account->key}"); - + } } - }); } public function checkClientSettings() { - if ($this->option('fix') == 'true') { - // Client::query()->whereNull('settings->currency_id')->cursor()->each(function ($client){ // if(is_array($client->settings) && count($client->settings) == 0) @@ -1047,36 +975,25 @@ class CheckData extends Command // }); - Client::query()->whereNull('country_id')->cursor()->each(function ($client){ - + Client::query()->whereNull('country_id')->cursor()->each(function ($client) { $client->country_id = $client->company->settings->country_id; $client->save(); $this->logMessage("Fixing country for # {$client->id}"); - }); - } - } public function checkVendorSettings() { - - if ($this->option('fix') == 'true') - { - - Vendor::query()->whereNull('currency_id')->orWhere('currency_id', '')->cursor()->each(function ($vendor){ - + if ($this->option('fix') == 'true') { + Vendor::query()->whereNull('currency_id')->orWhere('currency_id', '')->cursor()->each(function ($vendor) { $vendor->currency_id = $vendor->company->settings->currency_id; $vendor->save(); $this->logMessage("Fixing vendor currency for # {$vendor->id}"); - }); - } - } @@ -1085,14 +1002,12 @@ class CheckData extends Command { $this->wrong_paid_status = 0; - foreach(Invoice::with(['payments'])->where('is_deleted',0)->where('balance', '>', 0)->whereHas('payments')->where('status_id', 4)->cursor() as $invoice) - { + foreach (Invoice::with(['payments'])->where('is_deleted', 0)->where('balance', '>', 0)->whereHas('payments')->where('status_id', 4)->cursor() as $invoice) { $this->wrong_paid_status++; $this->logMessage("# {$invoice->id} " . ' - '.$invoice->number." - Marked as paid, but balance = {$invoice->balance}"); - if($this->option('balance_status')){ - + if ($this->option('balance_status')) { $val = $invoice->balance; $invoice->balance = 0; @@ -1101,8 +1016,7 @@ class CheckData extends Command $p = $invoice->payments->first(); - if($p && (int)$p->amount == 0) - { + if ($p && (int)$p->amount == 0) { $p->amount = $val; $p->applied = $val; $p->save(); @@ -1114,62 +1028,48 @@ class CheckData extends Command $this->logMessage("Fixing {$invoice->id} settings payment to {$val}"); - } - } $this->logMessage($this->wrong_paid_status." wrong invoices with bad balance state"); - } public function checkNinjaPortalUrls() { - - $wrong_count = CompanyUser::where('is_owner',1)->where('ninja_portal_url', '')->count(); + $wrong_count = CompanyUser::where('is_owner', 1)->where('ninja_portal_url', '')->count(); $this->logMessage("Missing ninja portal Urls = {$wrong_count}"); - if(!$this->option('portal_url')) + if (!$this->option('portal_url')) { return; + } - CompanyUser::where('is_owner',1)->where('ninja_portal_url', '')->cursor()->each(function ($cu){ + CompanyUser::where('is_owner', 1)->where('ninja_portal_url', '')->cursor()->each(function ($cu) { + $cc = ClientContact::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))->where('email', $cu->user->email)->first(); - $cc = ClientContact::on('db-ninja-01')->where('company_id', config('ninja.ninja_default_company_id'))->where('email', $cu->user->email)->first(); - - if($cc){ + if ($cc) { $ninja_portal_url = "https://invoiceninja.invoicing.co/client/ninja/{$cc->contact_key}/{$cu->account->key}"; $cu->ninja_portal_url = $ninja_portal_url; $cu->save(); $this->logMessage("Fixing - {$ninja_portal_url}"); - } - else{ - + } else { $c = Client::on('db-ninja-01')->where("company_id", config('ninja.ninja_default_company_id'))->where('custom_value2', $cu->account->key)->first(); - if($c) - { - - $cc = $c->contacts()->first(); + if ($c) { + $cc = $c->contacts()->first(); - if($cc) - { + if ($cc) { $ninja_portal_url = "https://invoiceninja.invoicing.co/client/ninja/{$cc->contact_key}/{$cu->account->key}"; $cu->ninja_portal_url = $ninja_portal_url; $cu->save(); $this->logMessage("Fixing - {$ninja_portal_url}"); - - } - } - + } } - }); - } -} \ No newline at end of file +} diff --git a/app/Console/Commands/CheckDb.php b/app/Console/Commands/CheckDb.php index c8e09736aac0..f143b0c5a834 100644 --- a/app/Console/Commands/CheckDb.php +++ b/app/Console/Commands/CheckDb.php @@ -11,8 +11,6 @@ namespace App\Console\Commands; -use App; -use App\Factory\ClientContactFactory; use App\Models\Account; use App\Models\Activity; use App\Models\Backup; @@ -24,7 +22,6 @@ use App\Models\CompanyGateway; use App\Models\CompanyLedger; use App\Models\CompanyToken; use App\Models\CompanyUser; -use App\Models\Contact; use App\Models\Credit; use App\Models\CreditInvitation; use App\Models\Design; @@ -53,13 +50,7 @@ use App\Models\User; use App\Models\Vendor; use App\Models\VendorContact; use App\Models\Webhook; -use App\Utils\Ninja; -use DB; -use Exception; use Illuminate\Console\Command; -use Illuminate\Support\Str; -use Mail; -use Symfony\Component\Console\Input\InputOption; /** * Class CheckDb. diff --git a/app/Console/Commands/CreateAccount.php b/app/Console/Commands/CreateAccount.php index 5748d32da6d3..e4e5b31e3dca 100644 --- a/app/Console/Commands/CreateAccount.php +++ b/app/Console/Commands/CreateAccount.php @@ -13,40 +13,19 @@ namespace App\Console\Commands; use App\DataMapper\ClientRegistrationFields; use App\DataMapper\CompanySettings; -use App\DataMapper\FeesAndLimits; -use App\Events\Invoice\InvoiceWasCreated; -use App\Factory\InvoiceFactory; -use App\Factory\InvoiceItemFactory; -use App\Helpers\Invoice\InvoiceSum; use App\Jobs\Company\CreateCompanyPaymentTerms; use App\Jobs\Company\CreateCompanyTaskStatuses; use App\Jobs\Util\VersionCheck; use App\Models\Account; -use App\Models\Client; -use App\Models\ClientContact; use App\Models\Company; -use App\Models\CompanyGateway; use App\Models\CompanyToken; -use App\Models\Country; -use App\Models\Credit; -use App\Models\Expense; -use App\Models\Product; -use App\Models\Project; -use App\Models\Quote; -use App\Models\Task; use App\Models\User; -use App\Models\Vendor; -use App\Models\VendorContact; use App\Repositories\InvoiceRepository; -use App\Utils\Ninja; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; -use Carbon\Carbon; -use Faker\Factory; use Illuminate\Console\Command; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Hash; -use Illuminate\Support\Facades\Schema; use Illuminate\Support\Str; class CreateAccount extends Command @@ -140,7 +119,6 @@ class CreateAccount extends Command (new VersionCheck())->handle(); $this->warmCache(); - } private function warmCache() @@ -162,7 +140,6 @@ class CreateAccount extends Command if ($tableData->count()) { Cache::forever($name, $tableData); } - } } } diff --git a/app/Console/Commands/CreateSingleAccount.php b/app/Console/Commands/CreateSingleAccount.php index d1a77dadbcdd..402769667cb3 100644 --- a/app/Console/Commands/CreateSingleAccount.php +++ b/app/Console/Commands/CreateSingleAccount.php @@ -50,13 +50,11 @@ use App\Utils\Ninja; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; use Carbon\Carbon; -use Database\Factories\BankTransactionRuleFactory; use Faker\Factory; use Illuminate\Console\Command; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Schema; -use Illuminate\Support\Str; use stdClass; class CreateSingleAccount extends Command @@ -80,9 +78,9 @@ class CreateSingleAccount extends Command */ public function handle() { - - if (Ninja::isHosted() || config('ninja.is_docker') || !$this->confirm('Are you sure you want to inject dummy data?')) + if (Ninja::isHosted() || config('ninja.is_docker') || !$this->confirm('Are you sure you want to inject dummy data?')) { return; + } $this->invoice_repo = new InvoiceRepository(); @@ -103,8 +101,7 @@ class CreateSingleAccount extends Command { $this->info('Creating Small Account and Company'); - if($user = User::where('email','small@example.com')->first()) - { + if ($user = User::where('email', 'small@example.com')->first()) { $user->account->delete(); } @@ -201,7 +198,7 @@ class CreateSingleAccount extends Command $btr = BankTransactionRule::factory()->create([ 'user_id' => $user->id, 'company_id' => $company->id, - 'applies_to' => (bool)rand(0,1) ? 'CREDIT' : 'DEBIT', + 'applies_to' => (bool)rand(0, 1) ? 'CREDIT' : 'DEBIT', ]); $client = Client::factory()->create([ @@ -359,7 +356,6 @@ class CreateSingleAccount extends Command private function createClient($company, $user) { - // dispatch(function () use ($company, $user) { // }); @@ -630,30 +626,29 @@ class CreateSingleAccount extends Command $cached_tables = config('ninja.cached_tables'); foreach ($cached_tables as $name => $class) { - // check that the table exists in case the migration is pending - if (! Schema::hasTable((new $class())->getTable())) { - continue; - } - if ($name == 'payment_terms') { - $orderBy = 'num_days'; - } elseif ($name == 'fonts') { - $orderBy = 'sort_order'; - } elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) { - $orderBy = 'name'; - } else { - $orderBy = 'id'; - } - $tableData = $class::orderBy($orderBy)->get(); - if ($tableData->count()) { - Cache::forever($name, $tableData); - } + // check that the table exists in case the migration is pending + if (! Schema::hasTable((new $class())->getTable())) { + continue; + } + if ($name == 'payment_terms') { + $orderBy = 'num_days'; + } elseif ($name == 'fonts') { + $orderBy = 'sort_order'; + } elseif (in_array($name, ['currencies', 'industries', 'languages', 'countries', 'banks'])) { + $orderBy = 'name'; + } else { + $orderBy = 'id'; + } + $tableData = $class::orderBy($orderBy)->get(); + if ($tableData->count()) { + Cache::forever($name, $tableData); + } } } private function createGateways($company, $user) { if (config('ninja.testvars.stripe') && ($this->gateway == 'all' || $this->gateway == 'stripe')) { - $cg = new CompanyGateway; $cg->company_id = $company->id; $cg->user_id = $user->id; @@ -672,8 +667,6 @@ class CreateSingleAccount extends Command $cg->fees_and_limits = $fees_and_limits; $cg->save(); - - } if (config('ninja.testvars.paypal') && ($this->gateway == 'all' || $this->gateway == 'paypal')) { diff --git a/app/Console/Commands/CreateTestData.php b/app/Console/Commands/CreateTestData.php index e7b5d44d7998..cd94c3ab70c2 100644 --- a/app/Console/Commands/CreateTestData.php +++ b/app/Console/Commands/CreateTestData.php @@ -380,7 +380,6 @@ class CreateTestData extends Command private function createClient($company, $user) { - // dispatch(function () use ($company, $user) { // }); diff --git a/app/Console/Commands/DemoMode.php b/app/Console/Commands/DemoMode.php index 3acbdd942d83..8cde523d3eed 100644 --- a/app/Console/Commands/DemoMode.php +++ b/app/Console/Commands/DemoMode.php @@ -257,7 +257,6 @@ class DemoMode extends Command private function createClient($company, $user, $assigned_user_id = null) { - // dispatch(function () use ($company, $user) { // }); diff --git a/app/Console/Commands/DesignUpdate.php b/app/Console/Commands/DesignUpdate.php index e069afa93799..c924ea268dfc 100644 --- a/app/Console/Commands/DesignUpdate.php +++ b/app/Console/Commands/DesignUpdate.php @@ -56,7 +56,6 @@ class DesignUpdate extends Command if (! config('ninja.db.multi_db_enabled')) { $this->handleOnDb(); } else { - //multiDB environment, need to foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); diff --git a/app/Console/Commands/HostedMigrations.php b/app/Console/Commands/HostedMigrations.php index 77ca261b2d37..d2a3b4bcc1b8 100644 --- a/app/Console/Commands/HostedMigrations.php +++ b/app/Console/Commands/HostedMigrations.php @@ -11,27 +11,19 @@ namespace App\Console\Commands; -use App\DataMapper\CompanySettings; use App\Exceptions\MigrationValidatorFailed; use App\Exceptions\NonExistingMigrationFile; use App\Exceptions\ProcessingMigrationArchiveFailed; use App\Exceptions\ResourceDependencyMissing; use App\Exceptions\ResourceNotAvailableForMigration; use App\Jobs\Util\Import; -use App\Jobs\Util\StartMigration; use App\Libraries\MultiDB; use App\Mail\MigrationFailed; -use App\Models\Account; -use App\Models\Company; -use App\Models\CompanyToken; use App\Models\User; use App\Utils\Traits\AppSetup; use App\Utils\Traits\MakesHash; use DirectoryIterator; -use Faker\Factory; -use Faker\Generator; use Illuminate\Console\Command; -use Illuminate\Support\Str; use ZipArchive; class HostedMigrations extends Command diff --git a/app/Console/Commands/HostedUsers.php b/app/Console/Commands/HostedUsers.php index 92df70a91830..133198b3e4cd 100644 --- a/app/Console/Commands/HostedUsers.php +++ b/app/Console/Commands/HostedUsers.php @@ -11,9 +11,7 @@ namespace App\Console\Commands; -use App\Models\ClientContact; use App\Models\Company; -use App\Models\User; use App\Utils\Ninja; use Illuminate\Console\Command; diff --git a/app/Console/Commands/MobileLocalization.php b/app/Console/Commands/MobileLocalization.php index bcc3fc6df7bb..482cf9042ade 100644 --- a/app/Console/Commands/MobileLocalization.php +++ b/app/Console/Commands/MobileLocalization.php @@ -11,8 +11,6 @@ namespace App\Console\Commands; -use App\Models\Company; -use App\Models\User; use App\Utils\CurlUtils; use Illuminate\Console\Command; diff --git a/app/Console/Commands/OpenApiYaml.php b/app/Console/Commands/OpenApiYaml.php index 9c43a7408a9e..06ea62e50eaf 100644 --- a/app/Console/Commands/OpenApiYaml.php +++ b/app/Console/Commands/OpenApiYaml.php @@ -63,9 +63,7 @@ class OpenApiYaml extends Command $this->info($directory); foreach ($directory as $file) { - - $this->info($file); - + $this->info($file); } Storage::disk('base')->delete('/openapi/api-docs.yaml'); @@ -76,14 +74,9 @@ class OpenApiYaml extends Command $directory = new DirectoryIterator($path . '/paths/'); foreach ($directory as $file) { - - if ($file->isFile() && ! $file->isDot()) - { - + if ($file->isFile() && ! $file->isDot()) { Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents("{$path}/paths/{$file->getFilename()}")); - } - } @@ -96,20 +89,12 @@ class OpenApiYaml extends Command $directory = new DirectoryIterator($path . '/components/schemas/'); foreach ($directory as $file) { - - if ($file->isFile() && ! $file->isDot()) - { - + if ($file->isFile() && ! $file->isDot()) { Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents("{$path}/components/schemas/{$file->getFilename()}")); - } - } // Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents($path.'/components/schemas/account.yaml')); Storage::disk('base')->append('/openapi/api-docs.yaml', file_get_contents($path.'/misc/misc.yaml')); - - } - } diff --git a/app/Console/Commands/PostUpdate.php b/app/Console/Commands/PostUpdate.php index 8b71ba90d81d..9f6365404efa 100644 --- a/app/Console/Commands/PostUpdate.php +++ b/app/Console/Commands/PostUpdate.php @@ -12,7 +12,6 @@ namespace App\Console\Commands; use App\Jobs\Util\VersionCheck; -use App\Utils\Ninja; use App\Utils\Traits\AppSetup; use Illuminate\Console\Command; use Illuminate\Support\Facades\Artisan; diff --git a/app/Console/Commands/ReactBuilder.php b/app/Console/Commands/ReactBuilder.php index c155bc2a43b0..7e75e59887b7 100644 --- a/app/Console/Commands/ReactBuilder.php +++ b/app/Console/Commands/ReactBuilder.php @@ -11,12 +11,7 @@ namespace App\Console\Commands; -use App\Libraries\MultiDB; -use App\Models\Backup; -use App\Models\Design; use Illuminate\Console\Command; -use Illuminate\Support\Facades\Storage; -use stdClass; class ReactBuilder extends Command { diff --git a/app/Console/Commands/SendRemindersCron.php b/app/Console/Commands/SendRemindersCron.php index 5f190351b9af..7319ec30f727 100644 --- a/app/Console/Commands/SendRemindersCron.php +++ b/app/Console/Commands/SendRemindersCron.php @@ -14,7 +14,6 @@ namespace App\Console\Commands; use App\DataMapper\InvoiceItem; use App\Events\Invoice\InvoiceWasEmailed; use App\Jobs\Entity\EmailEntity; -use App\Jobs\Ninja\SendReminders; use App\Jobs\Util\WebhookHandler; use App\Libraries\MultiDB; use App\Models\Invoice; @@ -97,7 +96,6 @@ class SendRemindersCron extends Command $invoice->save(); } }); - } private function calcLateFee($invoice, $template) :Invoice diff --git a/app/Console/Commands/SendTestEmails.php b/app/Console/Commands/SendTestEmails.php index 1b2a0920307d..0b0aef8bdfcb 100644 --- a/app/Console/Commands/SendTestEmails.php +++ b/app/Console/Commands/SendTestEmails.php @@ -13,22 +13,14 @@ namespace App\Console\Commands; use App\DataMapper\CompanySettings; use App\DataMapper\DefaultSettings; -use App\Factory\ClientFactory; -use App\Factory\InvoiceFactory; -use App\Factory\InvoiceInvitationFactory; -use App\Jobs\Invoice\CreateEntityPdf; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Mail\Migration\MaxCompanies; -use App\Mail\TemplateEmail; use App\Models\Account; -use App\Models\Client; -use App\Models\ClientContact; use App\Models\Company; use App\Models\User; use Faker\Factory; use Illuminate\Console\Command; -use Illuminate\Support\Facades\Mail; class SendTestEmails extends Command { diff --git a/app/Console/Commands/TranslationsExport.php b/app/Console/Commands/TranslationsExport.php index a88375cb405a..98a34e59bfac 100644 --- a/app/Console/Commands/TranslationsExport.php +++ b/app/Console/Commands/TranslationsExport.php @@ -11,14 +11,10 @@ namespace App\Console\Commands; -use App\Libraries\MultiDB; -use App\Models\Backup; -use App\Models\Design; use Illuminate\Console\Command; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\Storage; -use stdClass; class TranslationsExport extends Command { @@ -98,42 +94,35 @@ class TranslationsExport extends Command { $type =$this->option('type') ?? 'export'; - if($type == 'import') + if ($type == 'import') { $this->import(); + } - if($type == 'export') + if ($type == 'export') { $this->export(); - + } } private function import() { //loop and - foreach($this->langs as $lang) - { - + foreach ($this->langs as $lang) { $import_file = "textsphp_{$lang}.php"; $dir = $this->option('path') ?? storage_path('lang_import/'); $path = $dir.$import_file; - if(file_exists($path)){ + if (file_exists($path)) { $this->logMessage($path); $trans = file_get_contents($path); file_put_contents(lang_path("/{$lang}/texts.php"), $trans); - - } - else{ - + } else { $this->logMessage("Could not open file"); $this->logMessage($path); - } - } - } @@ -147,7 +136,7 @@ class TranslationsExport extends Command $translations = Lang::getLoader()->load($lang, 'texts'); Storage::disk('local')->put("lang/{$lang}/{$lang}.json", json_encode(Arr::dot($translations), JSON_UNESCAPED_UNICODE)); - } + } } private function logMessage($str) @@ -156,5 +145,4 @@ class TranslationsExport extends Command $this->info($str); $this->log .= $str."\n"; } - } diff --git a/app/Console/Commands/TypeCheck.php b/app/Console/Commands/TypeCheck.php index 387191db9054..d26785b0ad4b 100644 --- a/app/Console/Commands/TypeCheck.php +++ b/app/Console/Commands/TypeCheck.php @@ -11,17 +11,11 @@ namespace App\Console\Commands; -use App\Http\ValidationRules\ValidClientGroupSettingsRule; use App\Libraries\MultiDB; -use App\Models\Backup; use App\Models\Client; use App\Models\Company; -use App\Models\Design; use App\Utils\Traits\ClientGroupSettingsSaver; use Illuminate\Console\Command; -use Illuminate\Support\Facades\Storage; -use Illuminate\Support\Facades\Validator; -use stdClass; class TypeCheck extends Command { diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 056e3312a5de..4ba49439c45d 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -15,14 +15,13 @@ use App\Jobs\Cron\AutoBillCron; use App\Jobs\Cron\RecurringExpensesCron; use App\Jobs\Cron\RecurringInvoicesCron; use App\Jobs\Cron\SubscriptionCron; -use App\Jobs\Ledger\LedgerBalanceUpdate; +use App\Jobs\Invoice\InvoiceCheckLateWebhook; use App\Jobs\Ninja\AdjustEmailQuota; use App\Jobs\Ninja\BankTransactionSync; use App\Jobs\Ninja\CompanySizeCheck; use App\Jobs\Ninja\QueueSize; use App\Jobs\Ninja\SystemMaintenance; use App\Jobs\Ninja\TaskScheduler; -use App\Jobs\Invoice\InvoiceCheckLateWebhook; use App\Jobs\Quote\QuoteCheckExpired; use App\Jobs\Subscription\CleanStaleInvoiceOrder; use App\Jobs\Util\DiskCleanup; @@ -96,16 +95,13 @@ class Kernel extends ConsoleKernel if (Ninja::isSelfHost()) { - $schedule->call(function () { Account::whereNotNull('id')->update(['is_scheduler_running' => true]); })->everyFiveMinutes(); - } /* Run hosted specific jobs */ if (Ninja::isHosted()) { - $schedule->job(new AdjustEmailQuota)->dailyAt('23:30')->withoutOverlapping(); /* Pulls in bank transactions from third party services */ @@ -119,15 +115,12 @@ class Kernel extends ConsoleKernel $schedule->command('ninja:check-data --database=db-ninja-02')->dailyAt('02:20')->withoutOverlapping()->name('check-data-db-2-job')->onOneServer(); $schedule->command('ninja:s3-cleanup')->dailyAt('23:15')->withoutOverlapping()->name('s3-cleanup-job')->onOneServer(); - } if (config('queue.default') == 'database' && Ninja::isSelfHost() && config('ninja.internal_queue_enabled') && ! config('ninja.is_docker')) { - $schedule->command('queue:work database --stop-when-empty --memory=256')->everyMinute()->withoutOverlapping(); $schedule->command('queue:restart')->everyFiveMinutes()->withoutOverlapping(); - } } diff --git a/app/DataMapper/BaseSettings.php b/app/DataMapper/BaseSettings.php index 1b0269e86489..489e77db1078 100644 --- a/app/DataMapper/BaseSettings.php +++ b/app/DataMapper/BaseSettings.php @@ -57,5 +57,4 @@ class BaseSettings return $value; } } - } diff --git a/app/DataMapper/CompanySettings.php b/app/DataMapper/CompanySettings.php index 20e479ebebc2..fc3630d6646a 100644 --- a/app/DataMapper/CompanySettings.php +++ b/app/DataMapper/CompanySettings.php @@ -762,7 +762,6 @@ class CompanySettings extends BaseSettings */ public static function defaults(): stdClass { - $data = (object) get_class_vars(self::class); unset($data->casts); diff --git a/app/DataMapper/EmailTemplateDefaults.php b/app/DataMapper/EmailTemplateDefaults.php index 0f2d856aa0c5..c0c1c1d43ce8 100644 --- a/app/DataMapper/EmailTemplateDefaults.php +++ b/app/DataMapper/EmailTemplateDefaults.php @@ -20,7 +20,6 @@ class EmailTemplateDefaults App::setLocale($locale); switch ($template) { - /* Template */ case 'email_template_invoice': @@ -65,7 +64,7 @@ class EmailTemplateDefaults return self::emailPurchaseOrderTemplate(); break; - /* Subject */ + /* Subject */ case 'email_subject_purchase_order': return self::emailPurchaseOrderSubject(); case 'email_subject_invoice': @@ -240,7 +239,6 @@ class EmailTemplateDefaults public static function emailStatementTemplate() { - $statement_message = '

$client

'.self::transformText('client_statement_body').'

'; return $statement_message; diff --git a/app/DataMapper/Schedule/ClientStatement.php b/app/DataMapper/Schedule/ClientStatement.php index 1e9720593ead..a51cc15154fd 100644 --- a/app/DataMapper/Schedule/ClientStatement.php +++ b/app/DataMapper/Schedule/ClientStatement.php @@ -11,15 +11,11 @@ namespace App\DataMapper\Schedule; -use App\Models\Client; -use stdClass; - class ClientStatement { - /** * Defines the template name - * + * * @var string */ public string $template = 'client_statement'; @@ -28,7 +24,7 @@ class ClientStatement * An array of clients hashed_ids * * Leave blank if this action should apply to all clients - * + * * @var array */ public array $clients = []; @@ -46,7 +42,7 @@ class ClientStatement /** * The date range the statement should include - * + * * @var string */ public string $date_range = 'this_month'; @@ -54,7 +50,7 @@ class ClientStatement /** * If a custom range is select for the date range then * the start_date should be supplied in Y-m-d format - * + * * @var string */ public string $start_date = ''; @@ -62,7 +58,7 @@ class ClientStatement /** * If a custom range is select for the date range then * the end_date should be supplied in Y-m-d format - * + * * @var string */ public string $end_date = ''; @@ -87,10 +83,8 @@ class ClientStatement * String const which defines whether * the invoices to be shown are either * paid or unpaid - * + * * @var string */ public string $status = 'paid'; // paid | unpaid - - -} \ No newline at end of file +} diff --git a/app/DataMapper/Transactions/ClientStatusTransaction.php b/app/DataMapper/Transactions/ClientStatusTransaction.php index 5c3810ef3e1b..5fd661f0462e 100644 --- a/app/DataMapper/Transactions/ClientStatusTransaction.php +++ b/app/DataMapper/Transactions/ClientStatusTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php b/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php index cda3680e1e4d..7a69030dce1b 100644 --- a/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php +++ b/app/DataMapper/Transactions/GatewayPaymentMadeTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/InvoiceCancelledTransaction.php b/app/DataMapper/Transactions/InvoiceCancelledTransaction.php index 63952a11383b..d6f5b50de096 100644 --- a/app/DataMapper/Transactions/InvoiceCancelledTransaction.php +++ b/app/DataMapper/Transactions/InvoiceCancelledTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/InvoiceDeletedTransaction.php b/app/DataMapper/Transactions/InvoiceDeletedTransaction.php index be9dfc2a69df..503883bebab8 100644 --- a/app/DataMapper/Transactions/InvoiceDeletedTransaction.php +++ b/app/DataMapper/Transactions/InvoiceDeletedTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php b/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php index 24621e21b7e3..2a02beed93b5 100644 --- a/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php +++ b/app/DataMapper/Transactions/InvoiceFeeAppliedTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/InvoicePaymentTransaction.php b/app/DataMapper/Transactions/InvoicePaymentTransaction.php index 46f89c1ad5d8..10c22d1630f5 100644 --- a/app/DataMapper/Transactions/InvoicePaymentTransaction.php +++ b/app/DataMapper/Transactions/InvoicePaymentTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/InvoiceReversalTransaction.php b/app/DataMapper/Transactions/InvoiceReversalTransaction.php index fb32c72f3e53..9e514a3717fb 100644 --- a/app/DataMapper/Transactions/InvoiceReversalTransaction.php +++ b/app/DataMapper/Transactions/InvoiceReversalTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php b/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php index efbb0798c762..48a27f5ba6de 100644 --- a/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php +++ b/app/DataMapper/Transactions/InvoiceUpdatedTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/MarkPaidTransaction.php b/app/DataMapper/Transactions/MarkPaidTransaction.php index eca93175d54f..d099c0b05f1d 100644 --- a/app/DataMapper/Transactions/MarkPaidTransaction.php +++ b/app/DataMapper/Transactions/MarkPaidTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/PaymentAppliedTransaction.php b/app/DataMapper/Transactions/PaymentAppliedTransaction.php index 1291d97f8ce7..41f114f0b7c0 100644 --- a/app/DataMapper/Transactions/PaymentAppliedTransaction.php +++ b/app/DataMapper/Transactions/PaymentAppliedTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/PaymentDeletedTransaction.php b/app/DataMapper/Transactions/PaymentDeletedTransaction.php index c0f1b6964653..575bcbc0a66f 100644 --- a/app/DataMapper/Transactions/PaymentDeletedTransaction.php +++ b/app/DataMapper/Transactions/PaymentDeletedTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/PaymentFailedTransaction.php b/app/DataMapper/Transactions/PaymentFailedTransaction.php index 5152ad703187..f7ee79e5e695 100644 --- a/app/DataMapper/Transactions/PaymentFailedTransaction.php +++ b/app/DataMapper/Transactions/PaymentFailedTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/PaymentMadeTransaction.php b/app/DataMapper/Transactions/PaymentMadeTransaction.php index 3b7adf51d301..1c9688e3304d 100644 --- a/app/DataMapper/Transactions/PaymentMadeTransaction.php +++ b/app/DataMapper/Transactions/PaymentMadeTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/DataMapper/Transactions/PaymentRefundedTransaction.php b/app/DataMapper/Transactions/PaymentRefundedTransaction.php index 2b31a45f9300..83788d6f3fc8 100644 --- a/app/DataMapper/Transactions/PaymentRefundedTransaction.php +++ b/app/DataMapper/Transactions/PaymentRefundedTransaction.php @@ -11,10 +11,6 @@ namespace App\DataMapper\Transactions; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Models\TransactionEvent; /** diff --git a/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php b/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php index 77f71e960426..004ca3830aa1 100644 --- a/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php +++ b/app/Events/PurchaseOrder/PurchaseOrderWasAccepted.php @@ -13,7 +13,6 @@ namespace App\Events\PurchaseOrder; use App\Models\Company; use App\Models\PurchaseOrder; -use App\Models\PurchaseOrderInvitation; use App\Models\VendorContact; use Illuminate\Queue\SerializesModels; diff --git a/app/Events/Subscription/SubscriptionWasCreated.php b/app/Events/Subscription/SubscriptionWasCreated.php index 1da537bbbf1f..1aef2036b4ed 100644 --- a/app/Events/Subscription/SubscriptionWasCreated.php +++ b/app/Events/Subscription/SubscriptionWasCreated.php @@ -4,11 +4,8 @@ namespace App\Events\Subscription; use App\Models\Company; use App\Models\Subscription; -use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; -use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Broadcasting\PrivateChannel; -use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index a7d534780cec..9e258dbb19f2 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -11,10 +11,6 @@ namespace App\Exceptions; -use App\Exceptions\FilePermissionsFailure; -use App\Exceptions\InternalPDFFailure; -use App\Exceptions\PhantomPDFFailure; -use App\Exceptions\StripeConnectFailure; use App\Utils\Ninja; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\AuthenticationException; @@ -29,13 +25,13 @@ use Illuminate\Session\TokenMismatchException; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Schema; use Illuminate\Validation\ValidationException; +use League\Flysystem\UnableToCreateDirectory; use PDOException; use Sentry\Laravel\Integration; use Sentry\State\Scope; use Symfony\Component\Console\Exception\CommandNotFoundException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use League\Flysystem\UnableToCreateDirectory; use Throwable; class Handler extends ExceptionHandler @@ -127,7 +123,6 @@ class Handler extends ExceptionHandler if ($this->validException($exception) && $this->sentryShouldReport($exception)) { Integration::captureUnhandledException($exception); } - } elseif (app()->bound('sentry')) { Integration::configureScope(function (Scope $scope): void { if (auth()->guard('contact') && auth()->guard('contact')->user() && auth()->guard('contact')->user()->company->account->report_errors) { @@ -191,10 +186,11 @@ class Handler extends ExceptionHandler */ protected function sentryShouldReport(Throwable $e) { - if(Ninja::isHosted()) + if (Ninja::isHosted()) { $dontReport = array_merge($this->hostedDontReport, $this->internalDontReport); - else + } else { $dontReport = array_merge($this->selfHostDontReport, $this->internalDontReport); + } return is_null(Arr::first($dontReport, fn ($type) => $e instanceof $type)); } @@ -244,7 +240,7 @@ class Handler extends ExceptionHandler return response()->json(['message' => $exception->getMessage()], 400); } elseif ($exception instanceof StripeConnectFailure) { return response()->json(['message' => $exception->getMessage()], 400); - } + } return parent::render($request, $exception); } @@ -258,7 +254,7 @@ class Handler extends ExceptionHandler $guard = Arr::get($exception->guards(), 0); switch ($guard) { - case 'contact': + case 'contact': $login = 'client.login'; break; case 'user': diff --git a/app/Exceptions/PaymentFailed.php b/app/Exceptions/PaymentFailed.php index 9b2735edd08a..713dd54af13f 100644 --- a/app/Exceptions/PaymentFailed.php +++ b/app/Exceptions/PaymentFailed.php @@ -23,8 +23,7 @@ class PaymentFailed extends Exception public function render($request) { - if (auth()->guard('contact')->user() || ($request->has('cko-session-id') && $request->query('cko-session-id') )) { - + if (auth()->guard('contact')->user() || ($request->has('cko-session-id') && $request->query('cko-session-id'))) { return render('gateways.unsuccessful', [ 'message' => $this->getMessage(), 'code' => $this->getCode(), diff --git a/app/Exceptions/PaymentRefundFailed.php b/app/Exceptions/PaymentRefundFailed.php index bb273ba25973..4aa2c4487c66 100644 --- a/app/Exceptions/PaymentRefundFailed.php +++ b/app/Exceptions/PaymentRefundFailed.php @@ -36,7 +36,6 @@ class PaymentRefundFailed extends Exception */ public function render($request) { - // $msg = 'Unable to refund the transaction'; $msg = ctrans('texts.warning_local_refund'); diff --git a/app/Exceptions/YodleeApiException.php b/app/Exceptions/YodleeApiException.php index c8a2e224f135..177be9ae1834 100644 --- a/app/Exceptions/YodleeApiException.php +++ b/app/Exceptions/YodleeApiException.php @@ -36,7 +36,6 @@ class YodleeApiException extends Exception */ public function render($request) { - // $msg = 'Unable to refund the transaction'; $msg = ctrans('texts.error'); diff --git a/app/Export/CSV/BaseExport.php b/app/Export/CSV/BaseExport.php index ea562d76c47a..96990889b935 100644 --- a/app/Export/CSV/BaseExport.php +++ b/app/Export/CSV/BaseExport.php @@ -32,7 +32,6 @@ class BaseExport } switch ($date_range) { - case 'all': return $query; case 'last7': @@ -53,7 +52,6 @@ class BaseExport return $query->whereBetween($this->date_key, [$custom_start_date, $custom_end_date])->orderBy($this->date_key, 'ASC'); default: return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC'); - } } diff --git a/app/Export/CSV/ClientExport.php b/app/Export/CSV/ClientExport.php index e0504a6c340b..772c0152e7e5 100644 --- a/app/Export/CSV/ClientExport.php +++ b/app/Export/CSV/ClientExport.php @@ -17,7 +17,6 @@ use App\Models\Company; use App\Transformers\ClientContactTransformer; use App\Transformers\ClientTransformer; use App\Utils\Ninja; -use Illuminate\Support\Carbon; use Illuminate\Support\Facades\App; use League\Csv\Writer; @@ -181,11 +180,13 @@ class ClientExport extends BaseExport private function calculateStatus($client) { - if($client->is_deleted) + if ($client->is_deleted) { return ctrans('texts.deleted'); + } - if($client->deleted_at) + if ($client->deleted_at) { return ctrans('texts.arcvived'); + } return ctrans('texts.active'); } diff --git a/app/Export/CSV/CreditExport.php b/app/Export/CSV/CreditExport.php index 82dff6795a19..a612810863d3 100644 --- a/app/Export/CSV/CreditExport.php +++ b/app/Export/CSV/CreditExport.php @@ -12,7 +12,6 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; use App\Models\Credit; use App\Transformers\CreditTransformer; diff --git a/app/Export/CSV/DocumentExport.php b/app/Export/CSV/DocumentExport.php index c9167ef1561f..891a4499b227 100644 --- a/app/Export/CSV/DocumentExport.php +++ b/app/Export/CSV/DocumentExport.php @@ -12,9 +12,7 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; -use App\Models\Credit; use App\Models\Document; use App\Transformers\DocumentTransformer; use App\Utils\Ninja; diff --git a/app/Export/CSV/ExpenseExport.php b/app/Export/CSV/ExpenseExport.php index dced738d742c..de7e2dc19652 100644 --- a/app/Export/CSV/ExpenseExport.php +++ b/app/Export/CSV/ExpenseExport.php @@ -12,7 +12,6 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; use App\Models\Expense; use App\Transformers\ExpenseTransformer; diff --git a/app/Export/CSV/InvoiceExport.php b/app/Export/CSV/InvoiceExport.php index 492cb6d998a4..464ede3f1f05 100644 --- a/app/Export/CSV/InvoiceExport.php +++ b/app/Export/CSV/InvoiceExport.php @@ -12,7 +12,6 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; use App\Models\Invoice; use App\Transformers\InvoiceTransformer; diff --git a/app/Export/CSV/InvoiceItemExport.php b/app/Export/CSV/InvoiceItemExport.php index 7404a1714fb4..501b4e31a613 100644 --- a/app/Export/CSV/InvoiceItemExport.php +++ b/app/Export/CSV/InvoiceItemExport.php @@ -100,7 +100,6 @@ class InvoiceItemExport extends BaseExport public function run() { - MultiDB::setDb($this->company->db); App::forgetInstance('translator'); App::setLocale($this->company->locale()); @@ -110,8 +109,9 @@ class InvoiceItemExport extends BaseExport //load the CSV document from a string $this->csv = Writer::createFromString(); - if(count($this->input['report_keys']) == 0) + if (count($this->input['report_keys']) == 0) { $this->input['report_keys'] = array_values($this->entity_keys); + } //insert the header $this->csv->insertOne($this->buildHeader()); @@ -119,19 +119,16 @@ class InvoiceItemExport extends BaseExport $query = Invoice::query() ->withTrashed() ->with('client')->where('company_id', $this->company->id) - ->where('is_deleted',0); + ->where('is_deleted', 0); $query = $this->addDateRange($query); $query->cursor() - ->each(function ($invoice){ - + ->each(function ($invoice) { $this->iterateItems($invoice); + }); - }); - - return $this->csv->toString(); - + return $this->csv->toString(); } private function iterateItems(Invoice $invoice) @@ -140,81 +137,71 @@ class InvoiceItemExport extends BaseExport $transformed_items = []; - foreach($invoice->line_items as $item) - { + foreach ($invoice->line_items as $item) { $item_array = []; - foreach(array_values($this->input['report_keys']) as $key){ - - if(str_contains($key, "item.")){ - + foreach (array_values($this->input['report_keys']) as $key) { + if (str_contains($key, "item.")) { $key = str_replace("item.", "", $key); - if(property_exists($item, $key)) + if (property_exists($item, $key)) { $item_array[$key] = $item->{$key}; - else + } else { $item_array[$key] = ''; - + } } - } $entity = []; - foreach(array_values($this->input['report_keys']) as $key) - { + foreach (array_values($this->input['report_keys']) as $key) { $keyval = array_search($key, $this->entity_keys); - if(array_key_exists($key, $transformed_items)) + if (array_key_exists($key, $transformed_items)) { $entity[$keyval] = $transformed_items[$key]; - else + } else { $entity[$keyval] = ""; - + } } $transformed_items = array_merge($transformed_invoice, $item_array); $entity = $this->decorateAdvancedFields($invoice, $transformed_items); - $this->csv->insertOne($entity); - + $this->csv->insertOne($entity); } - } private function buildRow(Invoice $invoice) :array { - $transformed_invoice = $this->invoice_transformer->transform($invoice); $entity = []; - foreach(array_values($this->input['report_keys']) as $key){ - + foreach (array_values($this->input['report_keys']) as $key) { $keyval = array_search($key, $this->entity_keys); - if(array_key_exists($key, $transformed_invoice)) + if (array_key_exists($key, $transformed_invoice)) { $entity[$keyval] = $transformed_invoice[$key]; - else + } else { $entity[$keyval] = ""; - + } } return $this->decorateAdvancedFields($invoice, $entity); - } private function decorateAdvancedFields(Invoice $invoice, array $entity) :array { - if(in_array('currency_id', $this->input['report_keys'])) + if (in_array('currency_id', $this->input['report_keys'])) { $entity['currency'] = $invoice->client->currency() ? $invoice->client->currency()->code : $invoice->company->currency()->code; + } // if(in_array('client_id', $this->input['report_keys'])) - $entity['client'] = $invoice->client->present()->name(); + $entity['client'] = $invoice->client->present()->name(); // if(in_array('status_id', $this->input['report_keys'])) - $entity['status'] = $invoice->stringStatus($invoice->status_id); + $entity['status'] = $invoice->stringStatus($invoice->status_id); return $entity; } - } diff --git a/app/Export/CSV/PaymentExport.php b/app/Export/CSV/PaymentExport.php index 878db42df229..22e838e4164d 100644 --- a/app/Export/CSV/PaymentExport.php +++ b/app/Export/CSV/PaymentExport.php @@ -12,9 +12,7 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; -use App\Models\Credit; use App\Models\Document; use App\Models\Payment; use App\Transformers\PaymentTransformer; diff --git a/app/Export/CSV/ProductExport.php b/app/Export/CSV/ProductExport.php index ba3afc73dcce..a210df2260a3 100644 --- a/app/Export/CSV/ProductExport.php +++ b/app/Export/CSV/ProductExport.php @@ -12,9 +12,7 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; -use App\Models\Credit; use App\Models\Document; use App\Models\Product; use App\Transformers\ProductTransformer; diff --git a/app/Export/CSV/ProductSalesExport.php b/app/Export/CSV/ProductSalesExport.php index 1fdfb7362872..505d0b72ba61 100644 --- a/app/Export/CSV/ProductSalesExport.php +++ b/app/Export/CSV/ProductSalesExport.php @@ -12,17 +12,13 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; -use App\Models\Credit; use App\Models\Document; use App\Models\Invoice; -use App\Models\Product; -use App\Transformers\ProductTransformer; use App\Utils\Ninja; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\App; use League\Csv\Writer; -use Illuminate\Support\Carbon; class ProductSalesExport extends BaseExport { @@ -98,10 +94,9 @@ class ProductSalesExport extends BaseExport $query->cursor() ->each(function ($invoice) { - - foreach($invoice->line_items as $item) - $this->csv->insertOne($this->buildRow($invoice, $item)); - + foreach ($invoice->line_items as $item) { + $this->csv->insertOne($this->buildRow($invoice, $item)); + } }); return $this->csv->toString(); diff --git a/app/Export/CSV/QuoteExport.php b/app/Export/CSV/QuoteExport.php index 482b9d685d17..72bee3d23515 100644 --- a/app/Export/CSV/QuoteExport.php +++ b/app/Export/CSV/QuoteExport.php @@ -12,7 +12,6 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; use App\Models\Quote; use App\Transformers\QuoteTransformer; diff --git a/app/Export/CSV/QuoteItemExport.php b/app/Export/CSV/QuoteItemExport.php index 6e4ea48bcdf3..e8baeecedcd0 100644 --- a/app/Export/CSV/QuoteItemExport.php +++ b/app/Export/CSV/QuoteItemExport.php @@ -12,7 +12,6 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; use App\Models\Quote; use App\Transformers\QuoteTransformer; diff --git a/app/Export/CSV/RecurringInvoiceExport.php b/app/Export/CSV/RecurringInvoiceExport.php index 7fe5664c34d1..aaf4565caceb 100644 --- a/app/Export/CSV/RecurringInvoiceExport.php +++ b/app/Export/CSV/RecurringInvoiceExport.php @@ -12,7 +12,6 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; use App\Models\RecurringInvoice; use App\Transformers\RecurringInvoiceTransformer; diff --git a/app/Export/CSV/TaskExport.php b/app/Export/CSV/TaskExport.php index b91445687ea8..095fcd498537 100644 --- a/app/Export/CSV/TaskExport.php +++ b/app/Export/CSV/TaskExport.php @@ -12,7 +12,6 @@ namespace App\Export\CSV; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; use App\Models\DateFormat; use App\Models\Task; diff --git a/app/Factory/BankIntegrationFactory.php b/app/Factory/BankIntegrationFactory.php index a4918feccd5e..e49934c5a6dd 100644 --- a/app/Factory/BankIntegrationFactory.php +++ b/app/Factory/BankIntegrationFactory.php @@ -12,7 +12,6 @@ namespace App\Factory; use App\Models\BankIntegration; -use Illuminate\Support\Str; class BankIntegrationFactory { diff --git a/app/Factory/BankTransactionFactory.php b/app/Factory/BankTransactionFactory.php index 8355a83a24cd..3760d1bc40f7 100644 --- a/app/Factory/BankTransactionFactory.php +++ b/app/Factory/BankTransactionFactory.php @@ -12,7 +12,6 @@ namespace App\Factory; use App\Models\BankTransaction; -use Illuminate\Support\Str; class BankTransactionFactory { diff --git a/app/Factory/BankTransactionRuleFactory.php b/app/Factory/BankTransactionRuleFactory.php index 360ee32e1ab3..7bb2199b4d97 100644 --- a/app/Factory/BankTransactionRuleFactory.php +++ b/app/Factory/BankTransactionRuleFactory.php @@ -12,7 +12,6 @@ namespace App\Factory; use App\Models\BankTransactionRule; -use Illuminate\Support\Str; class BankTransactionRuleFactory { diff --git a/app/Factory/ClientGatewayTokenFactory.php b/app/Factory/ClientGatewayTokenFactory.php index 2fdd96ca5d60..be343a280737 100644 --- a/app/Factory/ClientGatewayTokenFactory.php +++ b/app/Factory/ClientGatewayTokenFactory.php @@ -12,7 +12,6 @@ namespace App\Factory; use App\Models\ClientGatewayToken; -use Illuminate\Support\Str; class ClientGatewayTokenFactory { diff --git a/app/Factory/CompanyGatewayFactory.php b/app/Factory/CompanyGatewayFactory.php index 8046399aff67..952054ed4383 100644 --- a/app/Factory/CompanyGatewayFactory.php +++ b/app/Factory/CompanyGatewayFactory.php @@ -11,7 +11,6 @@ namespace App\Factory; -use App\DataMapper\FeesAndLimits; use App\Models\CompanyGateway; class CompanyGatewayFactory diff --git a/app/Factory/PurchaseOrderFactory.php b/app/Factory/PurchaseOrderFactory.php index df5908486215..31a082ac83b7 100644 --- a/app/Factory/PurchaseOrderFactory.php +++ b/app/Factory/PurchaseOrderFactory.php @@ -13,7 +13,6 @@ namespace App\Factory; use App\Models\Client; use App\Models\PurchaseOrder; -use Illuminate\Database\Eloquent\Model; class PurchaseOrderFactory { diff --git a/app/Factory/PurchaseOrderInvitationFactory.php b/app/Factory/PurchaseOrderInvitationFactory.php index 8d354d244c8e..59371726cc53 100644 --- a/app/Factory/PurchaseOrderInvitationFactory.php +++ b/app/Factory/PurchaseOrderInvitationFactory.php @@ -3,7 +3,6 @@ namespace App\Factory; use App\Models\PurchaseOrderInvitation; -use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class PurchaseOrderInvitationFactory diff --git a/app/Factory/RecurringExpenseToExpenseFactory.php b/app/Factory/RecurringExpenseToExpenseFactory.php index eb527dfc5795..1fc9626aa72e 100644 --- a/app/Factory/RecurringExpenseToExpenseFactory.php +++ b/app/Factory/RecurringExpenseToExpenseFactory.php @@ -13,7 +13,6 @@ namespace App\Factory; use App\Models\Expense; use App\Models\RecurringExpense; -use App\Utils\Helpers; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; @@ -175,7 +174,10 @@ class RecurringExpenseToExpenseFactory $replacement = sprintf('%s to %s', $_left, $_right); $value = preg_replace( - sprintf('/%s/', preg_quote($match)), $replacement, $value, 1 + sprintf('/%s/', preg_quote($match)), + $replacement, + $value, + 1 ); } } @@ -196,7 +198,10 @@ class RecurringExpenseToExpenseFactory if (! Str::contains($match, ['-', '+', '/', '*'])) { $value = preg_replace( - sprintf('/%s/', $matches->keys()->first()), $replacements['literal'][$matches->keys()->first()], $value, 1 + sprintf('/%s/', $matches->keys()->first()), + $replacements['literal'][$matches->keys()->first()], + $value, + 1 ); } @@ -236,7 +241,10 @@ class RecurringExpenseToExpenseFactory } $value = preg_replace( - $target, $output, $value, 1 + $target, + $output, + $value, + 1 ); } } diff --git a/app/Factory/UserFactory.php b/app/Factory/UserFactory.php index 593cc98b2af0..d31a0019b2c9 100644 --- a/app/Factory/UserFactory.php +++ b/app/Factory/UserFactory.php @@ -11,7 +11,6 @@ namespace App\Factory; -use App\Models\CompanyUser; use App\Models\User; class UserFactory diff --git a/app/Filters/BankIntegrationFilters.php b/app/Filters/BankIntegrationFilters.php index 1932b0995dba..c1340b6f2651 100644 --- a/app/Filters/BankIntegrationFilters.php +++ b/app/Filters/BankIntegrationFilters.php @@ -49,7 +49,6 @@ class BankIntegrationFilters extends QueryFilters return $this->builder->where(function ($query) use ($filter) { $query->where('bank_account_name', 'like', '%'.$filter.'%'); }); - } /** @@ -68,7 +67,6 @@ class BankIntegrationFilters extends QueryFilters $filters = explode(',', $filter); return $this->builder->where(function ($query) use ($filters) { - if (in_array(parent::STATUS_ACTIVE, $filters)) { $query->orWhereNull('deleted_at'); } diff --git a/app/Filters/BankTransactionFilters.php b/app/Filters/BankTransactionFilters.php index 4830277be8aa..a1aab569020c 100644 --- a/app/Filters/BankTransactionFilters.php +++ b/app/Filters/BankTransactionFilters.php @@ -50,7 +50,6 @@ class BankTransactionFilters extends QueryFilters return $this->builder->where(function ($query) use ($filter) { $query->where('bank_transactions.description', 'like', '%'.$filter.'%'); }); - } @@ -79,8 +78,7 @@ class BankTransactionFilters extends QueryFilters return $this->builder; } - $this->builder->where(function ($query) use ($status_parameters){ - + $this->builder->where(function ($query) use ($status_parameters) { $status_array = []; $debit_or_withdrawal_array = []; @@ -105,14 +103,13 @@ class BankTransactionFilters extends QueryFilters $debit_or_withdrawal_array[] = 'DEBIT'; } - if(count($status_array) >=1) { + if (count($status_array) >=1) { $query->whereIn('status_id', $status_array); } - if(count($debit_or_withdrawal_array) >=1) { + if (count($debit_or_withdrawal_array) >=1) { $query->orWhereIn('base_type', $debit_or_withdrawal_array); } - }); return $this->builder; @@ -132,17 +129,21 @@ class BankTransactionFilters extends QueryFilters return $this->builder; } - if($sort_col[0] == 'deposit') + if ($sort_col[0] == 'deposit') { return $this->builder->where('base_type', 'CREDIT')->orderBy('amount', $sort_col[1]); + } - if($sort_col[0] == 'withdrawal') + if ($sort_col[0] == 'withdrawal') { return $this->builder->where('base_type', 'DEBIT')->orderBy('amount', $sort_col[1]); + } - if($sort_col[0] == 'status') + if ($sort_col[0] == 'status') { $sort_col[0] = 'status_id'; + } - if(in_array($sort_col[0],['invoices','expense'])) + if (in_array($sort_col[0], ['invoices','expense'])) { return $this->builder; + } return $this->builder->orderBy($sort_col[0], $sort_col[1]); } diff --git a/app/Filters/BankTransactionRuleFilters.php b/app/Filters/BankTransactionRuleFilters.php index be79cb58fe4a..ee8496f579b5 100644 --- a/app/Filters/BankTransactionRuleFilters.php +++ b/app/Filters/BankTransactionRuleFilters.php @@ -49,7 +49,6 @@ class BankTransactionRuleFilters extends QueryFilters return $this->builder->where(function ($query) use ($filter) { $query->where('bank_transaction_rules.name', 'like', '%'.$filter.'%'); }); - } /** diff --git a/app/Filters/ClientFilters.php b/app/Filters/ClientFilters.php index 0c3b86bec946..c2b23f0ad28f 100644 --- a/app/Filters/ClientFilters.php +++ b/app/Filters/ClientFilters.php @@ -147,8 +147,9 @@ class ClientFilters extends QueryFilters return $this->builder; } - if($sort_col[0] == 'display_name') + if ($sort_col[0] == 'display_name') { $sort_col[0] = 'name'; + } return $this->builder->orderBy($sort_col[0], $sort_col[1]); } @@ -165,11 +166,10 @@ class ClientFilters extends QueryFilters public function filter_details(string $filter = '') { - - if($filter == 'true') + if ($filter == 'true') { return $this->builder->select('id', 'name', 'number', 'id_number'); + } return $this->builder; - } } diff --git a/app/Filters/CreditFilters.php b/app/Filters/CreditFilters.php index b95e18b1433f..7fa39b281c21 100644 --- a/app/Filters/CreditFilters.php +++ b/app/Filters/CreditFilters.php @@ -44,17 +44,21 @@ class CreditFilters extends QueryFilters $credit_filters = []; - if (in_array('draft', $status_parameters)) + if (in_array('draft', $status_parameters)) { $credit_filters[] = Credit::STATUS_DRAFT; + } - if (in_array('partial', $status_parameters)) + if (in_array('partial', $status_parameters)) { $credit_filters[] = Credit::STATUS_PARTIAL; + } - if (in_array('applied', $status_parameters)) + if (in_array('applied', $status_parameters)) { $credit_filters[] = Credit::STATUS_APPLIED; + } - if(count($credit_filters) >=1) + if (count($credit_filters) >=1) { $this->builder->whereIn('status_id', $credit_filters); + } return $this->builder; } diff --git a/app/Filters/DesignFilters.php b/app/Filters/DesignFilters.php index e19707ff062d..d44cc2995147 100644 --- a/app/Filters/DesignFilters.php +++ b/app/Filters/DesignFilters.php @@ -23,7 +23,7 @@ class DesignFilters extends QueryFilters * * @param string query filter * @return Builder - * + * * @deprecated */ public function filter(string $filter = ''): Builder @@ -41,7 +41,7 @@ class DesignFilters extends QueryFilters * Sorts the list based on $sort. * * @param string sort formatted as column|asc - * + * * @return Builder */ public function sort(string $sort = ''): Builder @@ -62,6 +62,6 @@ class DesignFilters extends QueryFilters */ public function entityFilter(): Builder { - return $this->builder->where('company_id', auth()->user()->company()->id)->orWhere('company_id', null)->orderBy('id','asc'); + return $this->builder->where('company_id', auth()->user()->company()->id)->orWhere('company_id', null)->orderBy('id', 'asc'); } } diff --git a/app/Filters/DocumentFilters.php b/app/Filters/DocumentFilters.php index 0391c10aff0f..1b312161ab84 100644 --- a/app/Filters/DocumentFilters.php +++ b/app/Filters/DocumentFilters.php @@ -39,10 +39,10 @@ class DocumentFilters extends QueryFilters * Overriding method as client_id does * not exist on this model, just pass * back the builder - * + * * @param string $client_id The client hashed id. - * - * @return Builder + * + * @return Builder */ public function client_id(string $client_id = ''): Builder { @@ -69,8 +69,9 @@ class DocumentFilters extends QueryFilters public function company_documents($value = 'false') { - if($value == 'true') + if ($value == 'true') { return $this->builder->where('documentable_type', Company::class); + } return $this->builder; } diff --git a/app/Filters/ExpenseCategoryFilters.php b/app/Filters/ExpenseCategoryFilters.php index 3ed24beac66a..b25ad4d282e9 100644 --- a/app/Filters/ExpenseCategoryFilters.php +++ b/app/Filters/ExpenseCategoryFilters.php @@ -32,7 +32,6 @@ class ExpenseCategoryFilters extends QueryFilters } return $this->builder->where('name', 'like', '%'.$filter.'%'); - } /** @@ -49,8 +48,9 @@ class ExpenseCategoryFilters extends QueryFilters return $this->builder; } - if (is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['name'])) + if (is_array($sort_col) && in_array($sort_col[1], ['asc', 'desc']) && in_array($sort_col[0], ['name'])) { return $this->builder->orderBy($sort_col[0], $sort_col[1]); + } return $this->builder; diff --git a/app/Filters/ExpenseFilters.php b/app/Filters/ExpenseFilters.php index e04cc216e93d..0ff6e69035a8 100644 --- a/app/Filters/ExpenseFilters.php +++ b/app/Filters/ExpenseFilters.php @@ -65,52 +65,40 @@ class ExpenseFilters extends QueryFilters return $this->builder; } - $this->builder->where(function ($query) use($status_parameters){ - + $this->builder->where(function ($query) use ($status_parameters) { if (in_array('logged', $status_parameters)) { - - $query->orWhere(function ($query){ + $query->orWhere(function ($query) { $query->where('amount', '>', 0) ->whereNull('invoice_id') ->whereNull('payment_date') - ->where('should_be_invoiced',false); + ->where('should_be_invoiced', false); }); - } if (in_array('pending', $status_parameters)) { - - $query->orWhere(function ($query){ - $query->where('should_be_invoiced',true) + $query->orWhere(function ($query) { + $query->where('should_be_invoiced', true) ->whereNull('invoice_id'); }); - } if (in_array('invoiced', $status_parameters)) { - - $query->orWhere(function ($query){ + $query->orWhere(function ($query) { $query->whereNotNull('invoice_id'); }); - } if (in_array('paid', $status_parameters)) { - - $query->orWhere(function ($query){ + $query->orWhere(function ($query) { $query->whereNotNull('payment_date'); }); - } if (in_array('unpaid', $status_parameters)) { - - $query->orWhere(function ($query){ + $query->orWhere(function ($query) { $query->whereNull('payment_date'); }); - } - }); // nlog($this->builder->toSql()); @@ -123,10 +111,8 @@ class ExpenseFilters extends QueryFilters */ public function match_transactions($value = '') { - - if($value == 'true') - { - return $this->builder->where('is_deleted',0)->whereNull('transaction_id'); + if ($value == 'true') { + return $this->builder->where('is_deleted', 0)->whereNull('transaction_id'); } return $this->builder; diff --git a/app/Filters/InvoiceFilters.php b/app/Filters/InvoiceFilters.php index 55d2d2097fcb..6ae3da8e6f66 100644 --- a/app/Filters/InvoiceFilters.php +++ b/app/Filters/InvoiceFilters.php @@ -50,8 +50,7 @@ class InvoiceFilters extends QueryFilters return $this->builder; } - $this->builder->where(function ($query) use($status_parameters){ - + $this->builder->where(function ($query) use ($status_parameters) { $invoice_filters = []; if (in_array('paid', $status_parameters)) { @@ -63,7 +62,7 @@ class InvoiceFilters extends QueryFilters $invoice_filters[] = Invoice::STATUS_PARTIAL; } - if(count($invoice_filters) >0){ + if (count($invoice_filters) >0) { $query->whereIn('status_id', $invoice_filters); } @@ -79,8 +78,9 @@ class InvoiceFilters extends QueryFilters public function number(string $number = ''): Builder { - if(strlen($number) == 0) + if (strlen($number) == 0) { return $this->builder; + } return $this->builder->where('number', $number); } @@ -112,20 +112,19 @@ class InvoiceFilters extends QueryFilters } /** - * @return Builder - * @throws RuntimeException + * @return Builder + * @throws RuntimeException */ public function without_deleted_clients(): Builder { - return $this->builder->whereHas('client', function ($query) { - $query->where('is_deleted',0); - }); + $query->where('is_deleted', 0); + }); } /** - * @return Builder - * @throws InvalidArgumentException + * @return Builder + * @throws InvalidArgumentException */ public function upcoming(): Builder { @@ -138,8 +137,8 @@ class InvoiceFilters extends QueryFilters } /** - * @return void - * @throws InvalidArgumentException + * @return void + * @throws InvalidArgumentException */ public function overdue(): Builder { @@ -153,9 +152,9 @@ class InvoiceFilters extends QueryFilters } /** - * @param string $client_id - * @return Builder - * @throws InvalidArgumentException + * @param string $client_id + * @return Builder + * @throws InvalidArgumentException */ public function payable(string $client_id = ''): Builder { @@ -198,15 +197,15 @@ class InvoiceFilters extends QueryFilters { if (auth()->guard('contact')->user()) { return $this->contactViewFilter(); - } else { + } else { return $this->builder->company()->with(['invitations.company'], ['documents.company']); } } /** - * @param string $filter - * @return Builder - * @throws InvalidArgumentException + * @param string $filter + * @return Builder + * @throws InvalidArgumentException */ public function private_notes($filter = '') :Builder { diff --git a/app/Filters/PaymentFilters.php b/app/Filters/PaymentFilters.php index f3c21072d1ef..c4ef5d9370a1 100644 --- a/app/Filters/PaymentFilters.php +++ b/app/Filters/PaymentFilters.php @@ -46,17 +46,14 @@ class PaymentFilters extends QueryFilters */ public function match_transactions($value = 'true'): Builder { - - if($value == 'true'){ - + if ($value == 'true') { return $this->builder - ->where('is_deleted',0) - ->where(function ($query){ + ->where('is_deleted', 0) + ->where(function ($query) { $query->whereNull('transaction_id') - ->orWhere("transaction_id","") + ->orWhere("transaction_id", "") ->company(); }); - } return $this->builder; diff --git a/app/Filters/ProjectFilters.php b/app/Filters/ProjectFilters.php index c1545464480d..bcb6d1f0a260 100644 --- a/app/Filters/ProjectFilters.php +++ b/app/Filters/ProjectFilters.php @@ -61,8 +61,9 @@ class ProjectFilters extends QueryFilters return $this->builder; } - if(is_array($sort_col)) + if (is_array($sort_col)) { return $this->builder->orderBy($sort_col[0], $sort_col[1]); + } } /** diff --git a/app/Filters/PurchaseOrderFilters.php b/app/Filters/PurchaseOrderFilters.php index 7fb0c759490c..a3ef1709c6f4 100644 --- a/app/Filters/PurchaseOrderFilters.php +++ b/app/Filters/PurchaseOrderFilters.php @@ -16,7 +16,6 @@ use Illuminate\Database\Eloquent\Builder; class PurchaseOrderFilters extends QueryFilters { - /** * Filter based on client status. * @@ -41,8 +40,7 @@ class PurchaseOrderFilters extends QueryFilters return $this->builder; } - $this->builder->where(function ($query) use ($status_parameters){ - + $this->builder->where(function ($query) use ($status_parameters) { $po_status = []; if (in_array('draft', $status_parameters)) { @@ -50,12 +48,11 @@ class PurchaseOrderFilters extends QueryFilters } if (in_array('sent', $status_parameters)) { - $query->orWhere(function ($q){ - $q->where('status_id', PurchaseOrder::STATUS_SENT) - ->whereNull('due_date') - ->orWhere('due_date', '>=', now()->toDateString()); - }); - + $query->orWhere(function ($q) { + $q->where('status_id', PurchaseOrder::STATUS_SENT) + ->whereNull('due_date') + ->orWhere('due_date', '>=', now()->toDateString()); + }); } if (in_array('accepted', $status_parameters)) { @@ -66,7 +63,7 @@ class PurchaseOrderFilters extends QueryFilters $po_status[] = PurchaseOrder::STATUS_CANCELLED; } - if(count($status_parameters) >=1) { + if (count($status_parameters) >=1) { $query->whereIn('status_id', $status_parameters); } }); diff --git a/app/Filters/QueryFilters.php b/app/Filters/QueryFilters.php index db25717050b0..a9924bca1225 100644 --- a/app/Filters/QueryFilters.php +++ b/app/Filters/QueryFilters.php @@ -55,7 +55,7 @@ abstract class QueryFilters /** * The "with" filter property column. - * + * * var string */ protected $with_property = 'id'; @@ -151,7 +151,7 @@ abstract class QueryFilters if (in_array(self::STATUS_ARCHIVED, $filters)) { $query->orWhere(function ($query) { - $query->whereNotNull('deleted_at')->where('is_deleted',0); + $query->whereNotNull('deleted_at')->where('is_deleted', 0); }); } @@ -188,7 +188,6 @@ abstract class QueryFilters default: return '='; break; - } } @@ -208,38 +207,30 @@ abstract class QueryFilters public function created_at($value = '') { - - if($value == '') + if ($value == '') { return $this->builder; + } - try{ - - if(is_numeric($value)){ + try { + if (is_numeric($value)) { $created_at = Carbon::createFromTimestamp((int)$value); - } - else{ + } else { $created_at = Carbon::parse($value); } return $this->builder->where('created_at', '>=', $created_at); - - } - catch(\Exception $e) { - + } catch(\Exception $e) { return $this->builder; - } - } public function updated_at($value = '') { - - if ($value == '') + if ($value == '') { return $this->builder; + } try { - if (is_numeric($value)) { $created_at = Carbon::createFromTimestamp((int)$value); } else { @@ -248,7 +239,6 @@ abstract class QueryFilters return $this->builder->where('updated_at', '>=', $created_at); } catch (\Exception $e) { - return $this->builder; } } diff --git a/app/Filters/QuoteFilters.php b/app/Filters/QuoteFilters.php index 23bb09ba8cb7..ca011386d944 100644 --- a/app/Filters/QuoteFilters.php +++ b/app/Filters/QuoteFilters.php @@ -65,14 +65,13 @@ class QuoteFilters extends QueryFilters return $this->builder; } - $this->builder->where(function ($query) use ($status_parameters){ - + $this->builder->where(function ($query) use ($status_parameters) { if (in_array('sent', $status_parameters)) { - $query->orWhere(function ($q){ - $q->where('status_id', Quote::STATUS_SENT) - ->whereNull('due_date') - ->orWhere('due_date', '>=', now()->toDateString()); - }); + $query->orWhere(function ($q) { + $q->where('status_id', Quote::STATUS_SENT) + ->whereNull('due_date') + ->orWhere('due_date', '>=', now()->toDateString()); + }); } $quote_filters = []; @@ -86,26 +85,25 @@ class QuoteFilters extends QueryFilters $quote_filters[] = Quote::STATUS_APPROVED; } - if(count($quote_filters) >0){ + if (count($quote_filters) >0) { $query->orWhereIn('status_id', $quote_filters); } if (in_array('expired', $status_parameters)) { - $query->orWhere(function ($q){ - $q->where('status_id', Quote::STATUS_SENT) - ->whereNotNull('due_date') - ->where('due_date', '<=', now()->toDateString()); - }); + $query->orWhere(function ($q) { + $q->where('status_id', Quote::STATUS_SENT) + ->whereNotNull('due_date') + ->where('due_date', '<=', now()->toDateString()); + }); } if (in_array('upcoming', $status_parameters)) { - $query->orWhere(function ($q){ - $q->where('status_id', Quote::STATUS_SENT) - ->where('due_date', '>=', now()->toDateString()) - ->orderBy('due_date', 'DESC'); - }); + $query->orWhere(function ($q) { + $q->where('status_id', Quote::STATUS_SENT) + ->where('due_date', '>=', now()->toDateString()) + ->orderBy('due_date', 'DESC'); + }); } - }); return $this->builder; @@ -134,8 +132,9 @@ class QuoteFilters extends QueryFilters return $this->builder; } - if($sort_col[0] == 'valid_until') + if ($sort_col[0] == 'valid_until') { $sort_col[0] = 'due_date'; + } return $this->builder->orderBy($sort_col[0], $sort_col[1]); } diff --git a/app/Filters/RecurringInvoiceFilters.php b/app/Filters/RecurringInvoiceFilters.php index 07884685e7fc..d9655b975b63 100644 --- a/app/Filters/RecurringInvoiceFilters.php +++ b/app/Filters/RecurringInvoiceFilters.php @@ -66,21 +66,24 @@ class RecurringInvoiceFilters extends QueryFilters $recurring_filters = []; - if (in_array('active', $status_parameters)) + if (in_array('active', $status_parameters)) { $recurring_filters[] = RecurringInvoice::STATUS_ACTIVE; + } - if (in_array('paused', $status_parameters)) + if (in_array('paused', $status_parameters)) { $recurring_filters[] = RecurringInvoice::STATUS_PAUSED; + } - if (in_array('completed', $status_parameters)) + if (in_array('completed', $status_parameters)) { $recurring_filters[] = RecurringInvoice::STATUS_COMPLETED; + } - if(count($recurring_filters) >= 1) + if (count($recurring_filters) >= 1) { return $this->builder->whereIn('status_id', $recurring_filters); + } return $this->builder; - } public function number(string $number = ''): Builder diff --git a/app/Filters/TaskFilters.php b/app/Filters/TaskFilters.php index 9e732fcf978d..7a2495f1d434 100644 --- a/app/Filters/TaskFilters.php +++ b/app/Filters/TaskFilters.php @@ -74,7 +74,6 @@ class TaskFilters extends QueryFilters public function project_tasks($project): Builder { - if (strlen($project) == 0) { return $this->builder; } diff --git a/app/Filters/UserFilters.php b/app/Filters/UserFilters.php index a53b2eded078..ec3c0a08fd9a 100644 --- a/app/Filters/UserFilters.php +++ b/app/Filters/UserFilters.php @@ -70,17 +70,16 @@ class UserFilters extends QueryFilters } /** - * Overrides the base with() function as no company ID + * Overrides the base with() function as no company ID * exists on the user table - * + * * @param string $value Hashed ID of the user to return back in the dataset - * + * * @return Builder */ public function with(string $value = ''): Builder { - - if(strlen($value) == 0) { + if (strlen($value) == 0) { return $this->builder; } @@ -89,5 +88,4 @@ class UserFilters extends QueryFilters ->orderByRaw("{$this->with_property} = ? DESC", [$value]) ->where('account_id', auth()->user()->account_id); } - } diff --git a/app/Helpers/Bank/AccountTransformerInterface.php b/app/Helpers/Bank/AccountTransformerInterface.php index 6155a3976deb..94c7bb816d0b 100644 --- a/app/Helpers/Bank/AccountTransformerInterface.php +++ b/app/Helpers/Bank/AccountTransformerInterface.php @@ -13,5 +13,5 @@ namespace App\Helpers\Bank; interface AccountTransformerInterface { - public function transform($accounts); + public function transform($accounts); } diff --git a/app/Helpers/Bank/BankExpenseInterface.php b/app/Helpers/Bank/BankExpenseInterface.php index ca441bcb04fc..5b23a9321f68 100644 --- a/app/Helpers/Bank/BankExpenseInterface.php +++ b/app/Helpers/Bank/BankExpenseInterface.php @@ -13,5 +13,4 @@ namespace App\Helpers\Bank; interface BankExpenseInterface { - } diff --git a/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php b/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php index e2b90656fb6f..84b50df7fabf 100644 --- a/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php +++ b/app/Helpers/Bank/Yodlee/Transformer/AccountTransformer.php @@ -12,7 +12,7 @@ namespace App\Helpers\Bank\Yodlee\Transformer; use App\Helpers\Bank\AccountTransformerInterface; - + /** [0] => stdClass Object ( @@ -33,7 +33,7 @@ use App\Helpers\Bank\AccountTransformerInterface; [includeInNetWorth] => 1 [providerId] => 18769 [providerName] => Dag Site Captcha - [isManual] => + [isManual] => [currentBalance] => stdClass Object ( [currency] => USD @@ -64,17 +64,15 @@ use App\Helpers\Bank\AccountTransformerInterface; class AccountTransformer implements AccountTransformerInterface { - public function transform($yodlee_account) { - $data = []; - if(!property_exists($yodlee_account, 'account')) + if (!property_exists($yodlee_account, 'account')) { return $data; + } - foreach($yodlee_account->account as $account) - { + foreach ($yodlee_account->account as $account) { $data[] = $this->transformAccount($account); } @@ -83,7 +81,6 @@ class AccountTransformer implements AccountTransformerInterface public function transformAccount($account) { - return [ 'id' => $account->id, 'account_type' => $account->CONTAINER, @@ -100,5 +97,3 @@ class AccountTransformer implements AccountTransformerInterface ]; } } - - diff --git a/app/Helpers/Bank/Yodlee/Transformer/ExpenseTransformer.php b/app/Helpers/Bank/Yodlee/Transformer/ExpenseTransformer.php index 6274bb2ed911..ced5d0a48f14 100644 --- a/app/Helpers/Bank/Yodlee/Transformer/ExpenseTransformer.php +++ b/app/Helpers/Bank/Yodlee/Transformer/ExpenseTransformer.php @@ -10,7 +10,7 @@ */ namespace App\Helpers\Bank\Yodlee\Transformer; - + /** "date": "string", "sourceId": "string", @@ -74,7 +74,4 @@ namespace App\Helpers\Bank\Yodlee\Transformer; class ExpenseTransformer { - } - - diff --git a/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php b/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php index 3ae26cbf7c9e..42c0e9bf5895 100644 --- a/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php +++ b/app/Helpers/Bank/Yodlee/Transformer/IncomeTransformer.php @@ -74,7 +74,7 @@ use Illuminate\Support\Facades\Cache; "holdingDescription": "string", "isin": "string", "status": "POSTED" - + ( [CONTAINER] => bank [id] => 103953585 @@ -96,7 +96,7 @@ use Illuminate\Support\Facades\Cache; [original] => CHEROKEE NATION TAX TA TAHLEQUAH OK ) -[isManual] => +[isManual] => [sourceType] => AGGREGATED [date] => 2022-08-03 [transactionDate] => 2022-08-03 @@ -119,17 +119,17 @@ class IncomeTransformer implements BankRevenueInterface public function transform($transaction) { - $data = []; - if(!property_exists($transaction, 'transaction')) + if (!property_exists($transaction, 'transaction')) { return $data; + } - foreach($transaction->transaction as $transaction) - { + foreach ($transaction->transaction as $transaction) { //do not store duplicate / pending transactions - if(property_exists($transaction,'status') && $transaction->status == 'PENDING') + if (property_exists($transaction, 'status') && $transaction->status == 'PENDING') { continue; + } $data[] = $this->transformTransaction($transaction); } @@ -139,7 +139,6 @@ class IncomeTransformer implements BankRevenueInterface public function transformTransaction($transaction) { - return [ 'transaction_id' => $transaction->id, 'amount' => $transaction->amount->amount, @@ -158,34 +157,29 @@ class IncomeTransformer implements BankRevenueInterface { //CREDIT / DEBIT - if(property_exists($transaction, 'highLevelCategoryId') && $transaction->highLevelCategoryId == 10000012) + if (property_exists($transaction, 'highLevelCategoryId') && $transaction->highLevelCategoryId == 10000012) { return 'CREDIT'; + } return 'DEBIT'; - } private function convertCurrency(string $code) { - $currencies = Cache::get('currencies'); if (! $currencies) { $this->buildCache(true); } - $currency = $currencies->filter(function ($item) use($code){ + $currency = $currencies->filter(function ($item) use ($code) { return $item->code == $code; })->first(); - if($currency) + if ($currency) { return $currency->id; + } return 1; - } - - } - - diff --git a/app/Helpers/Bank/Yodlee/Yodlee.php b/app/Helpers/Bank/Yodlee/Yodlee.php index 325f168ca504..709acd306c46 100644 --- a/app/Helpers/Bank/Yodlee/Yodlee.php +++ b/app/Helpers/Bank/Yodlee/Yodlee.php @@ -16,10 +16,9 @@ use App\Helpers\Bank\Yodlee\Transformer\AccountTransformer; use App\Helpers\Bank\Yodlee\Transformer\IncomeTransformer; use Illuminate\Support\Facades\Http; use Illuminate\Support\Str; - + class Yodlee { - public bool $test_mode = false; private string $api_endpoint = 'https://production.api.yodlee.com/ysl'; @@ -44,7 +43,6 @@ class Yodlee public function __construct(?string $bank_account_id = null) { - $this->bank_account_id = $bank_account_id; $this->client_id = config('ninja.yodlee.client_id'); @@ -56,13 +54,13 @@ class Yodlee $this->test_mode = config('ninja.yodlee.test_mode'); config('ninja.yodlee.dev_mode') ? $this->setDevUrl() : null; - } public function getFastTrackUrl() { - if(config('ninja.yodlee.dev_mode')) + if (config('ninja.yodlee.dev_mode')) { return $this->dev_fast_track_url; + } return $this->test_mode ? $this->test_fast_track_url : $this->production_track_url; } @@ -94,12 +92,13 @@ class Yodlee */ public function getAccessToken($is_admin = false) { - if($is_admin) + if ($is_admin) { $user = $this->admin_name; - else + } else { $user = $this->bank_account_id ?: $this->admin_name; + } - $response = $this->bankFormRequest('/auth/token', 'post', [], ['loginName' => $user]); + $response = $this->bankFormRequest('/auth/token', 'post', [], ['loginName' => $user]); return $response->token->accessToken; } @@ -107,103 +106,98 @@ class Yodlee public function createUser($company) { - $token = $this->getAccessToken(true); $user['user'] = [ 'loginName' => Str::uuid(), ]; -/* -{ - "user": { - "preferences": { - "dateFormat": "string", - "timeZone": "string", - "currency": "USD", - "locale": "en_US" - }, - "address": { - "zip": "string", - "country": "string", - "address3": "string", - "address2": "string", - "city": "string", - "address1": "string", - "state": "string" - }, - "loginName": "string", - "name": { - "middle": "string", - "last": "string", - "fullName": "string", - "first": "string" - }, - "email": "string", - "segmentName": "string" - } -} -*/ + /* + { + "user": { + "preferences": { + "dateFormat": "string", + "timeZone": "string", + "currency": "USD", + "locale": "en_US" + }, + "address": { + "zip": "string", + "country": "string", + "address3": "string", + "address2": "string", + "city": "string", + "address1": "string", + "state": "string" + }, + "loginName": "string", + "name": { + "middle": "string", + "last": "string", + "fullName": "string", + "first": "string" + }, + "email": "string", + "segmentName": "string" + } + } + */ $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->post($this->getEndpoint(). "/user/register", $user); - if($response->successful()) + if ($response->successful()) { return $response->object(); + } - if($response->failed()) + if ($response->failed()) { throw new YodleeApiException($response->body()); - + } } public function getAccounts($params = []) { - $token = $this->getAccessToken(); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/accounts", $params); - if($response->successful()){ - + if ($response->successful()) { $at = new AccountTransformer(); return $at->transform($response->object()); - } - if($response->failed()) + if ($response->failed()) { throw new YodleeApiException($response->body()); - + } } public function getAccount($account_id) { - $token = $this->getAccessToken(); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/accounts/{$account_id}", []); - if($response->successful()) + if ($response->successful()) { return true; + } - if($response->failed()) + if ($response->failed()) { return false; + } } public function deleteAccount($account_id) { - $token = $this->getAccessToken(); $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->delete($this->getEndpoint(). "/accounts/{$account_id}", []); - if($response->successful()){ - + if ($response->successful()) { return true; - } - if($response->failed()) + if ($response->failed()) { throw new YodleeApiException($response->body()); - + } } @@ -213,16 +207,15 @@ class Yodlee $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions", $params); - if($response->successful()){ + if ($response->successful()) { // return $response->object(); $it = new IncomeTransformer(); return $it->transform($response->object()); - } - if($response->failed()) + if ($response->failed()) { throw new YodleeApiException($response->body()); - + } } public function getTransactionCount($params = []) @@ -231,16 +224,14 @@ class Yodlee $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions/count", $params); - if($response->successful()){ - + if ($response->successful()) { return $response->object(); - } - if($response->failed()) + if ($response->failed()) { throw new YodleeApiException($response->body()); - - } + } + } public function getTransactionCategories($params = []) { @@ -248,25 +239,26 @@ class Yodlee $response = Http::withHeaders($this->getHeaders(["Authorization" => "Bearer {$token}"]))->get($this->getEndpoint(). "/transactions/categories", $params); - if($response->successful()) + if ($response->successful()) { return $response->object(); + } - if($response->failed()) + if ($response->failed()) { throw new YodleeApiException($response->body()); - + } } private function bankFormRequest(string $uri, string $verb, array $data, array $headers) { - $response = Http::withHeaders($this->getFormHeaders($headers))->asForm()->{$verb}($this->getEndpoint() . $uri, $this->buildBody()); - if($response->successful()) + if ($response->successful()) { return $response->object(); + } - if($response->failed()) + if ($response->failed()) { throw new YodleeApiException($response->body()); - + } } private function getHeaders($data = []) @@ -287,12 +279,9 @@ class Yodlee private function buildBody() { - return [ 'clientId' => $this->client_id, 'secret' => $this->client_secret, ]; - } - } diff --git a/app/Helpers/ClientPortal.php b/app/Helpers/ClientPortal.php index 0e5a2276ef40..25f7706344f0 100644 --- a/app/Helpers/ClientPortal.php +++ b/app/Helpers/ClientPortal.php @@ -26,7 +26,7 @@ function isActive($page, bool $boolean = false) $current_page = Route::currentRouteName(); $action = Route::currentRouteAction(); // string - $show = str_replace(['.show','payment_methodss','documentss','subscriptionss','paymentss'],['s.index','payment_methods','documents','subscriptions','payments'], $current_page); + $show = str_replace(['.show','payment_methodss','documentss','subscriptionss','paymentss'], ['s.index','payment_methods','documents','subscriptions','payments'], $current_page); if ($page == $current_page && $boolean) { return true; @@ -36,7 +36,7 @@ function isActive($page, bool $boolean = false) return 'bg-gray-200'; } - if(($page == $show) && $boolean){ + if (($page == $show) && $boolean) { return true; } diff --git a/app/Helpers/Epc/EpcQrGenerator.php b/app/Helpers/Epc/EpcQrGenerator.php index 1778f336d349..2da19d1da679 100644 --- a/app/Helpers/Epc/EpcQrGenerator.php +++ b/app/Helpers/Epc/EpcQrGenerator.php @@ -15,17 +15,16 @@ use App\Models\Company; use App\Models\Invoice; use App\Models\RecurringInvoice; use App\Utils\Ninja; -use BaconQrCode\Renderer\ImageRenderer; use BaconQrCode\Renderer\Image\SvgImageBackEnd; +use BaconQrCode\Renderer\ImageRenderer; use BaconQrCode\Renderer\RendererStyle\RendererStyle; use BaconQrCode\Writer; /** * EpcQrGenerator. */ -class EpcQrGenerator +class EpcQrGenerator { - private array $sepa = [ 'serviceTag' => 'BCD', 'version' => 2, @@ -36,11 +35,12 @@ class EpcQrGenerator ]; - public function __construct(protected Company $company, protected Invoice|RecurringInvoice $invoice, protected float $amount){} + public function __construct(protected Company $company, protected Invoice|RecurringInvoice $invoice, protected float $amount) + { + } public function getQrCode() { - $renderer = new ImageRenderer( new RendererStyle(200), new SvgImageBackEnd() @@ -51,22 +51,18 @@ class EpcQrGenerator try { $qr = $writer->writeString($this->encodeMessage(), 'utf-8'); - } - catch(\Throwable $e){ + } catch(\Throwable $e) { return ''; - } - catch(\Exception $e){ + } catch(\Exception $e) { return ''; } return " {$qr}"; - } public function encodeMessage() { - - return rtrim(implode("\n", array( + return rtrim(implode("\n", [ $this->sepa['serviceTag'], sprintf('%03d', $this->sepa['version']), $this->sepa['characterSet'], @@ -76,25 +72,25 @@ class EpcQrGenerator isset($this->company?->custom_fields?->company1) ? $this->company->settings->custom_value1 : '', $this->formatMoney($this->amount), $this->sepa['purpose'], - substr($this->invoice->number,0,34), + substr($this->invoice->number, 0, 34), '', '' - )), "\n"); - + ]), "\n"); } private function validateFields() { - - if(Ninja::isSelfHost() && isset($this->company?->custom_fields?->company2)) + if (Ninja::isSelfHost() && isset($this->company?->custom_fields?->company2)) { nlog('The BIC field is not present and _may_ be a required fields for EPC QR codes'); + } - if(Ninja::isSelfHost() && isset($this->company?->custom_fields?->company1)) + if (Ninja::isSelfHost() && isset($this->company?->custom_fields?->company1)) { nlog('The IBAN field is required'); - + } } - private function formatMoney($value) { + private function formatMoney($value) + { return sprintf('EUR%s', number_format($value, 2, '.', '')); } -} \ No newline at end of file +} diff --git a/app/Helpers/Generic.php b/app/Helpers/Generic.php index cccd27e0c06c..a0b3247aab47 100644 --- a/app/Helpers/Generic.php +++ b/app/Helpers/Generic.php @@ -43,4 +43,4 @@ function nlog($output, $context = []): void $output = null; $context = null; -} \ No newline at end of file +} diff --git a/app/Helpers/Invoice/InvoiceItemSum.php b/app/Helpers/Invoice/InvoiceItemSum.php index 7201a03325d1..464679e2f5e2 100644 --- a/app/Helpers/Invoice/InvoiceItemSum.php +++ b/app/Helpers/Invoice/InvoiceItemSum.php @@ -112,11 +112,9 @@ class InvoiceItemSum if ($this->invoice->is_amount_discount) { $this->setLineTotal($this->getLineTotal() - $this->formatValue($this->item->discount, $this->currency->precision)); } else { - $discount = ($this->item->line_total * ($this->item->discount / 100)); $this->setLineTotal($this->formatValue(($this->getLineTotal() - $discount), $this->currency->precision)); - } $this->item->is_amount_discount = $this->invoice->is_amount_discount; diff --git a/app/Helpers/Invoice/InvoiceSum.php b/app/Helpers/Invoice/InvoiceSum.php index ffdfdf11232f..3510804b5917 100644 --- a/app/Helpers/Invoice/InvoiceSum.php +++ b/app/Helpers/Invoice/InvoiceSum.php @@ -12,7 +12,6 @@ namespace App\Helpers\Invoice; use App\Models\Invoice; -use App\Models\TaxRate; use App\Utils\Traits\NumberFormatter; use Illuminate\Support\Collection; @@ -101,7 +100,6 @@ class InvoiceSum private function calculateCustomValues() { - $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge1); $this->total_custom_values += $this->valuer($this->invoice->custom_surcharge2); @@ -151,7 +149,6 @@ class InvoiceSum */ private function calculateBalance() { - $this->setCalculatedAttributes(); return $this; diff --git a/app/Helpers/Invoice/ProRata.php b/app/Helpers/Invoice/ProRata.php index 97facf247b73..7c2027f6b8ac 100644 --- a/app/Helpers/Invoice/ProRata.php +++ b/app/Helpers/Invoice/ProRata.php @@ -13,9 +13,7 @@ namespace App\Helpers\Invoice; use App\Models\Invoice; use App\Models\RecurringInvoice; -use Carbon\Exceptions\InvalidFormatException; use Exception; -use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Support\Carbon; class ProRata diff --git a/app/Helpers/Mail/GmailTransport.php b/app/Helpers/Mail/GmailTransport.php index 4ea61fa3d2bc..4c74e0961d1e 100644 --- a/app/Helpers/Mail/GmailTransport.php +++ b/app/Helpers/Mail/GmailTransport.php @@ -11,9 +11,9 @@ namespace App\Helpers\Mail; +use Google\Client; use Google\Service\Gmail; use Google\Service\Gmail\Message; -use Google\Client; use Symfony\Component\Mailer\SentMessage; use Symfony\Component\Mailer\Transport\AbstractTransport; use Symfony\Component\Mime\MessageConverter; @@ -23,7 +23,6 @@ use Symfony\Component\Mime\MessageConverter; */ class GmailTransport extends AbstractTransport { - public function __construct() { parent::__construct(); @@ -50,34 +49,26 @@ class GmailTransport extends AbstractTransport $bcc_list = ''; - if($bccs) - { + if ($bccs) { $bcc_list = 'Bcc: '; - foreach($bccs->getAddresses() as $address){ - + foreach ($bccs->getAddresses() as $address) { $bcc_list .= $address->getAddress() .','; - } $bcc_list = rtrim($bcc_list, ",") . "\r\n"; - } + } $body->setRaw($this->base64_encode($bcc_list.$message->toString())); - try{ + try { $service->users_messages->send('me', $body, []); - } - catch(\Google\Service\Exception $e) { - + } catch(\Google\Service\Exception $e) { /* Need to slow down */ - if($e->getCode() == '429') { - + if ($e->getCode() == '429') { nlog("429 google - retrying "); $service->users_messages->send('me', $body, []); - } - } } @@ -90,5 +81,4 @@ class GmailTransport extends AbstractTransport { return 'gmail'; } - } diff --git a/app/Helpers/Mail/Office365MailTransport.php b/app/Helpers/Mail/Office365MailTransport.php index e396e8f42531..246ebb025069 100644 --- a/app/Helpers/Mail/Office365MailTransport.php +++ b/app/Helpers/Mail/Office365MailTransport.php @@ -11,16 +11,13 @@ namespace App\Helpers\Mail; -use Illuminate\Support\Str; use Microsoft\Graph\Graph; -use Microsoft\Graph\Model\UploadSession; use Symfony\Component\Mailer\SentMessage; use Symfony\Component\Mailer\Transport\AbstractTransport; use Symfony\Component\Mime\MessageConverter; class Office365MailTransport extends AbstractTransport { - public function __construct() { parent::__construct(); @@ -28,7 +25,6 @@ class Office365MailTransport extends AbstractTransport protected function doSend(SentMessage $message): void { - $symfony_message = MessageConverter::toEmail($message->getOriginalMessage()); $graph = new Graph(); @@ -41,16 +37,11 @@ class Office365MailTransport extends AbstractTransport $bcc_list = ''; - if($bccs) - { - - foreach($bccs->getAddresses() as $address){ - + if ($bccs) { + foreach ($bccs->getAddresses() as $address) { $bcc_list .= 'Bcc: "'.$address->getAddress().'" <'.$address->getAddress().'>\r\n'; - } - - } + } try { $graphMessage = $graph->createRequest('POST', '/users/'.$symfony_message->getFrom()[0]->getAddress().'/sendmail') @@ -66,12 +57,10 @@ class Office365MailTransport extends AbstractTransport ->setReturnType(\Microsoft\Graph\Model\Message::class) ->execute(); } - } public function __toString(): string { return 'office365'; } - } diff --git a/app/Helpers/Subscription/SubscriptionCalculator.php b/app/Helpers/Subscription/SubscriptionCalculator.php index ef0fa8465f64..dd9675bef4ad 100644 --- a/app/Helpers/Subscription/SubscriptionCalculator.php +++ b/app/Helpers/Subscription/SubscriptionCalculator.php @@ -13,7 +13,6 @@ namespace App\Helpers\Subscription; use App\Helpers\Invoice\ProRata; use App\Models\Invoice; -use App\Models\RecurringInvoice; use App\Models\Subscription; use Illuminate\Support\Carbon; diff --git a/app/Helpers/SwissQr/SwissQrGenerator.php b/app/Helpers/SwissQr/SwissQrGenerator.php index d6b47a99c315..abacbb57c056 100644 --- a/app/Helpers/SwissQr/SwissQrGenerator.php +++ b/app/Helpers/SwissQr/SwissQrGenerator.php @@ -21,7 +21,6 @@ use Sprain\SwissQrBill as QrBill; */ class SwissQrGenerator { - protected Company $company; protected $invoice; @@ -39,155 +38,143 @@ class SwissQrGenerator private function calcDueAmount() { - if($this->invoice->partial > 0) + if ($this->invoice->partial > 0) { return $this->invoice->partial; + } - if($this->invoice->status_id == Invoice::STATUS_DRAFT) + if ($this->invoice->status_id == Invoice::STATUS_DRAFT) { return $this->invoice->amount; + } return $this->invoice->balance; } public function run() { - - // This is an example how to create a typical qr bill: - // - with reference number - // - with known debtor - // - with specified amount - // - with human-readable additional information - // - using your QR-IBAN + // This is an example how to create a typical qr bill: + // - with reference number + // - with known debtor + // - with specified amount + // - with human-readable additional information + // - using your QR-IBAN // - // Likely the most common use-case in the business world. + // Likely the most common use-case in the business world. - // Create a new instance of QrBill, containing default headers with fixed values - $qrBill = QrBill\QrBill::create(); + // Create a new instance of QrBill, containing default headers with fixed values + $qrBill = QrBill\QrBill::create(); - // Add creditor information - // Who will receive the payment and to which bank account? - $qrBill->setCreditor( - QrBill\DataGroup\Element\CombinedAddress::create( - $this->company->present()->name(), - $this->company->present()->address1(), - $this->company->present()->getCompanyCityState(), - 'CH' - )); - - $qrBill->setCreditorInformation( - QrBill\DataGroup\Element\CreditorInformation::create( - $this->company->present()->qr_iban() ?: '' // This is a special QR-IBAN. Classic IBANs will not be valid here. - )); - - // Add debtor information - // Who has to pay the invoice? This part is optional. - // - // Notice how you can use two different styles of addresses: CombinedAddress or StructuredAddress - // They are interchangeable for creditor as well as debtor. - $qrBill->setUltimateDebtor( - QrBill\DataGroup\Element\StructuredAddress::createWithStreet( - substr($this->client->present()->name(), 0 , 70), - $this->client->address1 ? substr($this->client->address1, 0 , 70) : ' ', - $this->client->address2 ? substr($this->client->address2, 0 , 16) : ' ', - $this->client->postal_code ? substr($this->client->postal_code, 0, 16) : ' ', - $this->client->city ? substr($this->client->city, 0, 35) : ' ', - 'CH' - )); - - // Add payment amount information - // What amount is to be paid? - $qrBill->setPaymentAmountInformation( - QrBill\DataGroup\Element\PaymentAmountInformation::create( - 'CHF', - $this->calcDueAmount() - )); - - // Add payment reference - // This is what you will need to identify incoming payments. - - if(stripos($this->invoice->number, "Live") === 0) - { - // we're currently in preview status. Let's give a dummy reference for now - $invoice_number = "123456789"; - } - else - { - $tempInvoiceNumber = $this->invoice->number; - $tempInvoiceNumber = preg_replace('/[^A-Za-z0-9]/', '', $tempInvoiceNumber); - $tempInvoiceNumber = substr($tempInvoiceNumber, 1); - - $calcInvoiceNumber = ""; - $array = str_split($tempInvoiceNumber); - foreach($array as $char) - { - if (is_numeric($char)) - { - // - } - else - { - if ($char) - { - $char = strtolower($char); - $char = ord($char) - 96; - } - else - { - return 0; - } - } - $calcInvoiceNumber .= $char; - } - - $invoice_number = $calcInvoiceNumber; - - } - - if(strlen($this->company->present()->besr_id()) > 1) - { - $referenceNumber = QrBill\Reference\QrPaymentReferenceGenerator::generate( - $this->company->present()->besr_id() ?: '', // You receive this number from your bank (BESR-ID). Unless your bank is PostFinance, in that case use NULL. - $invoice_number// A number to match the payment with your internal data, e.g. an invoice number + // Add creditor information + // Who will receive the payment and to which bank account? + $qrBill->setCreditor( + QrBill\DataGroup\Element\CombinedAddress::create( + $this->company->present()->name(), + $this->company->present()->address1(), + $this->company->present()->getCompanyCityState(), + 'CH' + ) ); - $qrBill->setPaymentReference( - QrBill\DataGroup\Element\PaymentReference::create( - QrBill\DataGroup\Element\PaymentReference::TYPE_QR, - $referenceNumber - )); + $qrBill->setCreditorInformation( + QrBill\DataGroup\Element\CreditorInformation::create( + $this->company->present()->qr_iban() ?: '' // This is a special QR-IBAN. Classic IBANs will not be valid here. + ) + ); - } - else{ + // Add debtor information + // Who has to pay the invoice? This part is optional. + // + // Notice how you can use two different styles of addresses: CombinedAddress or StructuredAddress + // They are interchangeable for creditor as well as debtor. + $qrBill->setUltimateDebtor( + QrBill\DataGroup\Element\StructuredAddress::createWithStreet( + substr($this->client->present()->name(), 0, 70), + $this->client->address1 ? substr($this->client->address1, 0, 70) : ' ', + $this->client->address2 ? substr($this->client->address2, 0, 16) : ' ', + $this->client->postal_code ? substr($this->client->postal_code, 0, 16) : ' ', + $this->client->city ? substr($this->client->city, 0, 35) : ' ', + 'CH' + ) + ); - $qrBill->setPaymentReference( - QrBill\DataGroup\Element\PaymentReference::create( - QrBill\DataGroup\Element\PaymentReference::TYPE_NON - )); + // Add payment amount information + // What amount is to be paid? + $qrBill->setPaymentAmountInformation( + QrBill\DataGroup\Element\PaymentAmountInformation::create( + 'CHF', + $this->calcDueAmount() + ) + ); - } + // Add payment reference + // This is what you will need to identify incoming payments. + + if (stripos($this->invoice->number, "Live") === 0) { + // we're currently in preview status. Let's give a dummy reference for now + $invoice_number = "123456789"; + } else { + $tempInvoiceNumber = $this->invoice->number; + $tempInvoiceNumber = preg_replace('/[^A-Za-z0-9]/', '', $tempInvoiceNumber); + $tempInvoiceNumber = substr($tempInvoiceNumber, 1); + + $calcInvoiceNumber = ""; + $array = str_split($tempInvoiceNumber); + foreach ($array as $char) { + if (is_numeric($char)) { + // + } else { + if ($char) { + $char = strtolower($char); + $char = ord($char) - 96; + } else { + return 0; + } + } + $calcInvoiceNumber .= $char; + } + + $invoice_number = $calcInvoiceNumber; + } - // Optionally, add some human-readable information about what the bill is for. - $qrBill->setAdditionalInformation( - QrBill\DataGroup\Element\AdditionalInformation::create( - $this->invoice->public_notes ? substr($this->invoice->public_notes, 0, 139) : ctrans('texts.invoice_number_placeholder', ['invoice' => $this->invoice->number]) - ) - ); + if (strlen($this->company->present()->besr_id()) > 1) { + $referenceNumber = QrBill\Reference\QrPaymentReferenceGenerator::generate( + $this->company->present()->besr_id() ?: '', // You receive this number from your bank (BESR-ID). Unless your bank is PostFinance, in that case use NULL. + $invoice_number// A number to match the payment with your internal data, e.g. an invoice number + ); + + $qrBill->setPaymentReference( + QrBill\DataGroup\Element\PaymentReference::create( + QrBill\DataGroup\Element\PaymentReference::TYPE_QR, + $referenceNumber + ) + ); + } else { + $qrBill->setPaymentReference( + QrBill\DataGroup\Element\PaymentReference::create( + QrBill\DataGroup\Element\PaymentReference::TYPE_NON + ) + ); + } + + // Optionally, add some human-readable information about what the bill is for. + $qrBill->setAdditionalInformation( + QrBill\DataGroup\Element\AdditionalInformation::create( + $this->invoice->public_notes ? substr($this->invoice->public_notes, 0, 139) : ctrans('texts.invoice_number_placeholder', ['invoice' => $this->invoice->number]) + ) + ); - // Now get the QR code image and save it as a file. + // Now get the QR code image and save it as a file. try { - $output = new QrBill\PaymentPart\Output\HtmlOutput\HtmlOutput($qrBill, $this->client->locale() ?: 'en'); $html = $output ->setPrintable(false) ->getPaymentPart(); - return $html; - + return $html; } catch (\Exception $e) { - - foreach($qrBill->getViolations() as $key => $violation) { + foreach ($qrBill->getViolations() as $key => $violation) { nlog("qr"); nlog($violation); } @@ -197,8 +184,5 @@ class SwissQrGenerator return ''; // return $e->getMessage(); } - - } - } diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index 9e3916d32612..71de89040149 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -92,10 +92,10 @@ class ActivityController extends BaseController ->take($default_activities); if ($request->has('react')) { - - if(!auth()->user()->isAdmin()) + if (!auth()->user()->isAdmin()) { $activities->where('user_id', auth()->user()->id); - // return response()->json(['data' => []], 200); + } + // return response()->json(['data' => []], 200); $system = ctrans('texts.system'); @@ -183,7 +183,6 @@ class ActivityController extends BaseController */ if ($backup && $backup->filename && Storage::disk(config('filesystems.default'))->exists($backup->filename)) { //disk - if (Ninja::isHosted()) { $html_backup = file_get_contents(Storage::disk(config('filesystems.default'))->url($backup->filename)); } else { diff --git a/app/Http/Controllers/Auth/ContactForgotPasswordController.php b/app/Http/Controllers/Auth/ContactForgotPasswordController.php index f106936236bf..cda235731295 100644 --- a/app/Http/Controllers/Auth/ContactForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ContactForgotPasswordController.php @@ -112,7 +112,6 @@ class ContactForgotPasswordController extends Controller $response = false; if ($contact) { - /* Update all instances of the client */ $token = Str::random(60); ClientContact::where('email', $contact->email)->update(['token' => $token]); diff --git a/app/Http/Controllers/Auth/ContactLoginController.php b/app/Http/Controllers/Auth/ContactLoginController.php index edc60dc3c512..0872b085069d 100644 --- a/app/Http/Controllers/Auth/ContactLoginController.php +++ b/app/Http/Controllers/Auth/ContactLoginController.php @@ -24,7 +24,6 @@ use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; -use Route; class ContactLoginController extends Controller { @@ -45,12 +44,11 @@ class ContactLoginController extends Controller if ($request->session()->has('company_key')) { MultiDB::findAndSetDbByCompanyKey($request->session()->get('company_key')); $company = Company::where('company_key', $request->input('company_key'))->first(); - } - elseif($request->has('company_key')){ - MultiDB::findAndSetDbByCompanyKey($request->input('company_key')); + } elseif ($request->has('company_key')) { + MultiDB::findAndSetDbByCompanyKey($request->input('company_key')); $company = Company::where('company_key', $request->input('company_key'))->first(); - }elseif($company_key){ - MultiDB::findAndSetDbByCompanyKey($company_key); + } elseif ($company_key) { + MultiDB::findAndSetDbByCompanyKey($company_key); $company = Company::where('company_key', $company_key)->first(); } diff --git a/app/Http/Controllers/Auth/ContactRegisterController.php b/app/Http/Controllers/Auth/ContactRegisterController.php index 827f6147caac..15acb8c7d765 100644 --- a/app/Http/Controllers/Auth/ContactRegisterController.php +++ b/app/Http/Controllers/Auth/ContactRegisterController.php @@ -51,7 +51,6 @@ class ContactRegisterController extends Controller public function register(RegisterRequest $request) { - $request->merge(['company' => $request->company()]); $client = $this->getClient($request->all()); @@ -70,7 +69,7 @@ class ContactRegisterController extends Controller $client->save(); - if(isset($data['currency_id'])) { + if (isset($data['currency_id'])) { $settings = $client->settings; $settings->currency_id = isset($data['currency_id']) ? $data['currency_id'] : $data['company']->settings->currency_id; $client->settings = $settings; diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 4ac3e5ce2f39..5d4f4b347947 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -19,7 +19,6 @@ use App\Http\Controllers\Controller; use App\Http\Requests\Login\LoginRequest; use App\Jobs\Account\CreateAccount; use App\Jobs\Company\CreateCompanyToken; -use App\Jobs\Util\SystemLogger; use App\Libraries\MultiDB; use App\Libraries\OAuth\OAuth; use App\Libraries\OAuth\Providers\Google; @@ -28,7 +27,6 @@ use App\Models\Client; use App\Models\Company; use App\Models\CompanyToken; use App\Models\CompanyUser; -use App\Models\SystemLog; use App\Models\User; use App\Transformers\CompanyUserTransformer; use App\Utils\Ninja; @@ -41,12 +39,10 @@ use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; use Laravel\Socialite\Facades\Socialite; use Microsoft\Graph\Model; use PragmaRX\Google2FA\Google2FA; use Turbo124\Beacon\Facades\LightLogs; -use Illuminate\Support\Facades\Http; class LoginController extends BaseController { @@ -418,7 +414,7 @@ class LoginController extends BaseController $name = OAuth::splitName($user->name); - if($provider == 'apple') { + if ($provider == 'apple') { $name[0] = request()->has('first_name') ? request()->input('first_name') : $name[0]; $name[1] = request()->has('last_name') ? request()->input('last_name') : $name[1]; } @@ -495,12 +491,13 @@ class LoginController extends BaseController private function handleMicrosoftOauth() { - if (request()->has('accessToken')) + if (request()->has('accessToken')) { $accessToken = request()->input('accessToken'); - elseif(request()->has('access_token')) + } elseif (request()->has('access_token')) { $accessToken = request()->input('access_token'); - else + } else { return response()->json(['message' => 'Invalid response from oauth server, no access token in response.'], 400); + } $graph = new \Microsoft\Graph\Graph(); @@ -554,7 +551,6 @@ class LoginController extends BaseController return response()->json(['message' => 'Unable to authenticate this user'], 400); - } private function existingOauthUser($existing_user) @@ -600,10 +596,11 @@ class LoginController extends BaseController $google = new Google(); - if(request()->has('id_token')) + if (request()->has('id_token')) { $user = $google->getTokenResponse(request()->input('id_token')); - else + } else { return response()->json(['message' => 'Illegal request'], 403); + } if (is_array($user)) { $query = [ @@ -632,7 +629,6 @@ class LoginController extends BaseController } if ($user) { - //check the user doesn't already exist in some form if ($existing_login_user = MultiDB::hasUser(['email' => $google->harvestEmail($user)])) { if (!$existing_login_user->account) { @@ -702,7 +698,7 @@ class LoginController extends BaseController $parameters = ['access_type' => 'offline', 'prompt' => 'consent select_account', 'redirect_uri' => config('ninja.app_url') . '/auth/google']; } - if($provider == 'microsoft'){ + if ($provider == 'microsoft') { $scopes = ['email', 'Mail.Send', 'offline_access', 'profile', 'User.Read openid']; $parameters = ['response_type' => 'code', 'redirect_uri' => config('ninja.app_url')."/auth/microsoft"]; } @@ -766,8 +762,7 @@ class LoginController extends BaseController $oauth_expiry = now()->addSeconds($socialite_user->accessTokenResponseBody['expires_in']) ?: now()->addSeconds(300); - if($user = OAuth::handleAuth($socialite_user, $provider)) - { + if ($user = OAuth::handleAuth($socialite_user, $provider)) { nlog('found user and updating their user record'); $name = OAuth::splitName($socialite_user->getName()); diff --git a/app/Http/Controllers/Auth/VendorContactLoginController.php b/app/Http/Controllers/Auth/VendorContactLoginController.php index 242fd81ba839..91708e065faf 100644 --- a/app/Http/Controllers/Auth/VendorContactLoginController.php +++ b/app/Http/Controllers/Auth/VendorContactLoginController.php @@ -11,20 +11,9 @@ namespace App\Http\Controllers\Auth; -use App\Events\Contact\ContactLoggedIn; use App\Http\Controllers\Controller; -use App\Http\ViewComposers\PortalComposer; -use App\Libraries\MultiDB; -use App\Models\Account; -use App\Models\ClientContact; -use App\Models\Company; -use App\Utils\Ninja; use Auth; use Illuminate\Foundation\Auth\AuthenticatesUsers; -use Illuminate\Http\JsonResponse; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Hash; -use Route; class VendorContactLoginController extends Controller { diff --git a/app/Http/Controllers/Bank/YodleeController.php b/app/Http/Controllers/Bank/YodleeController.php index 7f107c1e8431..1783d097c904 100644 --- a/app/Http/Controllers/Bank/YodleeController.php +++ b/app/Http/Controllers/Bank/YodleeController.php @@ -20,11 +20,9 @@ use Illuminate\Http\Request; class YodleeController extends BaseController { - public function auth(YodleeAuthRequest $request) { - - // create a user at this point + // create a user at this point // use the one time token here to pull in the actual user // store the user_account_id on the accounts table @@ -35,15 +33,11 @@ class YodleeController extends BaseController //ensure user is enterprise!! - if($company->account->bank_integration_account_id){ - + if ($company->account->bank_integration_account_id) { $flow = 'edit'; $token = $company->account->bank_integration_account_id; - - } - else{ - + } else { $flow = 'add'; $response = $yodlee->createUser($company); @@ -53,13 +47,13 @@ class YodleeController extends BaseController $company->account->bank_integration_account_id = $token; $company->push(); - } $yodlee = new Yodlee($token); - if($request->has('window_closed') && $request->input("window_closed") == "true") + if ($request->has('window_closed') && $request->input("window_closed") == "true") { $this->getAccounts($company, $token); + } $data = [ 'access_token' => $yodlee->getAccessToken(), @@ -72,20 +66,16 @@ class YodleeController extends BaseController ]; return view('bank.yodlee.auth', $data); - } private function getAccounts($company, $token) { $yodlee = new Yodlee($token); - $accounts = $yodlee->getAccounts(); + $accounts = $yodlee->getAccounts(); - foreach($accounts as $account) - { - - if(!BankIntegration::where('bank_account_id', $account['id'])->where('company_id', $company->id)->exists()) - { + foreach ($accounts as $account) { + if (!BankIntegration::where('bank_account_id', $account['id'])->where('company_id', $company->id)->exists()) { $bank_integration = new BankIntegration(); $bank_integration->company_id = $company->id; $bank_integration->account_id = $company->account_id; @@ -104,16 +94,12 @@ class YodleeController extends BaseController $bank_integration->save(); } - } - $company->account->bank_integrations->each(function ($bank_integration) use ($company){ - + $company->account->bank_integrations->each(function ($bank_integration) use ($company) { ProcessBankTransactions::dispatch($company->account->bank_integration_account_id, $bank_integration); - }); - } @@ -183,7 +169,7 @@ class YodleeController extends BaseController }*/ public function refreshWebhook(Request $request) { -//we should ignore this one + //we should ignore this one nlog("yodlee refresh"); nlog($request->all()); @@ -218,7 +204,6 @@ class YodleeController extends BaseController */ public function balanceWebhook(Request $request) { - nlog("yodlee refresh"); nlog($request->all()); @@ -230,15 +215,15 @@ class YodleeController extends BaseController } /* -{ - "event":{ - "data":[ - { - "autoRefresh":{ +{ + "event":{ + "data":[ + { + "autoRefresh":{ "additionalStatus":"SCHEDULED", "status":"ENABLED" }, - "accountIds":[ + "accountIds":[ 1112645899, 1112645898 ], @@ -254,7 +239,7 @@ class YodleeController extends BaseController */ public function refreshUpdatesWebhook(Request $request) { -//notifies a user if there are problems with yodlee accessing the data + //notifies a user if there are problems with yodlee accessing the data nlog("update refresh"); nlog($request->all()); @@ -289,7 +274,7 @@ class YodleeController extends BaseController */ public function dataUpdatesWebhook(Request $request) { -//this is the main hook we use for notifications + //this is the main hook we use for notifications nlog("data refresh"); nlog($request->all()); @@ -300,5 +285,4 @@ class YodleeController extends BaseController // return response()->json(['message' => 'Unauthorized'], 403); } - } diff --git a/app/Http/Controllers/BankIntegrationController.php b/app/Http/Controllers/BankIntegrationController.php index 1c47c4fa4c96..02dabc66d189 100644 --- a/app/Http/Controllers/BankIntegrationController.php +++ b/app/Http/Controllers/BankIntegrationController.php @@ -25,7 +25,6 @@ use App\Http\Requests\BankIntegration\UpdateBankIntegrationRequest; use App\Jobs\Bank\ProcessBankTransactions; use App\Models\BankIntegration; use App\Repositories\BankIntegrationRepository; -use App\Services\Bank\BankMatchingService; use App\Transformers\BankIntegrationTransformer; use App\Utils\Traits\MakesHash; use Illuminate\Http\Request; @@ -94,11 +93,9 @@ class BankIntegrationController extends BaseController */ public function index(BankIntegrationFilters $filters) { - $bank_integrations = BankIntegration::filter($filters); return $this->listResponse($bank_integrations); - } /** @@ -262,7 +259,6 @@ class BankIntegrationController extends BaseController */ public function update(UpdateBankIntegrationRequest $request, BankIntegration $bank_integration) { - //stubs for updating the model $bank_integration = $this->bank_integration_repo->save($request->all(), $bank_integration); @@ -476,9 +472,8 @@ class BankIntegrationController extends BaseController ->company() ->cursor() ->each(function ($bank_integration, $key) use ($action) { - - $this->bank_integration_repo->{$action}($bank_integration); - }); + $this->bank_integration_repo->{$action}($bank_integration); + }); /* Need to understand which permission are required for the given bulk action ie. view / edit */ @@ -528,18 +523,16 @@ class BankIntegrationController extends BaseController $bank_account_id = auth()->user()->account->bank_integration_account_id; - if(!$bank_account_id) + if (!$bank_account_id) { return response()->json(['message' => 'Not yet authenticated with Bank Integration service'], 400); + } $yodlee = new Yodlee($bank_account_id); - $accounts = $yodlee->getAccounts(); + $accounts = $yodlee->getAccounts(); - foreach($accounts as $account) - { - - if(!BankIntegration::where('bank_account_id', $account['id'])->where('company_id', auth()->user()->company()->id)->exists()) - { + foreach ($accounts as $account) { + if (!BankIntegration::where('bank_account_id', $account['id'])->where('company_id', auth()->user()->company()->id)->exists()) { $bank_integration = new BankIntegration(); $bank_integration->company_id = auth()->user()->company()->id; $bank_integration->account_id = auth()->user()->account_id; @@ -556,19 +549,17 @@ class BankIntegrationController extends BaseController $bank_integration->currency = $account['account_currency']; $bank_integration->save(); - } } $account = auth()->user()->account; - if(Cache::get("throttle_polling:{$account->key}")) + if (Cache::get("throttle_polling:{$account->key}")) { return response()->json(BankIntegration::query()->company(), 200); + } - $account->bank_integrations->each(function ($bank_integration) use ($account){ - + $account->bank_integrations->each(function ($bank_integration) use ($account) { ProcessBankTransactions::dispatch($account->bank_integration_account_id, $bank_integration); - }); Cache::put("throttle_polling:{$account->key}", true, 300); @@ -615,11 +606,11 @@ class BankIntegrationController extends BaseController public function removeAccount(AdminBankIntegrationRequest $request, $acc_id) { - $bank_account_id = auth()->user()->account->bank_integration_account_id; - if(!$bank_account_id) + if (!$bank_account_id) { return response()->json(['message' => 'Not yet authenticated with Bank Integration service'], 400); + } $bi = BankIntegration::withTrashed()->where('bank_account_id', $acc_id)->company()->firstOrFail(); @@ -629,7 +620,6 @@ class BankIntegrationController extends BaseController $this->bank_integration_repo->delete($bi); return $this->itemResponse($bi->fresh()); - } @@ -671,14 +661,10 @@ class BankIntegrationController extends BaseController */ public function getTransactions(AdminBankIntegrationRequest $request) { - auth()->user()->account->bank_integrations->each(function ($bank_integration) { - (new ProcessBankTransactions(auth()->user()->account->bank_integration_account_id, $bank_integration))->handle(); - }); return response()->json(['message' => 'Fetching transactions....'], 200); - } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/BankTransactionController.php b/app/Http/Controllers/BankTransactionController.php index a1596e0f9afa..3967a969750e 100644 --- a/app/Http/Controllers/BankTransactionController.php +++ b/app/Http/Controllers/BankTransactionController.php @@ -13,27 +13,19 @@ namespace App\Http\Controllers; use App\Factory\BankTransactionFactory; use App\Filters\BankTransactionFilters; -use App\Helpers\Bank\Yodlee\Yodlee; -use App\Http\Requests\BankTransaction\AdminBankTransactionRequest; use App\Http\Requests\BankTransaction\BulkBankTransactionRequest; use App\Http\Requests\BankTransaction\CreateBankTransactionRequest; use App\Http\Requests\BankTransaction\DestroyBankTransactionRequest; use App\Http\Requests\BankTransaction\EditBankTransactionRequest; -use App\Http\Requests\BankTransaction\ImportBankTransactionsRequest; use App\Http\Requests\BankTransaction\MatchBankTransactionRequest; use App\Http\Requests\BankTransaction\ShowBankTransactionRequest; use App\Http\Requests\BankTransaction\StoreBankTransactionRequest; use App\Http\Requests\BankTransaction\UpdateBankTransactionRequest; -use App\Http\Requests\Import\PreImportRequest; use App\Jobs\Bank\MatchBankTransactions; use App\Models\BankTransaction; use App\Repositories\BankTransactionRepository; -use App\Services\Bank\BankMatchingService; use App\Transformers\BankTransactionTransformer; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; class BankTransactionController extends BaseController { @@ -98,11 +90,9 @@ class BankTransactionController extends BaseController */ public function index(BankTransactionFilters $filters) { - $bank_transactions = BankTransaction::filter($filters); return $this->listResponse($bank_transactions); - } /** @@ -266,7 +256,6 @@ class BankTransactionController extends BaseController */ public function update(UpdateBankTransactionRequest $request, BankTransaction $bank_transaction) { - //stubs for updating the model $bank_transaction = $this->bank_transaction_repo->save($request->all(), $bank_transaction); @@ -478,18 +467,13 @@ class BankTransactionController extends BaseController $bank_transactions = BankTransaction::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get(); - if($action == 'convert_matched') //catch this action - { - + if ($action == 'convert_matched') { //catch this action + $this->bank_transaction_repo->convert_matched($bank_transactions); - - } - else { - + } else { $bank_transactions->each(function ($bank_transaction, $key) use ($action) { - $this->bank_transaction_repo->{$action}($bank_transaction); + $this->bank_transaction_repo->{$action}($bank_transaction); }); - } /* Need to understand which permission are required for the given bulk action ie. view / edit */ @@ -548,14 +532,10 @@ class BankTransactionController extends BaseController */ public function match(MatchBankTransactionRequest $request) { - // MatchBankTransactions::dispatch(auth()->user()->company()->id, auth()->user()->company()->db, $request->all()); $bts = (new MatchBankTransactions(auth()->user()->company()->id, auth()->user()->company()->db, $request->all()))->handle(); return $this->listResponse($bts); - } - - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/BankTransactionRuleController.php b/app/Http/Controllers/BankTransactionRuleController.php index 143ae68a70cc..822a3cdc5165 100644 --- a/app/Http/Controllers/BankTransactionRuleController.php +++ b/app/Http/Controllers/BankTransactionRuleController.php @@ -11,11 +11,9 @@ namespace App\Http\Controllers; -use App\Factory\BankTransactionFactory; use App\Factory\BankTransactionRuleFactory; use App\Filters\BankTransactionFilters; use App\Filters\BankTransactionRuleFilters; -use App\Helpers\Bank\Yodlee\Yodlee; use App\Http\Requests\BankTransactionRule\BulkBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\CreateBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\DestroyBankTransactionRuleRequest; @@ -23,20 +21,10 @@ use App\Http\Requests\BankTransactionRule\EditBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\ShowBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\StoreBankTransactionRuleRequest; use App\Http\Requests\BankTransactionRule\UpdateBankTransactionRuleRequest; -use App\Http\Requests\BankTransaction\AdminBankTransactionRuleRequest; -use App\Http\Requests\Import\PreImportRequest; -use App\Jobs\Bank\MatchBankTransactionRules; -use App\Models\BankTransaction; use App\Models\BankTransactionRule; -use App\Repositories\BankTransactionRepository; use App\Repositories\BankTransactionRuleRepository; -use App\Services\Bank\BankMatchingService; use App\Transformers\BankTransactionRuleTransformer; -use App\Transformers\BankTransactionTransformer; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; class BankTransactionRuleController extends BaseController { @@ -101,11 +89,9 @@ class BankTransactionRuleController extends BaseController */ public function index(BankTransactionRuleFilters $filters) { - $bank_transaction_rules = BankTransactionRule::filter($filters); return $this->listResponse($bank_transaction_rules); - } /** @@ -269,7 +255,6 @@ class BankTransactionRuleController extends BaseController */ public function update(UpdateBankTransactionRuleRequest $request, BankTransactionRule $bank_transaction_rule) { - //stubs for updating the model $bank_transaction = $this->bank_transaction_repo->save($request->all(), $bank_transaction_rule); @@ -484,11 +469,10 @@ class BankTransactionRuleController extends BaseController ->company() ->cursor() ->each(function ($bank_transaction_rule, $key) use ($action) { - $this->bank_transaction_repo->{$action}($bank_transaction_rule); - }); + $this->bank_transaction_repo->{$action}($bank_transaction_rule); + }); /* Need to understand which permission are required for the given bulk action ie. view / edit */ return $this->listResponse(BankTransactionRule::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()); } - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index f319791092be..8871455980a6 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -11,33 +11,33 @@ namespace App\Http\Controllers; -use App\Models\User; -use App\Utils\Ninja; -use App\Models\Design; -use App\Utils\Statics; use App\Models\Account; -use App\Models\TaxRate; -use App\Models\Webhook; -use App\Models\Scheduler; -use App\Models\TaskStatus; -use App\Models\PaymentTerm; -use Illuminate\Support\Str; -use League\Fractal\Manager; -use App\Models\GroupSetting; -use App\Models\CompanyGateway; -use App\Utils\Traits\AppSetup; use App\Models\BankIntegration; use App\Models\BankTransaction; -use App\Models\ExpenseCategory; -use League\Fractal\Resource\Item; use App\Models\BankTransactionRule; +use App\Models\CompanyGateway; +use App\Models\Design; +use App\Models\ExpenseCategory; +use App\Models\GroupSetting; +use App\Models\PaymentTerm; +use App\Models\Scheduler; +use App\Models\TaskStatus; +use App\Models\TaxRate; +use App\Models\User; +use App\Models\Webhook; use App\Transformers\ArraySerializer; use App\Transformers\EntityTransformer; -use League\Fractal\Resource\Collection; -use Illuminate\Database\Eloquent\Builder; -use League\Fractal\Serializer\JsonApiSerializer; -use League\Fractal\Pagination\IlluminatePaginatorAdapter; +use App\Utils\Ninja; +use App\Utils\Statics; +use App\Utils\Traits\AppSetup; use Illuminate\Contracts\Container\BindingResolutionException; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Support\Str; +use League\Fractal\Manager; +use League\Fractal\Pagination\IlluminatePaginatorAdapter; +use League\Fractal\Resource\Collection; +use League\Fractal\Resource\Item; +use League\Fractal\Serializer\JsonApiSerializer; /** * Class BaseController. @@ -184,9 +184,9 @@ class BaseController extends Controller /** * Filters the includes to ensure the - * end user has the correct permissions to + * end user has the correct permissions to * view the includes - * + * * @param array $includes The includes for the object * @return string The filtered array of includes */ @@ -204,12 +204,11 @@ class BaseController extends Controller $collection = collect(explode(",", $includes)); - $filtered_includes = $collection->filter(function ($include) use ($permissions_array){ + $filtered_includes = $collection->filter(function ($include) use ($permissions_array) { return auth()->user()->hasPermission($permissions_array[$include]); }); return $filtered_includes->implode(","); - } /** @@ -247,7 +246,7 @@ class BaseController extends Controller /** * Refresh API response with latest cahnges * @param Builer $query - * @property App\Models\User auth()->user() + * @property App\Models\User auth()->user() * @return Builer */ protected function refreshResponse($query) @@ -283,11 +282,9 @@ class BaseController extends Controller $query->where('clients.updated_at', '>=', $updated_at)->with('contacts.company', 'gateway_tokens', 'documents'); if (! $user->hasPermission('view_client')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id); - }); - + }); } }, 'company.company_gateways' => function ($query) use ($user) { @@ -301,10 +298,9 @@ class BaseController extends Controller $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents'); if (! $user->hasPermission('view_credit')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id); - }); + }); } }, 'company.designs'=> function ($query) use ($updated_at, $user) { @@ -321,37 +317,30 @@ class BaseController extends Controller $query->where('updated_at', '>=', $updated_at)->with('documents'); if (! $user->hasPermission('view_expense')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id); - }); + }); } }, 'company.groups' => function ($query) { $query->whereNotNull('updated_at')->with('documents'); - }, 'company.invoices'=> function ($query) use ($updated_at, $user) { $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents'); if (! $user->hasPermission('view_invoice')) { - - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id); - }); - + }); } }, 'company.payments'=> function ($query) use ($updated_at, $user) { $query->where('updated_at', '>=', $updated_at)->with('paymentables', 'documents'); if (! $user->hasPermission('view_payment')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id); - }); - + }); } }, 'company.payment_terms'=> function ($query) use ($user) { @@ -365,78 +354,63 @@ class BaseController extends Controller $query->where('updated_at', '>=', $updated_at)->with('documents'); if (! $user->hasPermission('view_product')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id); - }); } - }, 'company.projects'=> function ($query) use ($updated_at, $user) { $query->where('updated_at', '>=', $updated_at)->with('documents'); if (! $user->hasPermission('view_project')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id); - }); - + }); } }, 'company.purchase_orders'=> function ($query) use ($updated_at, $user) { $query->where('updated_at', '>=', $updated_at)->with('documents'); if (! $user->hasPermission('view_purchase_order')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('purchase_orders.user_id', $user->id)->orWhere('purchase_orders.assigned_user_id', $user->id); - }); - + }); } }, 'company.quotes'=> function ($query) use ($updated_at, $user) { $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents'); if (! $user->hasPermission('view_quote')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('quotes.user_id', $user->id)->orWhere('quotes.assigned_user_id', $user->id); - }); - + }); } }, 'company.recurring_invoices'=> function ($query) use ($updated_at, $user) { $query->where('updated_at', '>=', $updated_at)->with('invitations', 'documents', 'client.gateway_tokens', 'client.group_settings', 'client.company'); if (! $user->hasPermission('view_recurring_invoice')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('recurring_invoices.user_id', $user->id)->orWhere('recurring_invoices.assigned_user_id', $user->id); - }); - + }); } }, 'company.recurring_expenses'=> function ($query) use ($updated_at, $user) { $query->where('updated_at', '>=', $updated_at)->with('documents'); if (! $user->hasPermission('view_recurring_expense')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id); - }); - + }); } }, 'company.tasks'=> function ($query) use ($updated_at, $user) { $query->where('updated_at', '>=', $updated_at)->with('documents'); if (! $user->hasPermission('view_task')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id); - }); - + }); } }, 'company.tax_rates'=> function ($query) { @@ -446,11 +420,9 @@ class BaseController extends Controller $query->where('updated_at', '>=', $updated_at)->with('contacts', 'documents'); if (! $user->hasPermission('view_vendor')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id); - }); - + }); } }, 'company.expense_categories'=> function ($query) { @@ -480,10 +452,9 @@ class BaseController extends Controller } //allows us to return integrations for users who can create bank transactions - if(!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) { + if (!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) { $query->exclude(["balance"]); } - }, 'company.bank_transactions'=> function ($query) use ($updated_at, $user) { $query->where('updated_at', '>=', $updated_at); @@ -526,8 +497,9 @@ class BaseController extends Controller private function resolveQueryLimit() { - if(request()->has('per_page')) + if (request()->has('per_page')) { return abs((int)request()->input('per_page', 20)); + } return 20; } @@ -575,24 +547,20 @@ class BaseController extends Controller } }, 'company.bank_integrations'=> function ($query) use ($user) { - if (! $user->hasPermission('view_bank_transaction')) { $query->where('bank_integrations.user_id', $user->id); } - if(!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) { + if (!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) { $query->exclude(["balance"]); } - }, 'company.bank_transaction_rules'=> function ($query) use ($user) { - if (! $user->isAdmin()) { $query->where('bank_transaction_rules.user_id', $user->id); } }, 'company.task_schedulers'=> function ($query) use ($user) { - if (! $user->isAdmin()) { $query->where('schedulers.user_id', $user->id); } @@ -615,17 +583,18 @@ class BaseController extends Controller } /** - * In case a user is not an admin and is - * able to access multiple companies, then we + * In case a user is not an admin and is + * able to access multiple companies, then we * need to pass back the mini load only - * + * * @return bool */ private function complexPermissionsUser(): bool { //if the user is attached to more than one company AND they are not an admin across all companies - if(auth()->user()->company_users()->count() > 1 && (auth()->user()->company_users()->where('is_admin',1)->count() != auth()->user()->company_users()->count())) + if (auth()->user()->company_users()->count() > 1 && (auth()->user()->company_users()->where('is_admin', 1)->count() != auth()->user()->company_users()->count())) { return true; + } return false; } @@ -664,11 +633,9 @@ class BaseController extends Controller $query->where('clients.created_at', '>=', $created_at)->with('contacts.company', 'gateway_tokens', 'documents'); if (! $user->hasPermission('view_client')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('clients.user_id', $user->id)->orWhere('clients.assigned_user_id', $user->id); }); - } }, 'company.company_gateways' => function ($query) use ($user) { @@ -682,8 +649,7 @@ class BaseController extends Controller $query->where('created_at', '>=', $created_at)->with('invitations', 'documents'); if (! $user->hasPermission('view_credit')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('credits.user_id', $user->id)->orWhere('credits.assigned_user_id', $user->id); }); } @@ -695,8 +661,7 @@ class BaseController extends Controller $query->where('created_at', '>=', $created_at)->with('documents'); if (! $user->hasPermission('view_expense')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('expenses.user_id', $user->id)->orWhere('expenses.assigned_user_id', $user->id); }); } @@ -708,22 +673,18 @@ class BaseController extends Controller $query->where('created_at', '>=', $created_at)->with('invitations', 'documents'); if (! $user->hasPermission('view_invoice')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('invoices.user_id', $user->id)->orWhere('invoices.assigned_user_id', $user->id); }); - } }, 'company.payments'=> function ($query) use ($created_at, $user) { $query->where('created_at', '>=', $created_at)->with('paymentables', 'documents'); if (! $user->hasPermission('view_payment')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('payments.user_id', $user->id)->orWhere('payments.assigned_user_id', $user->id); }); - } }, 'company.payment_terms'=> function ($query) use ($created_at) { @@ -733,8 +694,7 @@ class BaseController extends Controller $query->where('created_at', '>=', $created_at)->with('documents'); if (! $user->hasPermission('view_product')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('products.user_id', $user->id)->orWhere('products.assigned_user_id', $user->id); }); } @@ -743,8 +703,7 @@ class BaseController extends Controller $query->where('created_at', '>=', $created_at)->with('documents'); if (! $user->hasPermission('view_project')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('projects.user_id', $user->id)->orWhere('projects.assigned_user_id', $user->id); }); } @@ -753,44 +712,36 @@ class BaseController extends Controller $query->where('created_at', '>=', $created_at)->with('documents'); if (! $user->hasPermission('view_purchase_order')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('purchase_orders.user_id', $user->id)->orWhere('purchase_orders.assigned_user_id', $user->id); }); - } }, 'company.quotes'=> function ($query) use ($created_at, $user) { $query->where('created_at', '>=', $created_at)->with('invitations', 'documents'); if (! $user->hasPermission('view_quote')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('quotes.user_id', $user->id)->orWhere('quotes.assigned_user_id', $user->id); }); - } }, 'company.recurring_invoices'=> function ($query) use ($created_at, $user) { $query->where('created_at', '>=', $created_at)->with('invitations', 'documents', 'client.gateway_tokens', 'client.group_settings', 'client.company'); if (! $user->hasPermission('view_recurring_invoice')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('recurring_invoices.user_id', $user->id)->orWhere('recurring_invoices.assigned_user_id', $user->id); }); - } }, 'company.tasks'=> function ($query) use ($created_at, $user) { $query->where('created_at', '>=', $created_at)->with('documents'); if (! $user->hasPermission('view_task')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('tasks.user_id', $user->id)->orWhere('tasks.assigned_user_id', $user->id); }); - } }, 'company.tax_rates' => function ($query) use ($created_at) { @@ -800,11 +751,9 @@ class BaseController extends Controller $query->where('created_at', '>=', $created_at)->with('contacts', 'documents'); if (! $user->hasPermission('view_vendor')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('vendors.user_id', $user->id)->orWhere('vendors.assigned_user_id', $user->id); }); - } }, 'company.expense_categories'=> function ($query) { @@ -838,11 +787,9 @@ class BaseController extends Controller $query->where('created_at', '>=', $created_at)->with('documents'); if (! $user->hasPermission('view_recurring_expense')) { - - $query->whereNested(function($query) use ($user) { + $query->whereNested(function ($query) use ($user) { $query->where('recurring_expenses.user_id', $user->id)->orWhere('recurring_expenses.assigned_user_id', $user->id); }); - } }, 'company.bank_integrations'=> function ($query) use ($created_at, $user) { @@ -852,10 +799,9 @@ class BaseController extends Controller $query->where('bank_integrations.user_id', $user->id); } - if(!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) { + if (!$user->isSuperUser() && $user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) { $query->exclude(["balance"]); } - }, 'company.bank_transactions'=> function ($query) use ($created_at, $user) { $query->where('created_at', '>=', $created_at); @@ -902,22 +848,20 @@ class BaseController extends Controller if (auth()->user() && ! auth()->user()->hasPermission('view_'.Str::snake(class_basename($this->entity_type)))) { //06-10-2022 - some entities do not have assigned_user_id - this becomes an issue when we have a large company and low permission users - if(in_array($this->entity_type, [User::class])){ + if (in_array($this->entity_type, [User::class])) { $query->where('id', auth()->user()->id); - } - elseif(in_array($this->entity_type, [BankTransactionRule::class,CompanyGateway::class, TaxRate::class, BankIntegration::class, Scheduler::class, BankTransaction::class, Webhook::class, ExpenseCategory::class])){ //table without assigned_user_id - - if($this->entity_type == BankIntegration::class && !auth()->user()->isSuperUser() && auth()->user()->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) - $query->exclude(["balance"]); //allows us to selective display bank integrations back to the user if they can view / create bank transactions but without the bank balance being present in the response - else + } elseif (in_array($this->entity_type, [BankTransactionRule::class,CompanyGateway::class, TaxRate::class, BankIntegration::class, Scheduler::class, BankTransaction::class, Webhook::class, ExpenseCategory::class])) { //table without assigned_user_id + if ($this->entity_type == BankIntegration::class && !auth()->user()->isSuperUser() && auth()->user()->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])) { + $query->exclude(["balance"]); + } //allows us to selective display bank integrations back to the user if they can view / create bank transactions but without the bank balance being present in the response + else { $query->where('user_id', '=', auth()->user()->id); - } - elseif(in_array($this->entity_type, [Design::class, GroupSetting::class, PaymentTerm::class, TaskStatus::class])){ + } + } elseif (in_array($this->entity_type, [Design::class, GroupSetting::class, PaymentTerm::class, TaskStatus::class])) { // nlog($this->entity_type); - } - else + } else { $query->where('user_id', '=', auth()->user()->id)->orWhere('assigned_user_id', auth()->user()->id); - + } } // $query->exclude(['balance','credit_balance','paid_to_date']); @@ -1003,7 +947,6 @@ class BaseController extends Controller protected function getRequestIncludes($data) { - /* * Thresholds for displaying large account on first load */ @@ -1032,10 +975,10 @@ class BaseController extends Controller public function flutterRoute() { if ((bool) $this->checkAppSetup() !== false && $account = Account::first()) { - //always redirect invoicing.co to invoicing.co - if(Ninja::isHosted() && !in_array(request()->getSchemeAndHttpHost(), ['https://staging.invoicing.co', 'https://invoicing.co', 'https://demo.invoicing.co'])) + if (Ninja::isHosted() && !in_array(request()->getSchemeAndHttpHost(), ['https://staging.invoicing.co', 'https://invoicing.co', 'https://demo.invoicing.co'])) { return redirect()->secure('https://invoicing.co'); + } if (config('ninja.require_https') && ! request()->isSecure()) { return redirect()->secure(request()->getRequestUri()); @@ -1053,7 +996,7 @@ class BaseController extends Controller // 06-09-2022 - parse the path if loaded in a subdirectory for canvaskit resolution $canvas_path_array = parse_url(config('ninja.app_url')); $canvas_path = (array_key_exists('path', $canvas_path_array)) ? $canvas_path_array['path'] : ''; - $canvas_path = rtrim(str_replace("index.php", "", $canvas_path),'/'); + $canvas_path = rtrim(str_replace("index.php", "", $canvas_path), '/'); $data = []; @@ -1074,7 +1017,7 @@ class BaseController extends Controller $data['login'] = 'true'; } - if(request()->session()->has('signup')){ + if (request()->session()->has('signup')) { $data['signup'] = 'true'; } @@ -1119,7 +1062,6 @@ class BaseController extends Controller return 'main.html.dart.js'; default: return 'main.foss.dart.js'; - } } diff --git a/app/Http/Controllers/ClientController.php b/app/Http/Controllers/ClientController.php index f71d62495e01..bf4b43b76f07 100644 --- a/app/Http/Controllers/ClientController.php +++ b/app/Http/Controllers/ClientController.php @@ -493,7 +493,6 @@ class ClientController extends BaseController */ public function bulk(BulkClientRequest $request) { - $action = $request->action; $clients = Client::withTrashed() @@ -501,10 +500,10 @@ class ClientController extends BaseController ->whereIn('id', $request->ids) ->cursor() ->each(function ($client) use ($action) { - if (auth()->user()->can('edit', $client)) { - $this->client_repo->{$action}($client); - } - }); + if (auth()->user()->can('edit', $client)) { + $this->client_repo->{$action}($client); + } + }); return $this->listResponse(Client::withTrashed()->company()->whereIn('id', $request->ids)); } @@ -625,14 +624,11 @@ class ClientController extends BaseController { //delete all documents $client->documents->each(function ($document) { - - try{ + try { Storage::disk(config('filesystems.default'))->delete($document->url); - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog($e->getMessage()); } - }); //force delete the client @@ -707,19 +703,17 @@ class ClientController extends BaseController public function merge(PurgeClientRequest $request, Client $client, string $mergeable_client) { - $m_client = Client::withTrashed() ->where('id', $this->decodePrimaryKey($mergeable_client)) ->where('company_id', auth()->user()->company()->id) ->first(); - if(!$m_client) + if (!$m_client) { return response()->json(['message' => "Client not found"]); + } $merged_client = $client->service()->merge($m_client)->save(); return $this->itemResponse($merged_client); - } - } diff --git a/app/Http/Controllers/ClientGatewayTokenController.php b/app/Http/Controllers/ClientGatewayTokenController.php index 53263bfffa5e..75ea17883dea 100644 --- a/app/Http/Controllers/ClientGatewayTokenController.php +++ b/app/Http/Controllers/ClientGatewayTokenController.php @@ -11,8 +11,6 @@ namespace App\Http\Controllers; -use App\Events\ClientGatewayToken\ClientGatewayTokenWasCreated; -use App\Events\ClientGatewayToken\ClientGatewayTokenWasUpdated; use App\Factory\ClientGatewayTokenFactory; use App\Filters\ClientGatewayTokenFilters; use App\Http\Requests\ClientGatewayToken\CreateClientGatewayTokenRequest; @@ -22,19 +20,15 @@ use App\Http\Requests\ClientGatewayToken\ListClientGatewayTokenRequest; use App\Http\Requests\ClientGatewayToken\ShowClientGatewayTokenRequest; use App\Http\Requests\ClientGatewayToken\StoreClientGatewayTokenRequest; use App\Http\Requests\ClientGatewayToken\UpdateClientGatewayTokenRequest; -use App\Http\Requests\ClientGatewayToken\UploadClientGatewayTokenRequest; use App\Jobs\ClientGatewayToken\StoreClientGatewayToken; use App\Jobs\ClientGatewayToken\UpdateClientGatewayToken; -use App\Models\Account; use App\Models\ClientGatewayToken; use App\Repositories\ClientGatewayTokenRepository; use App\Transformers\ClientGatewayTokenTransformer; -use App\Utils\Ninja; use App\Utils\Traits\BulkOptions; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; use App\Utils\Traits\Uploadable; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** diff --git a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php index 8bb88d30e953..c4b016c647e5 100644 --- a/app/Http/Controllers/ClientPortal/ApplePayDomainController.php +++ b/app/Http/Controllers/ClientPortal/ApplePayDomainController.php @@ -13,11 +13,9 @@ namespace App\Http\Controllers\ClientPortal; use App\Http\Controllers\Controller; use App\Libraries\MultiDB; -use App\Models\Company; use App\Models\CompanyGateway; use App\Utils\Ninja; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Storage; class ApplePayDomainController extends Controller { @@ -25,7 +23,6 @@ class ApplePayDomainController extends Controller public function showAppleMerchantId(Request $request) { - /* Self Host */ if (Ninja::isSelfHost()) { diff --git a/app/Http/Controllers/ClientPortal/DocumentController.php b/app/Http/Controllers/ClientPortal/DocumentController.php index 3c50a64419af..b1a816d4bf77 100644 --- a/app/Http/Controllers/ClientPortal/DocumentController.php +++ b/app/Http/Controllers/ClientPortal/DocumentController.php @@ -86,7 +86,7 @@ class DocumentController extends Controller $zipFile->saveAsFile($filepath) // save the archive to a file ->close(); // close archive - return response()->download($filepath, $filename)->deleteFileAfterSend(true); + return response()->download($filepath, $filename)->deleteFileAfterSend(true); } catch (\PhpZip\Exception\ZipException $e) { // handle exception } finally { diff --git a/app/Http/Controllers/ClientPortal/InvitationController.php b/app/Http/Controllers/ClientPortal/InvitationController.php index 51fd56224e86..52ca200c8ceb 100644 --- a/app/Http/Controllers/ClientPortal/InvitationController.php +++ b/app/Http/Controllers/ClientPortal/InvitationController.php @@ -25,7 +25,6 @@ use App\Models\Payment; use App\Models\PurchaseOrderInvitation; use App\Models\QuoteInvitation; use App\Services\ClientPortal\InstantPayment; -use App\Utils\CurlUtils; use App\Utils\Ninja; use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; @@ -70,9 +69,9 @@ class InvitationController extends Controller private function genericRouter(string $entity, string $invitation_key) { - - if(!in_array($entity, ['invoice', 'credit', 'quote', 'recurring_invoice'])) + if (!in_array($entity, ['invoice', 'credit', 'quote', 'recurring_invoice'])) { return response()->json(['message' => 'Invalid resource request']); + } $is_silent = 'false'; @@ -86,38 +85,37 @@ class InvitationController extends Controller ->with('contact.client') ->firstOrFail(); - if($invitation->{$entity}->is_deleted) + if ($invitation->{$entity}->is_deleted) { return $this->render('generic.not_available', ['account' => $invitation->company->account, 'company' => $invitation->company]); + } /* 12/01/2022 Clean up an edge case where if the contact is trashed, restore if a invitation comes back. */ - if($invitation->contact->trashed()) + if ($invitation->contact->trashed()) { $invitation->contact->restore(); + } /* Return early if we have the correct client_hash embedded */ $client_contact = $invitation->contact; - if(empty($client_contact->email)) - $client_contact->email = Str::random(15) . "@example.com"; $client_contact->save(); + if (empty($client_contact->email)) { + $client_contact->email = Str::random(15) . "@example.com"; + } $client_contact->save(); if (request()->has('client_hash') && request()->input('client_hash') == $invitation->contact->client->client_hash) { request()->session()->invalidate(); auth()->guard('contact')->loginUsingId($client_contact->id, true); - } elseif ((bool) $invitation->contact->client->getSetting('enable_client_portal_password') !== false) { - //if no contact password has been set - allow user to set password - then continue to view entity - if(empty($invitation->contact->password)){ - - return $this->render('view_entity.set_password', [ - 'root' => 'themes', - 'entity_type' => $entity, - 'invitation_key' => $invitation_key - ]); + if (empty($invitation->contact->password)) { + return $this->render('view_entity.set_password', [ + 'root' => 'themes', + 'entity_type' => $entity, + 'invitation_key' => $invitation_key + ]); } $this->middleware('auth:contact'); return redirect()->route('client.login'); - } else { request()->session()->invalidate(); auth()->guard('contact')->loginUsingId($client_contact->id, true); @@ -127,22 +125,20 @@ class InvitationController extends Controller if (auth()->guard('contact')->user() && ! request()->has('silent') && ! $invitation->viewed_date) { $invitation->markViewed(); - if(!session()->get('is_silent')) + if (!session()->get('is_silent')) { event(new InvitationWasViewed($invitation->{$entity}, $invitation, $invitation->{$entity}->company, Ninja::eventVars())); + } - if(!session()->get('is_silent')) + if (!session()->get('is_silent')) { $this->fireEntityViewedEvent($invitation, $entity); - } - else{ + } + } else { $is_silent = 'true'; return redirect()->route('client.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->{$key}), 'silent' => $is_silent]); - } return redirect()->route('client.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->{$key})]); - - } private function fireEntityViewedEvent($invitation, $entity_string) @@ -165,20 +161,20 @@ class InvitationController extends Controller public function routerForDownload(string $entity, string $invitation_key) { - set_time_limit(45); - if(Ninja::isHosted()) + if (Ninja::isHosted()) { return $this->returnRawPdf($entity, $invitation_key); + } return redirect('client/'.$entity.'/'.$invitation_key.'/download_pdf'); } private function returnRawPdf(string $entity, string $invitation_key) { - - if(!in_array($entity, ['invoice', 'credit', 'quote', 'recurring_invoice'])) + if (!in_array($entity, ['invoice', 'credit', 'quote', 'recurring_invoice'])) { return response()->json(['message' => 'Invalid resource request']); + } $key = $entity.'_id'; @@ -189,8 +185,9 @@ class InvitationController extends Controller ->with('contact.client') ->firstOrFail(); - if(!$invitation) + if (!$invitation) { return response()->json(["message" => "no record found"], 400); + } $file_name = $invitation->{$entity}->numberFormatter().'.pdf'; @@ -198,13 +195,13 @@ class InvitationController extends Controller $headers = ['Content-Type' => 'application/pdf']; - if(request()->input('inline') == 'true') + if (request()->input('inline') == 'true') { $headers = array_merge($headers, ['Content-Disposition' => 'inline']); + } - return response()->streamDownload(function () use($file) { - echo $file; - }, $file_name, $headers); - + return response()->streamDownload(function () use ($file) { + echo $file; + }, $file_name, $headers); } public function routerForIframe(string $entity, string $client_hash, string $invitation_key) @@ -216,13 +213,13 @@ class InvitationController extends Controller $contact = ClientContact::withTrashed()->where('contact_key', $contact_key)->firstOrFail(); $payment = Payment::find($this->decodePrimaryKey($payment_id)); - if($payment->client_id != $contact->client_id) + if ($payment->client_id != $contact->client_id) { abort(403, 'You are not authorized to view this resource'); + } auth()->guard('contact')->loginUsingId($contact->id, true); return redirect()->route('client.payments.show', $payment->hashed_id); - } public function payInvoice(Request $request, string $invitation_key) @@ -232,23 +229,23 @@ class InvitationController extends Controller ->with('contact.client') ->firstOrFail(); - if($invitation->contact->trashed()) + if ($invitation->contact->trashed()) { $invitation->contact->restore(); + } auth()->guard('contact')->loginUsingId($invitation->contact->id, true); $invoice = $invitation->invoice; - if($invoice->partial > 0) + if ($invoice->partial > 0) { $amount = round($invoice->partial, (int)$invoice->client->currency()->precision); - else + } else { $amount = round($invoice->balance, (int)$invoice->client->currency()->precision); + } $gateways = $invitation->contact->client->service()->getPaymentMethods($amount); - if(is_array($gateways) && count($gateways) >=1) - { - + if (is_array($gateways) && count($gateways) >=1) { $data = [ 'company_gateway_id' => $gateways[0]['company_gateway_id'], 'payment_method_id' => $gateways[0]['gateway_type_id'], @@ -265,38 +262,37 @@ class InvitationController extends Controller $entity = 'invoice'; - if($invoice && is_array($gateways) && count($gateways) == 0) + if ($invoice && is_array($gateways) && count($gateways) == 0) { return redirect()->route('client.invoice.show', ['invoice' => $this->encodePrimaryKey($invitation->invoice_id)]); + } abort(404, "Invoice not found"); } public function unsubscribe(Request $request, string $entity, string $invitation_key) { - if($entity == 'invoice'){ + if ($entity == 'invoice') { $invite = InvoiceInvitation::withTrashed()->where('key', $invitation_key)->first(); $invite->contact->send_email = false; $invite->contact->save(); - }elseif($entity == 'quote'){ + } elseif ($entity == 'quote') { $invite = QuoteInvitation::withTrashed()->where('key', $invitation_key)->first(); $invite->contact->send_email = false; $invite->contact->save(); - }elseif($entity == 'credit'){ + } elseif ($entity == 'credit') { $invite = CreditInvitation::withTrashed()->where('key', $invitation_key)->first(); $invite->contact->send_email = false; $invite->contact->save(); - }elseif($entity == 'purchase_order'){ + } elseif ($entity == 'purchase_order') { $invite = PurchaseOrderInvitation::withTrashed()->where('key', $invitation_key)->first(); $invite->contact->send_email = false; $invite->contact->save(); - } - else + } else { return abort(404); + } $data['logo'] = $invite->company->present()->logo(); return $this->render('generic.unsubscribe', $data); - } - } diff --git a/app/Http/Controllers/ClientPortal/InvoiceController.php b/app/Http/Controllers/ClientPortal/InvoiceController.php index d87f56e06d2c..3bfa90b48ac5 100644 --- a/app/Http/Controllers/ClientPortal/InvoiceController.php +++ b/app/Http/Controllers/ClientPortal/InvoiceController.php @@ -20,10 +20,8 @@ use App\Http\Requests\ClientPortal\Invoices\ShowInvoicesRequest; use App\Models\Invoice; use App\Utils\Ninja; use App\Utils\Number; -use App\Utils\TempFile; use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; -use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -227,7 +225,6 @@ class InvoiceController extends Controller $zipFile = new \PhpZip\ZipFile(); try { foreach ($invoices as $invoice) { - //add it to the zip $zipFile->addFromString(basename($invoice->pdf_file_path()), file_get_contents($invoice->pdf_file_path(null, 'url', true))); } @@ -238,7 +235,7 @@ class InvoiceController extends Controller $zipFile->saveAsFile($filepath) // save the archive to a file ->close(); // close archive - return response()->download($filepath, $filename)->deleteFileAfterSend(true); + return response()->download($filepath, $filename)->deleteFileAfterSend(true); } catch (\PhpZip\Exception\ZipException $e) { // handle exception } finally { diff --git a/app/Http/Controllers/ClientPortal/NinjaPlanController.php b/app/Http/Controllers/ClientPortal/NinjaPlanController.php index 9e040640dfa5..d3d275b92a9f 100644 --- a/app/Http/Controllers/ClientPortal/NinjaPlanController.php +++ b/app/Http/Controllers/ClientPortal/NinjaPlanController.php @@ -15,7 +15,6 @@ namespace App\Http\Controllers\ClientPortal; use App\DataMapper\Analytics\TrialStarted; use App\Factory\RecurringInvoiceFactory; use App\Http\Controllers\Controller; -use App\Http\Requests\ClientPortal\Uploads\StoreUploadRequest; use App\Libraries\MultiDB; use App\Models\Account; use App\Models\ClientContact; @@ -28,11 +27,8 @@ use App\Models\Subscription; use App\Notifications\Ninja\NewAccountNotification; use App\Repositories\RecurringInvoiceRepository; use App\Repositories\SubscriptionRepository; -use App\Utils\Ninja; use App\Utils\Traits\MakesHash; -use Illuminate\Contracts\Routing\ResponseFactory; use Illuminate\Http\Request; -use Illuminate\Http\Response; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Auth; use Turbo124\Beacon\Facades\LightLogs; @@ -184,7 +180,7 @@ class NinjaPlanController extends Controller $old_recurring = RecurringInvoice::where('company_id', config('ninja.ninja_default_company_id'))->where('client_id', $client->id)->first(); - if($old_recurring) { + if ($old_recurring) { $old_recurring->service()->stop()->save(); $old_recurring_repo = new RecurringInvoiceRepository(); $old_recurring_repo->archive($old_recurring); @@ -207,7 +203,6 @@ class NinjaPlanController extends Controller public function plan() { - // return $this->trial(); //harvest the current plan $data = []; diff --git a/app/Http/Controllers/ClientPortal/PaymentController.php b/app/Http/Controllers/ClientPortal/PaymentController.php index dd7405278f17..3307eb7d2eb7 100644 --- a/app/Http/Controllers/ClientPortal/PaymentController.php +++ b/app/Http/Controllers/ClientPortal/PaymentController.php @@ -12,27 +12,20 @@ namespace App\Http\Controllers\ClientPortal; -use App\Exceptions\PaymentFailed; use App\Factory\PaymentFactory; use App\Http\Controllers\Controller; use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; -use App\Jobs\Invoice\InjectSignature; -use App\Jobs\Util\SystemLogger; use App\Models\CompanyGateway; use App\Models\Invoice; use App\Models\Payment; use App\Models\PaymentHash; -use App\Models\SystemLog; use App\Services\ClientPortal\InstantPayment; use App\Services\Subscription\SubscriptionService; -use App\Utils\Number; use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; use Illuminate\View\View; /** @@ -90,15 +83,13 @@ class PaymentController extends Controller public function response(PaymentResponseRequest $request) { - $gateway = CompanyGateway::findOrFail($request->input('company_gateway_id')); $payment_hash = PaymentHash::where('hash', $request->payment_hash)->firstOrFail(); $invoice = Invoice::with('client')->find($payment_hash->fee_invoice_id); $client = $invoice ? $invoice->client : auth()->guard('contact')->user()->client; // 09-07-2022 catch duplicate responses for invoices that already paid here. - if($invoice && $invoice->status_id == Invoice::STATUS_PAID){ - + if ($invoice && $invoice->status_id == Invoice::STATUS_PAID) { $data = [ 'invoice' => $invoice, 'key' => false, @@ -110,15 +101,14 @@ class PaymentController extends Controller } return $this->render('invoices.show', $data); - } - return $gateway - ->driver($client) - ->setPaymentMethod($request->input('payment_method_id')) - ->setPaymentHash($payment_hash) - ->checkRequirements() - ->processPaymentResponse($request); + return $gateway + ->driver($client) + ->setPaymentMethod($request->input('payment_method_id')) + ->setPaymentHash($payment_hash) + ->checkRequirements() + ->processPaymentResponse($request); } /** @@ -150,15 +140,14 @@ class PaymentController extends Controller $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($payment_hash->invoices(), 'invoice_id'))); - $invoices->each(function ($i){ + $invoices->each(function ($i) { $i->is_proforma = false; $i->saveQuietly(); }); event('eloquent.created: App\Models\Payment', $payment); - if($invoices->sum('balance') > 0){ - + if ($invoices->sum('balance') > 0) { $invoice = $invoices->first(); $invoice->service()->touchPdf(true); diff --git a/app/Http/Controllers/ClientPortal/PaymentMethodController.php b/app/Http/Controllers/ClientPortal/PaymentMethodController.php index de3c718928a9..f281816b65e2 100644 --- a/app/Http/Controllers/ClientPortal/PaymentMethodController.php +++ b/app/Http/Controllers/ClientPortal/PaymentMethodController.php @@ -23,7 +23,6 @@ use App\Utils\Traits\MakesDates; use Exception; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; -use Illuminate\Support\Facades\Log; use Illuminate\View\View; class PaymentMethodController extends Controller diff --git a/app/Http/Controllers/ClientPortal/QuoteController.php b/app/Http/Controllers/ClientPortal/QuoteController.php index 2bde3a57816c..ca99bdfe64d0 100644 --- a/app/Http/Controllers/ClientPortal/QuoteController.php +++ b/app/Http/Controllers/ClientPortal/QuoteController.php @@ -13,7 +13,6 @@ namespace App\Http\Controllers\ClientPortal; use App\Events\Misc\InvitationWasViewed; -use App\Events\Quote\QuoteWasApproved; use App\Events\Quote\QuoteWasViewed; use App\Http\Controllers\Controller; use App\Http\Requests\ClientPortal\Quotes\ProcessQuotesInBulkRequest; @@ -22,11 +21,9 @@ use App\Http\Requests\ClientPortal\Quotes\ShowQuotesRequest; use App\Jobs\Invoice\InjectSignature; use App\Models\Quote; use App\Utils\Ninja; -use App\Utils\TempFile; use App\Utils\Traits\MakesHash; use Illuminate\Contracts\View\Factory; use Illuminate\Http\Request; -use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Storage; use Illuminate\View\View; use Symfony\Component\HttpFoundation\BinaryFileResponse; @@ -81,7 +78,7 @@ class QuoteController extends Controller public function bulk(ProcessQuotesInBulkRequest $request) { $transformed_ids = $this->transformKeys($request->quotes); -nlog(request()->all()); + nlog(request()->all()); if ($request->action == 'download') { return $this->downloadQuotes((array) $transformed_ids); @@ -145,7 +142,6 @@ nlog(request()->all()); $zipFile = new \PhpZip\ZipFile(); try { foreach ($quotes as $quote) { - //add it to the zip $zipFile->addFromString(basename($quote->pdf_file_path()), file_get_contents($quote->pdf_file_path(null, 'url', true))); } @@ -156,7 +152,7 @@ nlog(request()->all()); $zipFile->saveAsFile($filepath) // save the archive to a file ->close(); // close archive - return response()->download($filepath, $filename)->deleteFileAfterSend(true); + return response()->download($filepath, $filename)->deleteFileAfterSend(true); } catch (\PhpZip\Exception\ZipException $e) { // handle exception } finally { @@ -181,12 +177,9 @@ nlog(request()->all()); if ($process) { foreach ($quotes as $quote) { - - - if(request()->has('user_input') && strlen(request()->input('user_input')) > 2) { - + if (request()->has('user_input') && strlen(request()->input('user_input')) > 2) { $quote->public_notes .= $quote->public_notes . "\n" . request()->input('user_input'); - $quote->saveQuietly(); + $quote->saveQuietly(); } $quote->service()->approve(auth()->user())->save(); @@ -197,8 +190,7 @@ nlog(request()->all()); } if (count($ids) == 1) { - - //forward client to the invoice if it exists + //forward client to the invoice if it exists if ($quote->invoice()->exists()) { return redirect()->route('client.invoice.show', $quote->invoice->hashed_id); } diff --git a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php index 7a26b9850698..fdf5e92cb78f 100644 --- a/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php +++ b/app/Http/Controllers/ClientPortal/RecurringInvoiceController.php @@ -20,7 +20,6 @@ use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Mail\RecurringInvoice\ClientContactRequestCancellationObject; use App\Models\RecurringInvoice; -use App\Notifications\ClientContactRequestCancellation; use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; use App\Utils\Traits\Notifications\UserNotifies; @@ -51,7 +50,7 @@ class RecurringInvoiceController extends Controller * * @param ShowRecurringInvoiceRequest $request * @param RecurringInvoice $recurring_invoice - * + * * @return Factory|View */ public function show(ShowRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice) @@ -63,17 +62,15 @@ class RecurringInvoiceController extends Controller /** * Handle the request cancellation notification - * + * * @param RequestCancellationRequest $request [description] * @param RecurringInvoice $recurring_invoice [description] - * + * * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse */ public function requestCancellation(RequestCancellationRequest $request, RecurringInvoice $recurring_invoice) { - if ($recurring_invoice->subscription?->allow_cancellation) { - $nmo = new NinjaMailerObject; $nmo->mailable = (new NinjaMailer((new ClientContactRequestCancellationObject($recurring_invoice, auth()->user(), false))->build())); $nmo->company = $recurring_invoice->company; diff --git a/app/Http/Controllers/ClientPortal/SubscriptionController.php b/app/Http/Controllers/ClientPortal/SubscriptionController.php index 393a7ed63e91..73a32f6b47de 100644 --- a/app/Http/Controllers/ClientPortal/SubscriptionController.php +++ b/app/Http/Controllers/ClientPortal/SubscriptionController.php @@ -16,7 +16,6 @@ use App\Http\Controllers\Controller; use App\Http\Requests\ClientPortal\RecurringInvoices\ShowRecurringInvoiceRequest; use App\Models\RecurringInvoice; use App\Utils\Ninja; -use Illuminate\Http\Request; class SubscriptionController extends Controller { @@ -50,9 +49,8 @@ class SubscriptionController extends Controller public function show(ShowRecurringInvoiceRequest $request, RecurringInvoice $recurring_invoice) { return $this->render('subscriptions.show', [ - 'invoice' => $recurring_invoice->load('invoices','subscription'), + 'invoice' => $recurring_invoice->load('invoices', 'subscription'), 'subscription' => $recurring_invoice->subscription ]); } - } diff --git a/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php b/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php index 6fd26bbba7ac..f06258104ea4 100644 --- a/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php +++ b/app/Http/Controllers/ClientPortal/SubscriptionPlanSwitchController.php @@ -16,8 +16,6 @@ use App\Http\Controllers\Controller; use App\Http\Requests\ClientPortal\Subscriptions\ShowPlanSwitchRequest; use App\Models\RecurringInvoice; use App\Models\Subscription; -use Illuminate\Http\Request; -use Illuminate\Support\Str; class SubscriptionPlanSwitchController extends Controller { @@ -31,7 +29,6 @@ class SubscriptionPlanSwitchController extends Controller */ public function index(ShowPlanSwitchRequest $request, RecurringInvoice $recurring_invoice, Subscription $target) { - $amount = $recurring_invoice->subscription ->service() ->calculateUpgradePriceV2($recurring_invoice, $target); @@ -45,7 +42,7 @@ class SubscriptionPlanSwitchController extends Controller render('subscriptions.denied'); } - $amount = max(0,$amount); + $amount = max(0, $amount); return render('subscriptions.switch', [ 'subscription' => $recurring_invoice->subscription, @@ -53,7 +50,6 @@ class SubscriptionPlanSwitchController extends Controller 'target' => $target, 'amount' => $amount, ]); - } public function not_availabe() diff --git a/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php b/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php index c13a1782ae60..b8d8f1fe395c 100644 --- a/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php +++ b/app/Http/Controllers/ClientPortal/SubscriptionPurchaseController.php @@ -17,7 +17,6 @@ use App\Models\Subscription; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class SubscriptionPurchaseController extends Controller @@ -53,13 +52,11 @@ class SubscriptionPurchaseController extends Controller $this->setLocale($request->query('locale')); } - if(!auth()->guard('contact')->check() && $subscription->registration_required && $subscription->company->client_can_register) { - - session()->put('url.intended', route('client.subscription.upgrade',['subscription' => $subscription->hashed_id])); + if (!auth()->guard('contact')->check() && $subscription->registration_required && $subscription->company->client_can_register) { + session()->put('url.intended', route('client.subscription.upgrade', ['subscription' => $subscription->hashed_id])); return redirect()->route('client.register', ['company_key' => $subscription->company->company_key]); - } - elseif(!auth()->guard('contact')->check() && $subscription->registration_required && ! $subscription->company->client_can_register) { + } elseif (!auth()->guard('contact')->check() && $subscription->registration_required && ! $subscription->company->client_can_register) { return render('generic.subscription_blocked', ['account' => $subscription->company->account, 'company' => $subscription->company]); } @@ -85,7 +82,4 @@ class SubscriptionPurchaseController extends Controller App::setLocale($record->locale); } } - - - } diff --git a/app/Http/Controllers/ClientPortal/SwitchCompanyController.php b/app/Http/Controllers/ClientPortal/SwitchCompanyController.php index cd1cddc2b9e1..8f6dc09366dd 100644 --- a/app/Http/Controllers/ClientPortal/SwitchCompanyController.php +++ b/app/Http/Controllers/ClientPortal/SwitchCompanyController.php @@ -15,7 +15,6 @@ namespace App\Http\Controllers\ClientPortal; use App\Http\Controllers\Controller; use App\Models\ClientContact; use App\Utils\Traits\MakesHash; -use Illuminate\Support\Facades\Auth; class SwitchCompanyController extends Controller { diff --git a/app/Http/Controllers/ClientStatementController.php b/app/Http/Controllers/ClientStatementController.php index 846fbe5dea41..4b41d43ba361 100644 --- a/app/Http/Controllers/ClientStatementController.php +++ b/app/Http/Controllers/ClientStatementController.php @@ -12,14 +12,6 @@ namespace App\Http\Controllers; use App\Http\Requests\Statements\CreateStatementRequest; -use App\Models\Design; -use App\Models\InvoiceInvitation; -use App\Services\PdfMaker\Design as PdfDesignModel; -use App\Services\PdfMaker\Design as PdfMakerDesign; -use App\Services\PdfMaker\PdfMaker as PdfMakerService; -use App\Utils\HostedPDF\NinjaPdf; -use App\Utils\HtmlEngine; -use App\Utils\PhantomJS\Phantom; use App\Utils\Traits\MakesHash; use App\Utils\Traits\Pdf\PdfMaker; @@ -110,15 +102,18 @@ class ClientStatementController extends BaseController { $send_email = false; - if($request->has('send_email') && $request->send_email == 'true') + if ($request->has('send_email') && $request->send_email == 'true') { $send_email = true; + } $pdf = $request->client()->service()->statement( - $request->only(['start_date', 'end_date', 'show_payments_table', 'show_aging_table', 'status']), $send_email + $request->only(['start_date', 'end_date', 'show_payments_table', 'show_aging_table', 'status']), + $send_email ); - if($send_email) + if ($send_email) { return response()->json(['message' => ctrans('texts.email_queued')], 200); + } if ($pdf) { return response()->streamDownload(function () use ($pdf) { diff --git a/app/Http/Controllers/CompanyController.php b/app/Http/Controllers/CompanyController.php index 8253f977e058..d5575e4e9753 100644 --- a/app/Http/Controllers/CompanyController.php +++ b/app/Http/Controllers/CompanyController.php @@ -13,8 +13,6 @@ namespace App\Http\Controllers; use App\DataMapper\Analytics\AccountDeleted; use App\DataMapper\CompanySettings; -use App\DataMapper\DefaultSettings; -use App\Factory\CompanyFactory; use App\Http\Requests\Company\CreateCompanyRequest; use App\Http\Requests\Company\DefaultCompanyRequest; use App\Http\Requests\Company\DestroyCompanyRequest; @@ -29,7 +27,6 @@ use App\Jobs\Company\CreateCompanyTaskStatuses; use App\Jobs\Company\CreateCompanyToken; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; -use App\Jobs\Ninja\RefundCancelledAccount; use App\Mail\Company\CompanyDeleted; use App\Models\Account; use App\Models\Company; @@ -42,9 +39,7 @@ use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; use App\Utils\Traits\Uploadable; use Illuminate\Foundation\Bus\DispatchesJobs; -use Illuminate\Http\Request; use Illuminate\Http\Response; -use Illuminate\Support\Facades\Auth; use Turbo124\Beacon\Facades\LightLogs; /** diff --git a/app/Http/Controllers/CompanyGatewayController.php b/app/Http/Controllers/CompanyGatewayController.php index 72ab74d2de06..b641344be700 100644 --- a/app/Http/Controllers/CompanyGatewayController.php +++ b/app/Http/Controllers/CompanyGatewayController.php @@ -29,7 +29,6 @@ use App\Repositories\CompanyRepository; use App\Transformers\CompanyGatewayTransformer; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Bus\DispatchesJobs; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** @@ -506,8 +505,8 @@ class CompanyGatewayController extends BaseController ->company() ->cursor() ->each(function ($company_gateway, $key) use ($action) { - $this->company_repo->{$action}($company_gateway); - }); + $this->company_repo->{$action}($company_gateway); + }); return $this->listResponse(CompanyGateway::withTrashed()->company()->whereIn('id', $request->ids)); } diff --git a/app/Http/Controllers/ConnectedAccountController.php b/app/Http/Controllers/ConnectedAccountController.php index 99a7d14b8bc0..94a75fccf9ec 100644 --- a/app/Http/Controllers/ConnectedAccountController.php +++ b/app/Http/Controllers/ConnectedAccountController.php @@ -13,15 +13,12 @@ namespace App\Http\Controllers; use App\Libraries\MultiDB; use App\Libraries\OAuth\Providers\Google; -use App\Models\CompanyUser; use App\Models\User; -use App\Transformers\CompanyUserTransformer; use App\Transformers\UserTransformer; use App\Utils\Traits\User\LoginCache; use Google_Client; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; use Microsoft\Graph\Model; class ConnectedAccountController extends BaseController @@ -95,8 +92,9 @@ class ConnectedAccountController extends BaseController { nlog($request->all()); - if(!$request->has('access_token')) + if (!$request->has('access_token')) { return response()->json(['message' => 'No access_token parameter found!'], 400); + } $graph = new \Microsoft\Graph\Graph(); $graph->setAccessToken($request->input('access_token')); @@ -105,15 +103,15 @@ class ConnectedAccountController extends BaseController ->setReturnType(Model\User::class) ->execute(); - if($user){ - + if ($user) { $email = $user->getMail() ?: $user->getUserPrincipalName(); nlog("microsoft"); nlog($email); - if(auth()->user()->email != $email && MultiDB::checkUserEmailExists($email)) + if (auth()->user()->email != $email && MultiDB::checkUserEmailExists($email)) { return response()->json(['message' => ctrans('texts.email_already_register')], 400); + } $connected_account = [ 'email' => $email, @@ -129,14 +127,12 @@ class ConnectedAccountController extends BaseController $this->setLoginCache(auth()->user()); return $this->itemResponse(auth()->user()); - } return response() ->json(['message' => ctrans('texts.invalid_credentials')], 401) ->header('X-App-Version', config('ninja.app_version')) ->header('X-Api-Version', config('ninja.minimum_client_version')); - } private function handleGoogleOauth() diff --git a/app/Http/Controllers/Contact/LoginController.php b/app/Http/Controllers/Contact/LoginController.php index efb9a6dce954..3ecc364402ba 100644 --- a/app/Http/Controllers/Contact/LoginController.php +++ b/app/Http/Controllers/Contact/LoginController.php @@ -13,8 +13,6 @@ namespace App\Http\Controllers\Contact; use App\Http\Controllers\BaseController; use App\Http\Controllers\Controller; -use App\Jobs\Account\CreateAccount; -use App\Libraries\MultiDB; use App\Libraries\OAuth\OAuth; use App\Models\ClientContact; use App\Models\User; diff --git a/app/Http/Controllers/CreditController.php b/app/Http/Controllers/CreditController.php index 1964deb2b583..7efebce877b2 100644 --- a/app/Http/Controllers/CreditController.php +++ b/app/Http/Controllers/CreditController.php @@ -27,8 +27,6 @@ use App\Http\Requests\Credit\UpdateCreditRequest; use App\Http\Requests\Credit\UploadCreditRequest; use App\Jobs\Credit\ZipCredits; use App\Jobs\Entity\EmailEntity; -use App\Jobs\Invoice\EmailCredit; -use App\Jobs\Invoice\ZipInvoices; use App\Models\Account; use App\Models\Client; use App\Models\Credit; @@ -37,7 +35,6 @@ use App\Repositories\CreditRepository; use App\Services\PdfMaker\PdfMerge; use App\Transformers\CreditTransformer; use App\Utils\Ninja; -use App\Utils\TempFile; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; use Illuminate\Http\Response; @@ -499,8 +496,9 @@ class CreditController extends BaseController { $action = $request->input('action'); - if(Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) + if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) { return response(['message' => 'Please verify your account to send emails.'], 400); + } $credits = Credit::withTrashed() ->whereIn('id', $request->ids) @@ -529,18 +527,16 @@ class CreditController extends BaseController return response()->json(['message' => ctrans('texts.sent_message')], 200); } - if($action == 'bulk_print' && auth()->user()->can('view', $credits->first())){ - - $paths = $credits->map(function ($credit){ + if ($action == 'bulk_print' && auth()->user()->can('view', $credits->first())) { + $paths = $credits->map(function ($credit) { return $credit->service()->getCreditPdf($credit->invitations->first()); }); $merge = (new PdfMerge($paths->toArray()))->run(); - return response()->streamDownload(function () use ($merge) { - echo ($merge); - }, 'print.pdf', ['Content-Type' => 'application/pdf']); - + return response()->streamDownload(function () use ($merge) { + echo($merge); + }, 'print.pdf', ['Content-Type' => 'application/pdf']); } $credits->each(function ($credit, $key) use ($action) { @@ -565,7 +561,7 @@ class CreditController extends BaseController $credit->service()->markPaid()->save(); return $this->itemResponse($credit); - break; + break; case 'clone_to_credit': $credit = CloneCreditFactory::create($credit, auth()->user()->id); @@ -591,7 +587,7 @@ class CreditController extends BaseController return response()->streamDownload(function () use ($file) { echo Storage::get($file); }, basename($file), ['Content-Type' => 'application/pdf']); - break; + break; case 'archive': $this->credit_repository->archive($credit); diff --git a/app/Http/Controllers/DesignController.php b/app/Http/Controllers/DesignController.php index 7a068f687120..677516725b4c 100644 --- a/app/Http/Controllers/DesignController.php +++ b/app/Http/Controllers/DesignController.php @@ -24,7 +24,6 @@ use App\Models\Design; use App\Repositories\DesignRepository; use App\Transformers\DesignTransformer; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Str; diff --git a/app/Http/Controllers/DocumentController.php b/app/Http/Controllers/DocumentController.php index 8efa4966f124..20263da9d34b 100644 --- a/app/Http/Controllers/DocumentController.php +++ b/app/Http/Controllers/DocumentController.php @@ -13,7 +13,6 @@ use App\Models\Document; use App\Repositories\DocumentRepository; use App\Transformers\DocumentTransformer; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; use Illuminate\Http\Response; class DocumentController extends BaseController diff --git a/app/Http/Controllers/EmailController.php b/app/Http/Controllers/EmailController.php index d618d8cf0dd9..69be30768391 100644 --- a/app/Http/Controllers/EmailController.php +++ b/app/Http/Controllers/EmailController.php @@ -13,10 +13,8 @@ namespace App\Http\Controllers; use App\Events\Credit\CreditWasEmailed; use App\Events\Quote\QuoteWasEmailed; -use App\Http\Middleware\UserVerified; use App\Http\Requests\Email\SendEmailRequest; use App\Jobs\Entity\EmailEntity; -use App\Jobs\Mail\EntitySentMailer; use App\Jobs\PurchaseOrder\PurchaseOrderEmail; use App\Models\Credit; use App\Models\Invoice; @@ -135,15 +133,15 @@ class EmailController extends BaseController $mo->entity_string = $entity; $mo->email_template = $template; - if(Ninja::isHosted() && !$entity_obj->company->account->account_sms_verified) - return response(['message' => 'Please verify your account to send emails.'], 400); + if (Ninja::isHosted() && !$entity_obj->company->account->account_sms_verified) { + return response(['message' => 'Please verify your account to send emails.'], 400); + } - if($entity == 'purchaseOrder' || $entity == 'purchase_order' || $template == 'purchase_order' || $entity == 'App\Models\PurchaseOrder'){ + if ($entity == 'purchaseOrder' || $entity == 'purchase_order' || $template == 'purchase_order' || $entity == 'App\Models\PurchaseOrder') { return $this->sendPurchaseOrder($entity_obj, $data, $template); } $entity_obj->invitations->each(function ($invitation) use ($data, $entity_string, $entity_obj, $template, $mo) { - if (! $invitation->contact->trashed() && $invitation->contact->email) { $entity_obj->service()->markSent()->save(); @@ -151,7 +149,6 @@ class EmailController extends BaseController // MailEntity::dispatch($invitation, $invitation->company->db, $mo); } - }); $entity_obj = $entity_obj->fresh(); @@ -196,7 +193,6 @@ class EmailController extends BaseController private function sendPurchaseOrder($entity_obj, $data, $template) { - $this->entity_type = PurchaseOrder::class; $this->entity_transformer = PurchaseOrderTransformer::class; @@ -206,6 +202,5 @@ class EmailController extends BaseController PurchaseOrderEmail::dispatch($entity_obj, $entity_obj->company, $data); return $this->itemResponse($entity_obj); - } } diff --git a/app/Http/Controllers/ExpenseController.php b/app/Http/Controllers/ExpenseController.php index 5e17dbdd6220..5b88ab9ea3ff 100644 --- a/app/Http/Controllers/ExpenseController.php +++ b/app/Http/Controllers/ExpenseController.php @@ -31,7 +31,6 @@ use App\Utils\Traits\BulkOptions; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; use App\Utils\Traits\Uploadable; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** diff --git a/app/Http/Controllers/FilterController.php b/app/Http/Controllers/FilterController.php index e957298d8642..270a2c4e1d81 100644 --- a/app/Http/Controllers/FilterController.php +++ b/app/Http/Controllers/FilterController.php @@ -11,9 +11,7 @@ namespace App\Http\Controllers; -use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Http\Request; -use Illuminate\Http\Response; class FilterController extends BaseController { @@ -33,7 +31,6 @@ class FilterController extends BaseController $entity_filters = []; switch ($entity) { - case 'invoice': $entity_filters = ['bulk_download', 'mark_paid', 'mark_sent', 'download', 'cancel', 'email']; break; @@ -53,7 +50,6 @@ class FilterController extends BaseController case 'recurring_invoice': $entity_filters = ['bulk_download', 'start', 'stop', 'email']; break; - } return response()->json(array_merge($this->base_filters, $entity_filters), 200); diff --git a/app/Http/Controllers/Gateways/Mollie3dsController.php b/app/Http/Controllers/Gateways/Mollie3dsController.php index 15bdc60261ac..3eab60b6a537 100644 --- a/app/Http/Controllers/Gateways/Mollie3dsController.php +++ b/app/Http/Controllers/Gateways/Mollie3dsController.php @@ -14,7 +14,6 @@ namespace App\Http\Controllers\Gateways; use App\Http\Controllers\Controller; use App\Http\Requests\Gateways\Mollie\Mollie3dsRequest; -use App\Models\PaymentHash; class Mollie3dsController extends Controller { diff --git a/app/Http/Controllers/GroupSettingController.php b/app/Http/Controllers/GroupSettingController.php index 4c9ee3cbd351..bafcdd17c728 100644 --- a/app/Http/Controllers/GroupSettingController.php +++ b/app/Http/Controllers/GroupSettingController.php @@ -27,7 +27,6 @@ use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; use App\Utils\Traits\Uploadable; use Illuminate\Foundation\Bus\DispatchesJobs; -use Illuminate\Http\Request; use Illuminate\Http\Response; class GroupSettingController extends BaseController diff --git a/app/Http/Controllers/HostedMigrationController.php b/app/Http/Controllers/HostedMigrationController.php index 5ef26c869f67..479b8d0d137a 100644 --- a/app/Http/Controllers/HostedMigrationController.php +++ b/app/Http/Controllers/HostedMigrationController.php @@ -13,12 +13,9 @@ namespace App\Http\Controllers; use App\Jobs\Account\CreateAccount; use App\Libraries\MultiDB; -use App\Models\Client; -use App\Models\ClientContact; use App\Models\Company; use App\Models\CompanyToken; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Artisan; class HostedMigrationController extends Controller { diff --git a/app/Http/Controllers/ImportController.php b/app/Http/Controllers/ImportController.php index 3f19741c1407..4d0634265176 100644 --- a/app/Http/Controllers/ImportController.php +++ b/app/Http/Controllers/ImportController.php @@ -159,14 +159,15 @@ class ImportController extends Controller public function detectDelimiter($csvfile) { - $delimiters = array(',', '.', ';'); + $delimiters = [',', '.', ';']; $bestDelimiter = ' '; $count = 0; - foreach ($delimiters as $delimiter) + foreach ($delimiters as $delimiter) { if (substr_count($csvfile, $delimiter) > $count) { $count = substr_count($csvfile, $delimiter); $bestDelimiter = $delimiter; } + } return $bestDelimiter; } } diff --git a/app/Http/Controllers/ImportJsonController.php b/app/Http/Controllers/ImportJsonController.php index 62ac13e7db24..309e70066bfe 100644 --- a/app/Http/Controllers/ImportJsonController.php +++ b/app/Http/Controllers/ImportJsonController.php @@ -11,17 +11,11 @@ namespace App\Http\Controllers; -use App\Exceptions\NonExistingMigrationFile; use App\Http\Requests\Import\ImportJsonRequest; -use App\Jobs\Company\CompanyExport; use App\Jobs\Company\CompanyImport; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use Illuminate\Http\Response; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\Storage; -use Illuminate\Support\Str; -use ZipArchive; class ImportJsonController extends BaseController { diff --git a/app/Http/Controllers/InAppPurchase/AppleController.php b/app/Http/Controllers/InAppPurchase/AppleController.php index f4e0bfd39190..8f3f385c7545 100644 --- a/app/Http/Controllers/InAppPurchase/AppleController.php +++ b/app/Http/Controllers/InAppPurchase/AppleController.php @@ -58,7 +58,6 @@ class AppleController extends BaseController */ public function confirm_purchase(Request $request) { - //store transaction_id in accounts table for future reference. } diff --git a/app/Http/Controllers/InvoiceController.php b/app/Http/Controllers/InvoiceController.php index f8214c1a134d..fb7cde006ec1 100644 --- a/app/Http/Controllers/InvoiceController.php +++ b/app/Http/Controllers/InvoiceController.php @@ -29,13 +29,11 @@ use App\Http\Requests\Invoice\UpdateInvoiceRequest; use App\Http\Requests\Invoice\UpdateReminderRequest; use App\Http\Requests\Invoice\UploadInvoiceRequest; use App\Jobs\Cron\AutoBill; -use App\Jobs\Entity\EmailEntity; use App\Jobs\Invoice\BulkInvoiceJob; use App\Jobs\Invoice\StoreInvoice; use App\Jobs\Invoice\UpdateReminders; use App\Jobs\Invoice\ZipInvoices; use App\Jobs\Ninja\TransactionLog; -use App\Jobs\Util\UnlinkFile; use App\Models\Account; use App\Models\Client; use App\Models\Invoice; @@ -46,12 +44,10 @@ use App\Services\PdfMaker\PdfMerge; use App\Transformers\InvoiceTransformer; use App\Transformers\QuoteTransformer; use App\Utils\Ninja; -use App\Utils\TempFile; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; use Illuminate\Http\Request; use Illuminate\Http\Response; -use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Storage; /** @@ -536,8 +532,9 @@ class InvoiceController extends BaseController $ids = $request->input('ids'); - if(Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) + if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) { return response(['message' => 'Please verify your account to send emails.'], 400); + } $invoices = Invoice::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get(); @@ -563,28 +560,24 @@ class InvoiceController extends BaseController return response()->json(['message' => ctrans('texts.sent_message')], 200); } - if($action == 'download' && $invoices->count() >=1 && auth()->user()->can('view', $invoices->first())) { - - $file = $invoices->first()->service()->getInvoicePdf(); - - return response()->streamDownload(function () use ($file) { - echo Storage::get($file); - }, basename($file), ['Content-Type' => 'application/pdf']); + if ($action == 'download' && $invoices->count() >=1 && auth()->user()->can('view', $invoices->first())) { + $file = $invoices->first()->service()->getInvoicePdf(); + return response()->streamDownload(function () use ($file) { + echo Storage::get($file); + }, basename($file), ['Content-Type' => 'application/pdf']); } - if($action == 'bulk_print' && auth()->user()->can('view', $invoices->first())){ - - $paths = $invoices->map(function ($invoice){ + if ($action == 'bulk_print' && auth()->user()->can('view', $invoices->first())) { + $paths = $invoices->map(function ($invoice) { return $invoice->service()->getInvoicePdf(); }); $merge = (new PdfMerge($paths->toArray()))->run(); - return response()->streamDownload(function () use ($merge) { - echo ($merge); - }, 'print.pdf', ['Content-Type' => 'application/pdf']); - + return response()->streamDownload(function () use ($merge) { + echo($merge); + }, 'print.pdf', ['Content-Type' => 'application/pdf']); } /* diff --git a/app/Http/Controllers/LicenseController.php b/app/Http/Controllers/LicenseController.php index 0e6916679211..88e04574d928 100644 --- a/app/Http/Controllers/LicenseController.php +++ b/app/Http/Controllers/LicenseController.php @@ -14,7 +14,6 @@ namespace App\Http\Controllers; use App\Models\Account; use App\Utils\CurlUtils; use Carbon\Carbon; -use Illuminate\Http\Request; use Illuminate\Http\Response; use stdClass; diff --git a/app/Http/Controllers/LogoutController.php b/app/Http/Controllers/LogoutController.php index 9007888b70a4..2889b777d0dd 100644 --- a/app/Http/Controllers/LogoutController.php +++ b/app/Http/Controllers/LogoutController.php @@ -14,8 +14,6 @@ namespace App\Http\Controllers; use App\Models\CompanyToken; use Illuminate\Http\Request; use Illuminate\Http\Response; -use stdClass; -use Symfony\Component\HttpFoundation\StreamedResponse; class LogoutController extends BaseController { diff --git a/app/Http/Controllers/OneTimeTokenController.php b/app/Http/Controllers/OneTimeTokenController.php index 6362287e1444..a271fc7b0b3e 100644 --- a/app/Http/Controllers/OneTimeTokenController.php +++ b/app/Http/Controllers/OneTimeTokenController.php @@ -14,7 +14,6 @@ namespace App\Http\Controllers; use App\Http\Requests\OneTimeToken\OneTimeRouterRequest; use App\Http\Requests\OneTimeToken\OneTimeTokenRequest; use App\Models\Company; -use App\Models\CompanyUser; use App\Models\User; use Illuminate\Http\Response; use Illuminate\Support\Facades\Auth; diff --git a/app/Http/Controllers/OpenAPI/BankTransactionRule.php b/app/Http/Controllers/OpenAPI/BankTransactionRule.php index 522b1764b265..fa62eb3a39ea 100644 --- a/app/Http/Controllers/OpenAPI/BankTransactionRule.php +++ b/app/Http/Controllers/OpenAPI/BankTransactionRule.php @@ -22,4 +22,4 @@ * @OA\Property(property="vendor_id", type="string", example="AS3df3A", description="The vendor hashed id"), * @OA\Property(property="category_id", type="string", example="AS3df3A", description="The category hashed id"), * ) - */ \ No newline at end of file + */ diff --git a/app/Http/Controllers/PaymentController.php b/app/Http/Controllers/PaymentController.php index 5db41cfb45b1..e6bc57408d6d 100644 --- a/app/Http/Controllers/PaymentController.php +++ b/app/Http/Controllers/PaymentController.php @@ -584,7 +584,7 @@ class PaymentController extends BaseController { switch ($action) { case 'restore': - $this->payment_repo->restore($payment); + $this->payment_repo->restore($payment); if (! $bulk) { return $this->itemResponse($payment); @@ -592,7 +592,7 @@ class PaymentController extends BaseController break; case 'archive': - $this->payment_repo->archive($payment); + $this->payment_repo->archive($payment); if (! $bulk) { return $this->itemResponse($payment); @@ -600,7 +600,7 @@ class PaymentController extends BaseController // code... break; case 'delete': - $this->payment_repo->delete($payment); + $this->payment_repo->delete($payment); if (! $bulk) { return $this->itemResponse($payment); diff --git a/app/Http/Controllers/PaymentNotificationWebhookController.php b/app/Http/Controllers/PaymentNotificationWebhookController.php index 0a4f1f7e59db..5e9510caa184 100644 --- a/app/Http/Controllers/PaymentNotificationWebhookController.php +++ b/app/Http/Controllers/PaymentNotificationWebhookController.php @@ -13,11 +13,9 @@ namespace App\Http\Controllers; use App\Http\Requests\Payments\PaymentNotificationWebhookRequest; -use App\Libraries\MultiDB; use App\Models\Client; use App\Models\CompanyGateway; use App\Utils\Traits\MakesHash; -use Auth; class PaymentNotificationWebhookController extends Controller { diff --git a/app/Http/Controllers/PaymentWebhookController.php b/app/Http/Controllers/PaymentWebhookController.php index 5c394b44cdf3..4704dc14f5c4 100644 --- a/app/Http/Controllers/PaymentWebhookController.php +++ b/app/Http/Controllers/PaymentWebhookController.php @@ -19,8 +19,9 @@ class PaymentWebhookController extends Controller public function __invoke(PaymentWebhookRequest $request) { //return early if we cannot resolve the company gateway - if(!$request->getCompanyGateway()) + if (!$request->getCompanyGateway()) { return response()->json([], 200); + } return $request ->getCompanyGateway() diff --git a/app/Http/Controllers/PostMarkController.php b/app/Http/Controllers/PostMarkController.php index 4acfb7b8d497..5639d3ccd308 100644 --- a/app/Http/Controllers/PostMarkController.php +++ b/app/Http/Controllers/PostMarkController.php @@ -11,20 +11,8 @@ namespace App\Http\Controllers; -use App\DataMapper\Analytics\Mail\EmailBounce; -use App\DataMapper\Analytics\Mail\EmailSpam; use App\Jobs\PostMark\ProcessPostmarkWebhook; -use App\Jobs\Util\SystemLogger; -use App\Libraries\MultiDB; -use App\Models\CreditInvitation; -use App\Models\InvoiceInvitation; -use App\Models\QuoteInvitation; -use App\Models\RecurringInvoiceInvitation; -use App\Models\SystemLog; -use App\Notifications\Ninja\EmailBounceNotification; -use App\Notifications\Ninja\EmailSpamNotification; use Illuminate\Http\Request; -use Turbo124\Beacon\Facades\LightLogs; /** * Class PostMarkController. diff --git a/app/Http/Controllers/PreviewController.php b/app/Http/Controllers/PreviewController.php index 216f8c0e5704..e69a12e22f3c 100644 --- a/app/Http/Controllers/PreviewController.php +++ b/app/Http/Controllers/PreviewController.php @@ -32,9 +32,9 @@ use App\Repositories\CreditRepository; use App\Repositories\InvoiceRepository; use App\Repositories\QuoteRepository; use App\Repositories\RecurringInvoiceRepository; +use App\Services\PdfMaker\Design; use App\Services\PdfMaker\Design as PdfDesignModel; use App\Services\PdfMaker\Design as PdfMakerDesign; -use App\Services\PdfMaker\Design; use App\Services\PdfMaker\PdfMaker; use App\Utils\HostedPDF\NinjaPdf; use App\Utils\HtmlEngine; @@ -177,8 +177,9 @@ class PreviewController extends BaseController public function design(DesignPreviewRequest $request) { - if(Ninja::isHosted() && $request->getHost() != 'preview.invoicing.co') + if (Ninja::isHosted() && $request->getHost() != 'preview.invoicing.co') { return response()->json(['message' => 'This server cannot handle this request.'], 400); + } $company = auth()->user()->company(); @@ -214,34 +215,34 @@ class PreviewController extends BaseController ->first(); } - if($request->has('client_id')) { + if ($request->has('client_id')) { $client = Client::withTrashed()->find($this->decodePrimaryKey($request->client_id)); - if($request->settings_type == 'client'){ - $client->settings = $request->settings; - $client->save(); - } - + if ($request->settings_type == 'client') { + $client->settings = $request->settings; + $client->save(); + } } - if($request->has('group_id')) { + if ($request->has('group_id')) { $group = GroupSetting::withTrashed()->find($this->decodePrimaryKey($request->group_id)); - if($request->settings_type == 'group'){ - $group->settings = $request->settings; - $group->save(); - } - + if ($request->settings_type == 'group') { + $group->settings = $request->settings; + $group->save(); + } } - if($request->settings_type == 'company'){ + if ($request->settings_type == 'company') { $company->settings = $request->settings; $company->save(); } - if($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice') + if ($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice') { $request->merge(['footer' => $company->settings->invoice_footer]); + } - if($request->has('terms') && !$request->filled('terms') && $request->input('entity') == 'recurring_invoice') + if ($request->has('terms') && !$request->filled('terms') && $request->input('entity') == 'recurring_invoice') { $request->merge(['terms' => $company->settings->invoice_terms]); + } $entity_obj = $repo->save($request->all(), $entity_obj); @@ -302,9 +303,7 @@ class PreviewController extends BaseController nlog($maker->getCompiledHTML()); return $maker->getCompiledHTML(); } - - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog($e->getMessage()); DB::connection(config('database.default'))->rollBack(); @@ -316,36 +315,34 @@ class PreviewController extends BaseController return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true)); } - if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){ + if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') { $pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true)); $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); - $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); + $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); - if ($numbered_pdf) { - $pdf = $numbered_pdf; + if ($numbered_pdf) { + $pdf = $numbered_pdf; + } + + return $pdf; } - return $pdf; - } - $file_path = (new PreviewPdf($maker->getCompiledHTML(true), $company))->handle(); $response = Response::make($file_path, 200); $response->header('Content-Type', 'application/pdf'); return $response; - - - } public function live(PreviewInvoiceRequest $request) { - if(Ninja::isHosted() && $request->getHost() != 'preview.invoicing.co') + if (Ninja::isHosted() && $request->getHost() != 'preview.invoicing.co') { return response()->json(['message' => 'This server cannot handle this request.'], 400); + } $company = auth()->user()->company(); @@ -381,11 +378,13 @@ class PreviewController extends BaseController ->first(); } - if($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice') + if ($request->has('footer') && !$request->filled('footer') && $request->input('entity') == 'recurring_invoice') { $request->merge(['footer' => $company->settings->invoice_footer]); + } - if($request->has('terms') && !$request->filled('terms') && $request->input('entity') == 'recurring_invoice') + if ($request->has('terms') && !$request->filled('terms') && $request->input('entity') == 'recurring_invoice') { $request->merge(['terms' => $company->settings->invoice_terms]); + } $entity_obj = $repo->save($request->all(), $entity_obj); @@ -445,9 +444,7 @@ class PreviewController extends BaseController if (request()->query('html') == 'true') { return $maker->getCompiledHTML(); } - - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog($e->getMessage()); DB::connection(config('database.default'))->rollBack(); @@ -459,21 +456,21 @@ class PreviewController extends BaseController return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true)); } - if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){ + if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') { $pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true)); $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); - $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); + $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); - if ($numbered_pdf) { - $pdf = $numbered_pdf; + if ($numbered_pdf) { + $pdf = $numbered_pdf; + } + + return $pdf; } - return $pdf; - } - $file_path = (new PreviewPdf($maker->getCompiledHTML(true), $company))->handle(); if (Ninja::isHosted()) { diff --git a/app/Http/Controllers/PreviewPurchaseOrderController.php b/app/Http/Controllers/PreviewPurchaseOrderController.php index e22d6feabb18..284286733fc0 100644 --- a/app/Http/Controllers/PreviewPurchaseOrderController.php +++ b/app/Http/Controllers/PreviewPurchaseOrderController.php @@ -12,38 +12,21 @@ namespace App\Http\Controllers; use App\DataMapper\Analytics\LivePreview; -use App\Factory\CreditFactory; -use App\Factory\InvoiceFactory; use App\Factory\PurchaseOrderFactory; -use App\Factory\QuoteFactory; -use App\Factory\RecurringInvoiceFactory; -use App\Http\Requests\Invoice\StoreInvoiceRequest; -use App\Http\Requests\Preview\PreviewInvoiceRequest; use App\Http\Requests\Preview\PreviewPurchaseOrderRequest; use App\Jobs\Util\PreviewPdf; use App\Libraries\MultiDB; use App\Models\Client; -use App\Models\ClientContact; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\InvoiceInvitation; use App\Models\PurchaseOrder; use App\Models\PurchaseOrderInvitation; -use App\Models\Quote; -use App\Models\RecurringInvoice; use App\Models\Vendor; use App\Models\VendorContact; -use App\Repositories\CreditRepository; -use App\Repositories\InvoiceRepository; use App\Repositories\PurchaseOrderRepository; -use App\Repositories\QuoteRepository; -use App\Repositories\RecurringInvoiceRepository; +use App\Services\PdfMaker\Design; use App\Services\PdfMaker\Design as PdfDesignModel; use App\Services\PdfMaker\Design as PdfMakerDesign; -use App\Services\PdfMaker\Design; use App\Services\PdfMaker\PdfMaker; use App\Utils\HostedPDF\NinjaPdf; -use App\Utils\HtmlEngine; use App\Utils\Ninja; use App\Utils\PhantomJS\Phantom; use App\Utils\Traits\MakesHash; @@ -52,7 +35,6 @@ use App\Utils\Traits\Pdf\PageNumbering; use App\Utils\VendorHtmlEngine; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\Response; use Turbo124\Beacon\Facades\LightLogs; @@ -107,7 +89,6 @@ class PreviewPurchaseOrderController extends BaseController ! empty(request()->input('entity')) && ! empty(request()->input('entity_id')) && request()->has('body')) { - $design_object = json_decode(json_encode(request()->input('design'))); if (! is_object($design_object)) { @@ -159,16 +140,16 @@ class PreviewPurchaseOrderController extends BaseController return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true)); } - if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){ + if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') { $pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true)); $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); - if($numbered_pdf) + if ($numbered_pdf) { $pdf = $numbered_pdf; + } return $pdf; - } //else @@ -191,24 +172,22 @@ class PreviewPurchaseOrderController extends BaseController $class = PurchaseOrder::class; try { - DB::connection(config('database.default'))->beginTransaction(); - if($request->has('entity_id')){ - + if ($request->has('entity_id')) { $entity_obj = $class::on(config('database.default')) ->with('vendor.company') ->where('id', $this->decodePrimaryKey($request->input('entity_id'))) ->where('company_id', $company->id) ->withTrashed() ->first(); - } $entity_obj = $repo->save($request->all(), $entity_obj); - if(!$request->has('entity_id')) + if (!$request->has('entity_id')) { $entity_obj->service()->fillDefaults()->save(); + } App::forgetInstance('translator'); $t = app('translator'); @@ -220,8 +199,9 @@ class PreviewPurchaseOrderController extends BaseController $design = \App\Models\Design::find($entity_obj->design_id); /* Catch all in case migration doesn't pass back a valid design */ - if(!$design) + if (!$design) { $design = \App\Models\Design::find(2); + } if ($design->is_custom) { $options = [ @@ -258,11 +238,7 @@ class PreviewPurchaseOrderController extends BaseController if (request()->query('html') == 'true') { return $maker->getCompiledHTML(); } - - - } - catch(\Exception $e){ - + } catch(\Exception $e) { DB::connection(config('database.default'))->rollBack(); return; } @@ -273,13 +249,14 @@ class PreviewPurchaseOrderController extends BaseController return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true)); } - if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){ + if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') { $pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true)); $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); - if($numbered_pdf) + if ($numbered_pdf) { $pdf = $numbered_pdf; + } return $pdf; } @@ -287,19 +264,17 @@ class PreviewPurchaseOrderController extends BaseController $file_path = (new PreviewPdf($maker->getCompiledHTML(true), $company))->handle(); - if(Ninja::isHosted()) - { - LightLogs::create(new LivePreview()) - ->increment() - ->batch(); - } + if (Ninja::isHosted()) { + LightLogs::create(new LivePreview()) + ->increment() + ->batch(); + } $response = Response::make($file_path, 200); $response->header('Content-Type', 'application/pdf'); return $response; - } private function blankEntity() @@ -311,8 +286,9 @@ class PreviewPurchaseOrderController extends BaseController $invitation = PurchaseOrderInvitation::where('company_id', auth()->user()->company()->id)->orderBy('id', 'desc')->first(); /* If we don't have a valid invitation in the system - create a mock using transactions */ - if(!$invitation) + if (!$invitation) { return $this->mockEntity(); + } $design_object = json_decode(json_encode(request()->input('design'))); @@ -351,15 +327,16 @@ class PreviewPurchaseOrderController extends BaseController return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true)); } - if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){ + if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') { $pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true)); $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); - if($numbered_pdf) - $pdf = $numbered_pdf; + if ($numbered_pdf) { + $pdf = $numbered_pdf; + } - return $pdf; + return $pdf; } $file_path = (new PreviewPdf($maker->getCompiledHTML(true), auth()->user()->company()))->handle(); @@ -368,12 +345,10 @@ class PreviewPurchaseOrderController extends BaseController $response->header('Content-Type', 'application/pdf'); return $response; - } private function mockEntity() { - DB::connection(auth()->user()->company()->db)->beginTransaction(); $vendor = Vendor::factory()->create([ @@ -448,15 +423,16 @@ class PreviewPurchaseOrderController extends BaseController return (new Phantom)->convertHtmlToPdf($maker->getCompiledHTML(true)); } - if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){ + if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') { $pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true)); $numbered_pdf = $this->pageNumbering($pdf, auth()->user()->company()); - if($numbered_pdf) - $pdf = $numbered_pdf; + if ($numbered_pdf) { + $pdf = $numbered_pdf; + } - return $pdf; + return $pdf; } $file_path = (new PreviewPdf($maker->getCompiledHTML(true), auth()->user()->company()))->handle(); diff --git a/app/Http/Controllers/ProductController.php b/app/Http/Controllers/ProductController.php index e865b811d582..010d656c951f 100644 --- a/app/Http/Controllers/ProductController.php +++ b/app/Http/Controllers/ProductController.php @@ -26,7 +26,6 @@ use App\Repositories\ProductRepository; use App\Transformers\ProductTransformer; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; -use Illuminate\Http\Request; use Illuminate\Http\Response; class ProductController extends BaseController diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index fb2a5ef316e9..fc921b191242 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -27,7 +27,6 @@ use App\Transformers\ProjectTransformer; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** diff --git a/app/Http/Controllers/PurchaseOrderController.php b/app/Http/Controllers/PurchaseOrderController.php index c77c95a27083..51ae86e9e3ed 100644 --- a/app/Http/Controllers/PurchaseOrderController.php +++ b/app/Http/Controllers/PurchaseOrderController.php @@ -11,7 +11,6 @@ namespace App\Http\Controllers; - use App\Events\PurchaseOrder\PurchaseOrderWasCreated; use App\Events\PurchaseOrder\PurchaseOrderWasUpdated; use App\Factory\PurchaseOrderFactory; @@ -25,16 +24,13 @@ use App\Http\Requests\PurchaseOrder\ShowPurchaseOrderRequest; use App\Http\Requests\PurchaseOrder\StorePurchaseOrderRequest; use App\Http\Requests\PurchaseOrder\UpdatePurchaseOrderRequest; use App\Http\Requests\PurchaseOrder\UploadPurchaseOrderRequest; -use App\Jobs\Invoice\ZipInvoices; use App\Jobs\PurchaseOrder\PurchaseOrderEmail; use App\Jobs\PurchaseOrder\ZipPurchaseOrders; use App\Models\Account; use App\Models\Client; -use App\Models\Expense; use App\Models\PurchaseOrder; use App\Repositories\PurchaseOrderRepository; use App\Services\PdfMaker\PdfMerge; -use App\Transformers\ExpenseTransformer; use App\Transformers\PurchaseOrderTransformer; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; @@ -186,7 +182,6 @@ class PurchaseOrderController extends BaseController */ public function store(StorePurchaseOrderRequest $request) { - $purchase_order = $this->purchase_order_repository->save($request->all(), PurchaseOrderFactory::create(auth()->user()->company()->id, auth()->user()->id)); $purchase_order = $purchase_order->service() @@ -478,13 +473,13 @@ class PurchaseOrderController extends BaseController */ public function bulk(BulkPurchaseOrderRequest $request) { - $action = $request->input('action'); $ids = $request->input('ids'); - if(Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) + if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) { return response(['message' => 'Please verify your account to send emails.'], 400); + } $purchase_orders = PurchaseOrder::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get(); @@ -507,18 +502,16 @@ class PurchaseOrderController extends BaseController return response()->json(['message' => ctrans('texts.sent_message')], 200); } - if($action == 'bulk_print' && auth()->user()->can('view', $purchase_orders->first())){ - - $paths = $purchase_orders->map(function ($purchase_order){ + if ($action == 'bulk_print' && auth()->user()->can('view', $purchase_orders->first())) { + $paths = $purchase_orders->map(function ($purchase_order) { return $purchase_order->service()->getPurchaseOrderPdf(); }); $merge = (new PdfMerge($paths->toArray()))->run(); - return response()->streamDownload(function () use ($merge) { - echo ($merge); - }, 'print.pdf', ['Content-Type' => 'application/pdf']); - + return response()->streamDownload(function () use ($merge) { + echo($merge); + }, 'print.pdf', ['Content-Type' => 'application/pdf']); } /* @@ -605,7 +598,7 @@ class PurchaseOrderController extends BaseController } private function performAction(PurchaseOrder $purchase_order, $action, $bulk = false) - { + { /*If we are using bulk actions, we don't want to return anything */ switch ($action) { case 'mark_sent': @@ -619,9 +612,9 @@ class PurchaseOrderController extends BaseController $file = $purchase_order->service()->getPurchaseOrderPdf(); - return response()->streamDownload(function () use($file) { - echo Storage::get($file); - }, basename($file), ['Content-Type' => 'application/pdf']); + return response()->streamDownload(function () use ($file) { + echo Storage::get($file); + }, basename($file), ['Content-Type' => 'application/pdf']); break; case 'restore': @@ -673,8 +666,9 @@ class PurchaseOrderController extends BaseController case 'expense': - if($purchase_order->expense()->exists()) + if ($purchase_order->expense()->exists()) { return response()->json(['message' => ctrans('texts.purchase_order_already_expensed')], 400); + } $expense = $purchase_order->service()->expense(); @@ -682,8 +676,7 @@ class PurchaseOrderController extends BaseController case 'cancel': - if($purchase_order->status_id <= PurchaseOrder::STATUS_SENT) - { + if ($purchase_order->status_id <= PurchaseOrder::STATUS_SENT) { $purchase_order->status_id = PurchaseOrder::STATUS_CANCELLED; $purchase_order->save(); } @@ -751,16 +744,16 @@ class PurchaseOrderController extends BaseController */ public function upload(UploadPurchaseOrderRequest $request, PurchaseOrder $purchase_order) { - - if(!$this->checkFeature(Account::FEATURE_DOCUMENTS)) + if (!$this->checkFeature(Account::FEATURE_DOCUMENTS)) { return $this->featureFailure(); + } - if ($request->has('documents')) + if ($request->has('documents')) { $this->saveDocuments($request->file('documents'), $purchase_order); + } return $this->itemResponse($purchase_order->fresh()); - - } + } /** @@ -828,8 +821,4 @@ class PurchaseOrderController extends BaseController echo Storage::get($file); }, basename($file), $headers); } - - - - } diff --git a/app/Http/Controllers/QuoteController.php b/app/Http/Controllers/QuoteController.php index a75dd9ec3104..ca27b5840054 100644 --- a/app/Http/Controllers/QuoteController.php +++ b/app/Http/Controllers/QuoteController.php @@ -27,20 +27,16 @@ use App\Http\Requests\Quote\ShowQuoteRequest; use App\Http\Requests\Quote\StoreQuoteRequest; use App\Http\Requests\Quote\UpdateQuoteRequest; use App\Http\Requests\Quote\UploadQuoteRequest; -use App\Jobs\Invoice\ZipInvoices; use App\Jobs\Quote\ZipQuotes; use App\Models\Account; use App\Models\Client; use App\Models\Invoice; -use App\Models\Project; use App\Models\Quote; use App\Repositories\QuoteRepository; use App\Services\PdfMaker\PdfMerge; use App\Transformers\InvoiceTransformer; -use App\Transformers\ProjectTransformer; use App\Transformers\QuoteTransformer; use App\Utils\Ninja; -use App\Utils\TempFile; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; @@ -516,8 +512,9 @@ class QuoteController extends BaseController $ids = request()->input('ids'); - if(Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) + if (Ninja::isHosted() && (stripos($action, 'email') !== false) && !auth()->user()->company()->account->account_sms_verified) { return response(['message' => 'Please verify your account to send emails.'], 400); + } $quotes = Quote::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get(); @@ -554,32 +551,26 @@ class QuoteController extends BaseController return $this->listResponse(Quote::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()); } - if($action == 'bulk_print' && auth()->user()->can('view', $quotes->first())){ - - $paths = $quotes->map(function ($quote){ + if ($action == 'bulk_print' && auth()->user()->can('view', $quotes->first())) { + $paths = $quotes->map(function ($quote) { return $quote->service()->getQuotePdf(); }); $merge = (new PdfMerge($paths->toArray()))->run(); - return response()->streamDownload(function () use ($merge) { - echo ($merge); - }, 'print.pdf', ['Content-Type' => 'application/pdf']); - + return response()->streamDownload(function () use ($merge) { + echo($merge); + }, 'print.pdf', ['Content-Type' => 'application/pdf']); } - if($action == 'convert_to_project') - { - + if ($action == 'convert_to_project') { $quotes->each(function ($quote, $key) use ($action) { - if (auth()->user()->can('edit', $quote)) - { + if (auth()->user()->can('edit', $quote)) { $project = CloneQuoteToProjectFactory::create($quote, auth()->user()->id); if (empty($project->number)) { $project->number = $this->getNextProjectNumber($project); - } $project->save(); $quote->project_id = $project->id; @@ -693,7 +684,7 @@ class QuoteController extends BaseController return $this->itemResponse($quote->service()->convertToInvoice()); - break; + break; case 'clone_to_invoice': diff --git a/app/Http/Controllers/RecurringExpenseController.php b/app/Http/Controllers/RecurringExpenseController.php index b601a12c6a35..2edb1be1e82e 100644 --- a/app/Http/Controllers/RecurringExpenseController.php +++ b/app/Http/Controllers/RecurringExpenseController.php @@ -31,7 +31,6 @@ use App\Utils\Traits\BulkOptions; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; use App\Utils\Traits\Uploadable; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** diff --git a/app/Http/Controllers/RecurringInvoiceController.php b/app/Http/Controllers/RecurringInvoiceController.php index 756e26f67da7..d19830888da4 100644 --- a/app/Http/Controllers/RecurringInvoiceController.php +++ b/app/Http/Controllers/RecurringInvoiceController.php @@ -30,7 +30,6 @@ use App\Transformers\RecurringInvoiceTransformer; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; -use Carbon\Carbon; use Illuminate\Http\Response; use Illuminate\Support\Facades\Storage; diff --git a/app/Http/Controllers/Reports/ProductSalesReportController.php b/app/Http/Controllers/Reports/ProductSalesReportController.php index 6eb518451ef0..f27de4b19343 100644 --- a/app/Http/Controllers/Reports/ProductSalesReportController.php +++ b/app/Http/Controllers/Reports/ProductSalesReportController.php @@ -11,10 +11,8 @@ namespace App\Http\Controllers\Reports; -use App\Export\CSV\ProductExport; use App\Export\CSV\ProductSalesExport; use App\Http\Controllers\BaseController; -use App\Http\Requests\Report\GenericReportRequest; use App\Http\Requests\Report\ProductSalesReportRequest; use App\Jobs\Report\SendToAdmin; use App\Models\Client; diff --git a/app/Http/Controllers/Reports/ProfitAndLossController.php b/app/Http/Controllers/Reports/ProfitAndLossController.php index 1d7c8833ccf1..3d1f0751066d 100644 --- a/app/Http/Controllers/Reports/ProfitAndLossController.php +++ b/app/Http/Controllers/Reports/ProfitAndLossController.php @@ -11,7 +11,6 @@ namespace App\Http\Controllers\Reports; -use App\Export\CSV\PaymentExport; use App\Http\Controllers\BaseController; use App\Http\Requests\Report\ProfitLossRequest; use App\Jobs\Report\SendToAdmin; diff --git a/app/Http/Controllers/SetupController.php b/app/Http/Controllers/SetupController.php index 7d024d894cd8..ff0faf16cbc4 100644 --- a/app/Http/Controllers/SetupController.php +++ b/app/Http/Controllers/SetupController.php @@ -20,7 +20,6 @@ use App\Jobs\Util\SchedulerCheck; use App\Jobs\Util\VersionCheck; use App\Models\Account; use App\Utils\CurlUtils; -use App\Utils\HostedPDF\NinjaPdf; use App\Utils\Ninja; use App\Utils\SystemHealth; use App\Utils\Traits\AppSetup; @@ -31,9 +30,7 @@ use Illuminate\Contracts\Routing\ResponseFactory; use Illuminate\Http\JsonResponse; use Illuminate\Http\Response; use Illuminate\Support\Facades\Artisan; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Storage; @@ -212,7 +209,6 @@ class SetupController extends Controller public function checkPdf(Request $request) { try { - // if (config('ninja.pdf_generator') == 'phantom') { // return $this->testPhantom(); // } diff --git a/app/Http/Controllers/StaticController.php b/app/Http/Controllers/StaticController.php index 2b9c2ae3fb26..bd9fddf84e31 100644 --- a/app/Http/Controllers/StaticController.php +++ b/app/Http/Controllers/StaticController.php @@ -11,13 +11,7 @@ namespace App\Http\Controllers; -use App\Http\Requests\Account\CreateAccountRequest; -use App\Jobs\Account\CreateAccount; -use App\Models\Account; -use App\Models\CompanyUser; -use App\Transformers\CompanyUserTransformer; use App\Utils\Statics; -use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Http\Response; class StaticController extends BaseController diff --git a/app/Http/Controllers/StripeConnectController.php b/app/Http/Controllers/StripeConnectController.php index 73a12b03ebfd..9408f987b0b9 100644 --- a/app/Http/Controllers/StripeConnectController.php +++ b/app/Http/Controllers/StripeConnectController.php @@ -12,7 +12,6 @@ namespace App\Http\Controllers; use App\DataMapper\FeesAndLimits; -use App\Exceptions\SystemError; use App\Factory\CompanyGatewayFactory; use App\Http\Requests\StripeConnect\InitializeStripeConnectRequest; use App\Libraries\MultiDB; @@ -20,10 +19,7 @@ use App\Models\Client; use App\Models\Company; use App\Models\CompanyGateway; use App\Models\GatewayType; -use App\PaymentDrivers\Stripe\Connect\Account; use App\PaymentDrivers\Stripe\Jobs\StripeWebhook; -use Exception; -use Illuminate\Http\Request; use Stripe\Exception\ApiErrorException; class StripeConnectController extends BaseController @@ -70,7 +66,7 @@ class StripeConnectController extends BaseController { \Stripe\Stripe::setApiKey(config('ninja.ninja_stripe_key')); - if($request->has('error') && $request->error == 'access_denied'){ + if ($request->has('error') && $request->error == 'access_denied') { return view('auth.connect.access_denied'); } @@ -80,9 +76,7 @@ class StripeConnectController extends BaseController 'code' => $request->input('code'), ]); } catch (\Exception $e) { - return view('auth.connect.access_denied'); - } MultiDB::findAndSetDbByCompanyKey($request->getTokenContent()['company_key']); diff --git a/app/Http/Controllers/StripeController.php b/app/Http/Controllers/StripeController.php index 8980d74181b8..a50402a6c1e1 100644 --- a/app/Http/Controllers/StripeController.php +++ b/app/Http/Controllers/StripeController.php @@ -38,7 +38,6 @@ class StripeController extends BaseController public function import() { - // return response()->json(['message' => 'Processing'], 200); if (auth()->user()->isAdmin()) { diff --git a/app/Http/Controllers/TaskController.php b/app/Http/Controllers/TaskController.php index e157fdf8e735..2617ebf1f270 100644 --- a/app/Http/Controllers/TaskController.php +++ b/app/Http/Controllers/TaskController.php @@ -33,7 +33,6 @@ use App\Utils\Traits\BulkOptions; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; use App\Utils\Traits\Uploadable; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** diff --git a/app/Http/Controllers/TaskSchedulerController.php b/app/Http/Controllers/TaskSchedulerController.php index dc3d297cf0fc..6de1bd1581d9 100644 --- a/app/Http/Controllers/TaskSchedulerController.php +++ b/app/Http/Controllers/TaskSchedulerController.php @@ -12,19 +12,15 @@ namespace App\Http\Controllers; use App\Factory\SchedulerFactory; +use App\Http\Requests\Task\DestroySchedulerRequest; use App\Http\Requests\TaskScheduler\CreateSchedulerRequest; use App\Http\Requests\TaskScheduler\ShowSchedulerRequest; use App\Http\Requests\TaskScheduler\StoreSchedulerRequest; use App\Http\Requests\TaskScheduler\UpdateSchedulerRequest; -use App\Http\Requests\Task\DestroySchedulerRequest; -use App\Jobs\Ninja\TaskScheduler; -use App\Jobs\Report\ProfitAndLoss; use App\Models\Scheduler; use App\Repositories\SchedulerRepository; use App\Transformers\SchedulerTransformer; use App\Utils\Traits\MakesHash; -use Carbon\Carbon; -use Illuminate\Database\Eloquent\Model; use Symfony\Component\HttpFoundation\Request; class TaskSchedulerController extends BaseController @@ -336,8 +332,9 @@ class TaskSchedulerController extends BaseController { $action = request()->input('action'); - if(!in_array($action, ['archive', 'restore', 'delete'])) + if (!in_array($action, ['archive', 'restore', 'delete'])) { return response()->json(['message' => 'Bulk action does not exist'], 400); + } $ids = request()->input('ids'); @@ -351,5 +348,4 @@ class TaskSchedulerController extends BaseController return $this->listResponse(Scheduler::withTrashed()->whereIn('id', $this->transformKeys($ids))); } - } diff --git a/app/Http/Controllers/TaskStatusController.php b/app/Http/Controllers/TaskStatusController.php index 3ed5ae224db9..188312faa512 100644 --- a/app/Http/Controllers/TaskStatusController.php +++ b/app/Http/Controllers/TaskStatusController.php @@ -461,10 +461,8 @@ class TaskStatusController extends BaseController ->whereIn('id', $this->transformKeys($ids)) ->cursor() ->each(function ($task_status, $key) use ($action) { - - $this->task_status_repo->{$action}($task_status); - - }); + $this->task_status_repo->{$action}($task_status); + }); return $this->listResponse(TaskStatus::withTrashed()->whereIn('id', $this->transformKeys($ids))); } diff --git a/app/Http/Controllers/TaxRateController.php b/app/Http/Controllers/TaxRateController.php index 29f7e2a310ba..fb60fbc40bb9 100644 --- a/app/Http/Controllers/TaxRateController.php +++ b/app/Http/Controllers/TaxRateController.php @@ -23,7 +23,6 @@ use App\Models\TaxRate; use App\Repositories\BaseRepository; use App\Transformers\TaxRateTransformer; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** diff --git a/app/Http/Controllers/TemplateController.php b/app/Http/Controllers/TemplateController.php index b7faf147f3a3..f105c868b027 100644 --- a/app/Http/Controllers/TemplateController.php +++ b/app/Http/Controllers/TemplateController.php @@ -11,14 +11,11 @@ namespace App\Http\Controllers; -use App\Utils\Ninja; use App\Utils\TemplateEngine; use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesInvoiceHtml; use App\Utils\Traits\MakesTemplateData; use Illuminate\Http\Response; -use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; class TemplateController extends BaseController { diff --git a/app/Http/Controllers/TokenController.php b/app/Http/Controllers/TokenController.php index bf35e279480e..6cf4413bf57b 100644 --- a/app/Http/Controllers/TokenController.php +++ b/app/Http/Controllers/TokenController.php @@ -25,7 +25,6 @@ use App\Transformers\CompanyTokenHashedTransformer; use App\Transformers\CompanyTokenTransformer; use App\Utils\Traits\ChecksEntityStatus; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** diff --git a/app/Http/Controllers/TwilioController.php b/app/Http/Controllers/TwilioController.php index a58cbb015c60..465e1b989830 100644 --- a/app/Http/Controllers/TwilioController.php +++ b/app/Http/Controllers/TwilioController.php @@ -17,13 +17,10 @@ use App\Http\Requests\Twilio\Generate2faRequest; use App\Http\Requests\Twilio\GenerateSmsRequest; use App\Libraries\MultiDB; use App\Models\User; -use Illuminate\Foundation\Bus\DispatchesJobs; -use Illuminate\Http\Response; use Twilio\Rest\Client; class TwilioController extends BaseController { - public function __construct() { parent::__construct(); @@ -38,8 +35,9 @@ class TwilioController extends BaseController { $account = auth()->user()->company()->account; - if(MultiDB::hasPhoneNumber($request->phone)) + if (MultiDB::hasPhoneNumber($request->phone)) { return response()->json(['message' => 'This phone number has already been verified with another account'], 400); + } $sid = config('ninja.twilio_account_sid'); $token = config('ninja.twilio_auth_token'); @@ -53,11 +51,8 @@ class TwilioController extends BaseController ->services(config('ninja.twilio_verify_sid')) ->verifications ->create($request->phone, "sms"); - } - catch(\Exception $e) { - + } catch(\Exception $e) { return response()->json(['message' => 'Invalid phone number please use + country code + number ie. +15552343334'], 400); - } $account->account_sms_verification_code = $verification->sid; @@ -74,7 +69,6 @@ class TwilioController extends BaseController */ public function confirm(ConfirmSmsRequest $request) { - $account = auth()->user()->company()->account; $sid = config('ninja.twilio_account_sid'); @@ -92,8 +86,7 @@ class TwilioController extends BaseController ]); - if($verification_check->status == 'approved'){ - + if ($verification_check->status == 'approved') { $account->account_sms_verified = true; $account->save(); @@ -108,15 +101,15 @@ class TwilioController extends BaseController return response()->json(['message' => 'SMS not verified'], 400); - } public function generate2faResetCode(Generate2faRequest $request) { $user = User::where('email', $request->email)->first(); - if(!$user) + if (!$user) { return response()->json(['message' => 'Unable to retrieve user.'], 400); + } $sid = config('ninja.twilio_account_sid'); $token = config('ninja.twilio_auth_token'); @@ -129,11 +122,8 @@ class TwilioController extends BaseController ->services(config('ninja.twilio_verify_sid')) ->verifications ->create($user->phone, "sms"); - } - catch(\Exception $e) { - + } catch(\Exception $e) { return response()->json(['message' => 'Invalid phone number on file, we are unable to reset. Please contact support.'], 400); - } $user->sms_verification_code = $verification->sid; @@ -146,8 +136,9 @@ class TwilioController extends BaseController { $user = User::where('email', $request->email)->first(); - if(!$user) + if (!$user) { return response()->json(['message' => 'Unable to retrieve user.'], 400); + } $sid = config('ninja.twilio_account_sid'); $token = config('ninja.twilio_auth_token'); @@ -163,9 +154,8 @@ class TwilioController extends BaseController "code" => $request->code ]); - if($verification_check->status == 'approved'){ - - if($request->query('validate_only') == 'true'){ + if ($verification_check->status == 'approved') { + if ($request->query('validate_only') == 'true') { $user->verified_phone_number = true; $user->save(); return response()->json(['message' => 'SMS verified'], 200); @@ -179,12 +169,10 @@ class TwilioController extends BaseController } return response()->json(['message' => 'SMS not verified.'], 400); - - } + } public function validatePhoneNumber() { - $sid = config('ninja.twilio_account_sid'); $token = config('ninja.twilio_auth_token'); @@ -194,7 +182,5 @@ class TwilioController extends BaseController ->fetch(["countryCode" => "AU"]); print($phone_number); - } - } diff --git a/app/Http/Controllers/TwoFactorController.php b/app/Http/Controllers/TwoFactorController.php index e05adb3060a1..bc3b1ba77411 100644 --- a/app/Http/Controllers/TwoFactorController.php +++ b/app/Http/Controllers/TwoFactorController.php @@ -14,7 +14,6 @@ namespace App\Http\Controllers; use App\Http\Requests\TwoFactor\EnableTwoFactorRequest; use App\Models\User; use App\Transformers\UserTransformer; -use Crypt; use PragmaRX\Google2FA\Google2FA; class TwoFactorController extends BaseController diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index 99d4505945fc..8cccb0a93fc6 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -11,14 +11,12 @@ namespace App\Http\Controllers; -use App\DataMapper\CompanySettings; use App\Events\User\UserWasCreated; use App\Events\User\UserWasDeleted; use App\Events\User\UserWasUpdated; use App\Factory\UserFactory; use App\Filters\UserFilters; use App\Http\Controllers\Traits\VerifiesUserEmail; -use App\Http\Requests\User\AttachCompanyUserRequest; use App\Http\Requests\User\BulkUserRequest; use App\Http\Requests\User\CreateUserRequest; use App\Http\Requests\User\DestroyUserRequest; @@ -29,18 +27,13 @@ use App\Http\Requests\User\ShowUserRequest; use App\Http\Requests\User\StoreUserRequest; use App\Http\Requests\User\UpdateUserRequest; use App\Jobs\Company\CreateCompanyToken; -use App\Jobs\Mail\NinjaMailer; -use App\Jobs\Mail\NinjaMailerJob; -use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\User\UserEmailChanged; -use App\Mail\Admin\VerifyUserObject; use App\Models\CompanyUser; use App\Models\User; use App\Repositories\UserRepository; use App\Transformers\UserTransformer; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** @@ -64,11 +57,9 @@ class UserController extends BaseController */ public function __construct(UserRepository $user_repo) { - parent::__construct(); $this->user_repo = $user_repo; - } /** @@ -461,8 +452,9 @@ class UserController extends BaseController */ public function destroy(DestroyUserRequest $request, User $user) { - if($user->isOwner()) - return response()->json(['message', 'Cannot detach owner.'],400); + if ($user->isOwner()) { + return response()->json(['message', 'Cannot detach owner.'], 400); + } /* If the user passes the company user we archive the company user */ $user = $this->user_repo->delete($request->all(), $user); @@ -600,7 +592,6 @@ class UserController extends BaseController */ public function detach(DetachCompanyUserRequest $request, User $user) { - if ($request->entityIsDeleted($user)) { return $request->disallowUpdate(); } @@ -610,8 +601,9 @@ class UserController extends BaseController ->withTrashed() ->first(); - if($company_user->is_owner) + if ($company_user->is_owner) { return response()->json(['message', 'Cannot detach owner.'], 401); + } $token = $company_user->token->where('company_id', $company_user->company_id)->where('user_id', $company_user->user_id)->first(); @@ -674,11 +666,9 @@ class UserController extends BaseController */ public function invite(ReconfirmUserRequest $request, User $user) { - $user->service()->invite($user->company()); return response()->json(['message' => ctrans('texts.confirmation_resent')], 200); - } @@ -730,10 +720,8 @@ class UserController extends BaseController */ public function reconfirm(ReconfirmUserRequest $request, User $user) { - $user->service()->invite($user->company()); return response()->json(['message' => ctrans('texts.confirmation_resent')], 200); - } } diff --git a/app/Http/Controllers/VendorController.php b/app/Http/Controllers/VendorController.php index 07e932b181a9..4ac01af36de1 100644 --- a/app/Http/Controllers/VendorController.php +++ b/app/Http/Controllers/VendorController.php @@ -31,7 +31,6 @@ use App\Utils\Traits\BulkOptions; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; use App\Utils\Traits\Uploadable; -use Illuminate\Http\Request; use Illuminate\Http\Response; /** diff --git a/app/Http/Controllers/VendorPortal/DocumentController.php b/app/Http/Controllers/VendorPortal/DocumentController.php index 71b35af63747..c12820953b25 100644 --- a/app/Http/Controllers/VendorPortal/DocumentController.php +++ b/app/Http/Controllers/VendorPortal/DocumentController.php @@ -13,8 +13,8 @@ namespace App\Http\Controllers\VendorPortal; use App\Http\Controllers\Controller; -use App\Http\Requests\VendorPortal\Documents\ShowDocumentRequest; use App\Http\Requests\Document\DownloadMultipleDocumentsRequest; +use App\Http\Requests\VendorPortal\Documents\ShowDocumentRequest; use App\Libraries\MultiDB; use App\Models\Document; use App\Utils\TempFile; @@ -111,7 +111,7 @@ class DocumentController extends Controller $zipFile->saveAsFile($filepath) // save the archive to a file ->close(); // close archive - return response()->download($filepath, $filename)->deleteFileAfterSend(true); + return response()->download($filepath, $filename)->deleteFileAfterSend(true); } catch (\PhpZip\Exception\ZipException $e) { // handle exception } finally { diff --git a/app/Http/Controllers/VendorPortal/InvitationController.php b/app/Http/Controllers/VendorPortal/InvitationController.php index b2a7fe7f5f19..80bc02e5d5df 100644 --- a/app/Http/Controllers/VendorPortal/InvitationController.php +++ b/app/Http/Controllers/VendorPortal/InvitationController.php @@ -11,28 +11,14 @@ namespace App\Http\Controllers\VendorPortal; -use App\Events\Credit\CreditWasViewed; -use App\Events\Invoice\InvoiceWasViewed; use App\Events\Misc\InvitationWasViewed; use App\Events\PurchaseOrder\PurchaseOrderWasViewed; -use App\Events\Quote\QuoteWasViewed; use App\Http\Controllers\Controller; -use App\Jobs\Entity\CreateRawPdf; use App\Jobs\Vendor\CreatePurchaseOrderPdf; -use App\Models\Client; -use App\Models\ClientContact; -use App\Models\CreditInvitation; -use App\Models\InvoiceInvitation; -use App\Models\Payment; -use App\Models\PurchaseOrder; use App\Models\PurchaseOrderInvitation; -use App\Models\QuoteInvitation; -use App\Services\ClientPortal\InstantPayment; -use App\Utils\CurlUtils; use App\Utils\Ninja; use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; @@ -46,33 +32,34 @@ class InvitationController extends Controller public function purchaseOrder(string $invitation_key) { - Auth::logout(); $invitation = PurchaseOrderInvitation::withTrashed() ->where('key', $invitation_key) ->whereHas('purchase_order', function ($query) { - $query->where('is_deleted',0); + $query->where('is_deleted', 0); }) ->with('contact.vendor') ->first(); - if(!$invitation) - return abort(404,'The resource is no longer available.'); + if (!$invitation) { + return abort(404, 'The resource is no longer available.'); + } - if($invitation->contact->trashed()) + if ($invitation->contact->trashed()) { $invitation->contact->restore(); + } $vendor_contact = $invitation->contact; $entity = 'purchase_order'; - if(empty($vendor_contact->email)) - $vendor_contact->email = Str::random(15) . "@example.com"; $vendor_contact->save(); + if (empty($vendor_contact->email)) { + $vendor_contact->email = Str::random(15) . "@example.com"; + } $vendor_contact->save(); if (request()->has('vendor_hash') && request()->input('vendor_hash') == $invitation->contact->vendor->vendor_hash) { request()->session()->invalidate(); auth()->guard('vendor')->loginUsingId($vendor_contact->id, true); - } else { request()->session()->invalidate(); auth()->guard('vendor')->loginUsingId($vendor_contact->id, true); @@ -81,21 +68,14 @@ class InvitationController extends Controller session()->put('is_silent', request()->has('silent')); if (auth()->guard('vendor')->user() && ! session()->get('is_silent') && ! $invitation->viewed_date) { - $invitation->markViewed(); event(new InvitationWasViewed($invitation->purchase_order, $invitation, $invitation->company, Ninja::eventVars())); event(new PurchaseOrderWasViewed($invitation, $invitation->company, Ninja::eventVars())); - - } - else{ - + } else { return redirect()->route('vendor.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->purchase_order_id), 'silent' => session()->get('is_silent')]); - } return redirect()->route('vendor.'.$entity.'.show', [$entity => $this->encodePrimaryKey($invitation->purchase_order_id)]); - - } public function download(string $invitation_key) @@ -105,8 +85,9 @@ class InvitationController extends Controller ->with('contact.vendor') ->firstOrFail(); - if(!$invitation) + if (!$invitation) { return response()->json(["message" => "no record found"], 400); + } $file_name = $invitation->purchase_order->numberFormatter().'.pdf'; @@ -114,15 +95,12 @@ class InvitationController extends Controller $headers = ['Content-Type' => 'application/pdf']; - if(request()->input('inline') == 'true') + if (request()->input('inline') == 'true') { $headers = array_merge($headers, ['Content-Disposition' => 'inline']); + } - return response()->streamDownload(function () use($file) { - echo $file; - }, $file_name, $headers); + return response()->streamDownload(function () use ($file) { + echo $file; + }, $file_name, $headers); } - - - - } diff --git a/app/Http/Controllers/VendorPortal/PurchaseOrderController.php b/app/Http/Controllers/VendorPortal/PurchaseOrderController.php index 6d1eee326790..1a9d309558d1 100644 --- a/app/Http/Controllers/VendorPortal/PurchaseOrderController.php +++ b/app/Http/Controllers/VendorPortal/PurchaseOrderController.php @@ -24,7 +24,6 @@ use App\Utils\Ninja; use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; use Illuminate\Contracts\View\Factory; -use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\View\View; @@ -203,7 +202,6 @@ class PurchaseOrderController extends Controller $zipFile = new \PhpZip\ZipFile(); try { foreach ($purchase_orders as $purchase_order) { - //add it to the zip $zipFile->addFromString(basename($purchase_order->pdf_file_path()), file_get_contents($purchase_order->pdf_file_path(null, 'url', true))); } @@ -214,7 +212,7 @@ class PurchaseOrderController extends Controller $zipFile->saveAsFile($filepath) // save the archive to a file ->close(); // close archive - return response()->download($filepath, $filename)->deleteFileAfterSend(true); + return response()->download($filepath, $filename)->deleteFileAfterSend(true); } catch (\PhpZip\Exception\ZipException $e) { // handle exception } finally { diff --git a/app/Http/Controllers/VendorPortal/UploadController.php b/app/Http/Controllers/VendorPortal/UploadController.php index ac7cc1f8e6c0..c9c6da65815b 100644 --- a/app/Http/Controllers/VendorPortal/UploadController.php +++ b/app/Http/Controllers/VendorPortal/UploadController.php @@ -33,7 +33,6 @@ class UploadController extends Controller */ public function upload(StoreUploadRequest $request, PurchaseOrder $purchase_order) { - $this->saveDocuments($request->getFile(), $purchase_order, true); return response([], 200); diff --git a/app/Http/Controllers/VendorPortal/VendorContactController.php b/app/Http/Controllers/VendorPortal/VendorContactController.php index 224eb2dacf7e..ea26616691a0 100644 --- a/app/Http/Controllers/VendorPortal/VendorContactController.php +++ b/app/Http/Controllers/VendorPortal/VendorContactController.php @@ -15,7 +15,6 @@ use App\Http\Controllers\Controller; use App\Models\VendorContact; use App\Utils\Traits\MakesHash; use App\Utils\TranslationHelper; -use Illuminate\Http\Request; class VendorContactController extends Controller { diff --git a/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php b/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php index 1636f43cbae6..96190431d68c 100644 --- a/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php +++ b/app/Http/Controllers/VendorPortal/VendorContactHashLoginController.php @@ -12,8 +12,6 @@ namespace App\Http\Controllers\VendorPortal; use App\Http\Controllers\Controller; -use App\Http\ViewComposers\PortalComposer; -use App\Models\RecurringInvoice; use Auth; class VendorContactHashLoginController extends Controller @@ -37,6 +35,4 @@ class VendorContactHashLoginController extends Controller { return render('generic.error', ['title' => session()->get('title'), 'notification' => session()->get('notification')]); } - - } diff --git a/app/Http/Controllers/WePayController.php b/app/Http/Controllers/WePayController.php index d8351f78a4ba..a37a5e56a95b 100644 --- a/app/Http/Controllers/WePayController.php +++ b/app/Http/Controllers/WePayController.php @@ -17,7 +17,6 @@ use App\Models\CompanyGateway; use App\Models\User; use App\PaymentDrivers\WePayPaymentDriver; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; class WePayController extends BaseController diff --git a/app/Http/Controllers/WebhookController.php b/app/Http/Controllers/WebhookController.php index 5c6b9d5ffbef..f77fef636efb 100644 --- a/app/Http/Controllers/WebhookController.php +++ b/app/Http/Controllers/WebhookController.php @@ -24,7 +24,6 @@ use App\Models\Webhook; use App\Repositories\BaseRepository; use App\Transformers\WebhookTransformer; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; use Illuminate\Http\Response; class WebhookController extends BaseController diff --git a/app/Http/Livewire/BillingPortalPurchase.php b/app/Http/Livewire/BillingPortalPurchase.php index 567ddabf56ae..8b7f79a5628f 100644 --- a/app/Http/Livewire/BillingPortalPurchase.php +++ b/app/Http/Livewire/BillingPortalPurchase.php @@ -11,6 +11,7 @@ namespace App\Http\Livewire; +use App\DataMapper\ClientSettings; use App\Factory\ClientFactory; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; @@ -22,12 +23,9 @@ use App\Models\Invoice; use App\Models\Subscription; use App\Repositories\ClientContactRepository; use App\Repositories\ClientRepository; -use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; -use App\DataMapper\ClientSettings; use Livewire\Component; class BillingPortalPurchase extends Component @@ -198,16 +196,14 @@ class BillingPortalPurchase extends Component if (request()->query('coupon')) { $this->coupon = request()->query('coupon'); $this->handleCoupon(); - } - elseif(strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0){ + } elseif (strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) { $this->price = $this->subscription->promo_price; } /* Leave this here, otherwise a logged in user will need to reauth... painfully */ - if(Auth::guard('contact')->check()){ + if (Auth::guard('contact')->check()) { return $this->getPaymentMethods(auth()->guard('contact')->user()); } - } /** @@ -277,25 +273,22 @@ class BillingPortalPurchase extends Component } } - if(array_key_exists('currency_id', $this->request_data)) { - - $currency = Cache::get('currencies')->filter(function ($item){ + if (array_key_exists('currency_id', $this->request_data)) { + $currency = Cache::get('currencies')->filter(function ($item) { return $item->id == $this->request_data['currency_id']; })->first(); - if($currency) + if ($currency) { $data['settings']->currency_id = $currency->id; - - } - elseif($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) { - - $currency = Cache::get('currencies')->filter(function ($item){ + } + } elseif ($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) { + $currency = Cache::get('currencies')->filter(function ($item) { return $item->id == $this->subscription->group_settings->settings->currency_id; })->first(); - if($currency) + if ($currency) { $data['settings']->currency_id = $currency->id; - + } } if (array_key_exists('locale', $this->request_data)) { @@ -334,10 +327,11 @@ class BillingPortalPurchase extends Component return $this; } - if ((int)$this->price == 0) + if ((int)$this->price == 0) { $this->steps['payment_required'] = false; - else + } else { $this->steps['fetched_payment_methods'] = true; + } $this->methods = $contact->client->service()->getPaymentMethods($this->price); @@ -431,7 +425,6 @@ class BillingPortalPurchase extends Component public function handlePaymentNotRequired() { - $is_eligible = $this->subscription->service()->isEligible($this->contact); if ($is_eligible['status_code'] != 200) { @@ -478,16 +471,15 @@ class BillingPortalPurchase extends Component return $this->quantity; } - $this->quantity--; - $this->price = $this->price * $this->quantity; + $this->quantity--; + $this->price = $this->price * $this->quantity; - return $this->quantity; + return $this->quantity; } public function handleCoupon() { - - if($this->steps['discount_applied']){ + if ($this->steps['discount_applied']) { $this->price = $this->subscription->promo_price; return; } @@ -496,9 +488,9 @@ class BillingPortalPurchase extends Component $this->price = $this->subscription->promo_price; $this->quantity = 1; $this->steps['discount_applied'] = true; - } - else + } else { $this->price = $this->subscription->price; + } } public function passwordlessLogin() diff --git a/app/Http/Livewire/BillingPortalPurchasev2.php b/app/Http/Livewire/BillingPortalPurchasev2.php index f7f4d1ba79dc..ae9c980d082c 100644 --- a/app/Http/Livewire/BillingPortalPurchasev2.php +++ b/app/Http/Livewire/BillingPortalPurchasev2.php @@ -15,9 +15,7 @@ use App\DataMapper\ClientSettings; use App\Factory\ClientFactory; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; -use App\Jobs\Subscription\CleanStaleInvoiceOrder; use App\Libraries\MultiDB; -use App\Mail\ContactPasswordlessLogin; use App\Mail\Subscription\OtpCode; use App\Models\Client; use App\Models\ClientContact; @@ -27,15 +25,11 @@ use App\Models\Subscription; use App\Repositories\ClientContactRepository; use App\Repositories\ClientRepository; use App\Utils\Number; -use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; -use Illuminate\Validation\Rule; -use Laracasts\Presenter\Exceptions\PresenterException; use InvalidArgumentException; +use Laracasts\Presenter\Exceptions\PresenterException; use Livewire\Component; class BillingPortalPurchasev2 extends Component @@ -171,7 +165,7 @@ class BillingPortalPurchasev2 extends Component $this->company = $this->subscription->company; - if(auth()->guard('contact')->check()){ + if (auth()->guard('contact')->check()) { $this->email = auth()->guard('contact')->user()->email; $this->contact = auth()->guard('contact')->user(); $this->authenticated = true; @@ -195,31 +189,28 @@ class BillingPortalPurchasev2 extends Component //every thing below is redundant - if (request()->query('coupon')) { + if (request()->query('coupon')) { $this->coupon = request()->query('coupon'); $this->handleCoupon(); + } elseif (isset($this->subscription->promo_code) && strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) { + $this->price = $this->subscription->promo_price; } - elseif(isset($this->subscription->promo_code) && strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0){ - $this->price = $this->subscription->promo_price; - } - } public function loginValidation() { $this->resetErrorBag('login'); - $this->resetValidation('login'); + $this->resetValidation('login'); } public function handleLogin($user_code) { - $this->resetErrorBag('login'); $this->resetValidation('login'); $code = Cache::get("subscriptions:otp:{$this->email}"); - if($user_code != $code){ + if ($user_code != $code) { $errors = $this->getErrorBag(); $errors->add('login', ctrans('texts.invalid_code')); return $this; @@ -229,11 +220,10 @@ class BillingPortalPurchasev2 extends Component ->where('company_id', $this->subscription->company_id) ->first(); - if($contact){ + if ($contact) { Auth::guard('contact')->loginUsingId($contact->id, true); $this->contact = $contact; - } - else { + } else { $this->createClientContact(); } @@ -241,32 +231,30 @@ class BillingPortalPurchasev2 extends Component $this->authenticated = true; $this->payment_started = true; - } public function resetEmail() { $this->resetErrorBag('login'); - $this->resetValidation('login'); + $this->resetValidation('login'); $this->email = null; } public function handleEmail() { - $this->validateOnly('email', ['email' => 'required|bail|email:rfc']); + $this->validateOnly('email', ['email' => 'required|bail|email:rfc']); - $rand = rand(100000,999999); + $rand = rand(100000, 999999); - $email_hash = "subscriptions:otp:{$this->email}"; + $email_hash = "subscriptions:otp:{$this->email}"; - Cache::put($email_hash, $rand, 120); + Cache::put($email_hash, $rand, 120); - $this->emailOtpCode($rand); + $this->emailOtpCode($rand); } private function emailOtpCode($code) { - $cc = new ClientContact(); $cc->email = $this->email; @@ -276,7 +264,6 @@ class BillingPortalPurchasev2 extends Component $nmo->settings = $this->subscription->company->settings; $nmo->to_user = $cc; NinjaMailerJob::dispatch($nmo); - } /** @@ -284,17 +271,14 @@ class BillingPortalPurchasev2 extends Component */ public function handleCoupon() { - - if($this->coupon == $this->subscription->promo_code) { + if ($this->coupon == $this->subscription->promo_code) { $this->valid_coupon = true; $this->buildBundle(); - } - else{ + } else { $this->discount = 0; $this->valid_coupon = false; $this->buildBundle(); } - } /** @@ -302,142 +286,123 @@ class BillingPortalPurchasev2 extends Component */ public function buildBundle() { - $this->bundle = collect(); + $this->bundle = collect(); - $data = $this->data; + $data = $this->data; - /* Recurring products can have a variable quantity */ - foreach($this->recurring_products as $key => $p) - { + /* Recurring products can have a variable quantity */ + foreach ($this->recurring_products as $key => $p) { + $qty = isset($data[$key]['recurring_qty']) ? $data[$key]['recurring_qty'] : 1; + $total = $p->price * $qty; - $qty = isset($data[$key]['recurring_qty']) ? $data[$key]['recurring_qty'] : 1; + $this->bundle->push([ + 'description' => $p->notes, + 'product_key' => $p->product_key, + 'unit_cost' => $p->price, + 'product' => nl2br(substr($p->notes, 0, 50)), + 'price' => Number::formatMoney($total, $this->subscription->company).' / '. RecurringInvoice::frequencyForKey($this->subscription->frequency_id), + 'total' => $total, + 'qty' => $qty, + 'is_recurring' => true, + 'product_image' => $p->product_image, + ]); + } + + /* One time products can only have a single quantity */ + foreach ($this->products as $key => $p) { + $qty = 1; + $total = $p->price * $qty; + + $this->bundle->push([ + 'description' => $p->notes, + 'product_key' => $p->product_key, + 'unit_cost' => $p->price, + 'product' => nl2br(substr($p->notes, 0, 50)), + 'price' => Number::formatMoney($total, $this->subscription->company), + 'total' => $total, + 'qty' => $qty, + 'is_recurring' => false + ]); + } + + foreach ($this->data as $key => $value) { + /* Optional recurring products can have a variable quantity */ + if (isset($this->data[$key]['optional_recurring_qty'])) { + $p = $this->optional_recurring_products->first(function ($v, $k) use ($key) { + return $k == $key; + }); + + $qty = isset($this->data[$key]['optional_recurring_qty']) ? $this->data[$key]['optional_recurring_qty'] : false; $total = $p->price * $qty; - $this->bundle->push([ - 'description' => $p->notes, - 'product_key' => $p->product_key, - 'unit_cost' => $p->price, - 'product' => nl2br(substr($p->notes, 0, 50)), - 'price' => Number::formatMoney($total, $this->subscription->company).' / '. RecurringInvoice::frequencyForKey($this->subscription->frequency_id), - 'total' => $total, - 'qty' => $qty, - 'is_recurring' => true, - 'product_image' => $p->product_image, - ]); + if ($qty) { + $this->bundle->push([ + 'description' => $p->notes, + 'product_key' => $p->product_key, + 'unit_cost' => $p->price, + 'product' => nl2br(substr($p->notes, 0, 50)), + 'price' => Number::formatMoney($total, $this->subscription->company).' / '. RecurringInvoice::frequencyForKey($this->subscription->frequency_id), + 'total' => $total, + 'qty' => $qty, + 'is_recurring' => true + ]); + } } - /* One time products can only have a single quantity */ - foreach($this->products as $key => $p) - { + /* Optional products can have a variable quantity */ + if (isset($this->data[$key]['optional_qty'])) { + $p = $this->optional_products->first(function ($v, $k) use ($key) { + return $k == $key; + }); - $qty = 1; + $qty = isset($this->data[$key]['optional_qty']) ? $this->data[$key]['optional_qty'] : false; $total = $p->price * $qty; - $this->bundle->push([ - 'description' => $p->notes, - 'product_key' => $p->product_key, - 'unit_cost' => $p->price, - 'product' => nl2br(substr($p->notes, 0, 50)), - 'price' => Number::formatMoney($total, $this->subscription->company), - 'total' => $total, - 'qty' => $qty, - 'is_recurring' => false - ]); - - } - - foreach($this->data as $key => $value) - { - - /* Optional recurring products can have a variable quantity */ - if(isset($this->data[$key]['optional_recurring_qty'])) - { - $p = $this->optional_recurring_products->first(function ($v,$k) use($key){ - return $k == $key; - }); - - $qty = isset($this->data[$key]['optional_recurring_qty']) ? $this->data[$key]['optional_recurring_qty'] : false; - $total = $p->price * $qty; - - if($qty) - { - - $this->bundle->push([ - 'description' => $p->notes, - 'product_key' => $p->product_key, - 'unit_cost' => $p->price, - 'product' => nl2br(substr($p->notes, 0, 50)), - 'price' => Number::formatMoney($total, $this->subscription->company).' / '. RecurringInvoice::frequencyForKey($this->subscription->frequency_id), - 'total' => $total, - 'qty' => $qty, - 'is_recurring' => true - ]); - - } + if ($qty) { + $this->bundle->push([ + 'description' => $p->notes, + 'product_key' => $p->product_key, + 'unit_cost' => $p->price, + 'product' => nl2br(substr($p->notes, 0, 50)), + 'price' => Number::formatMoney($total, $this->subscription->company), + 'total' => $total, + 'qty' => $qty, + 'is_recurring' => false + ]); } - - /* Optional products can have a variable quantity */ - if(isset($this->data[$key]['optional_qty'])) - { - $p = $this->optional_products->first(function ($v,$k) use($key){ - return $k == $key; - }); - - $qty = isset($this->data[$key]['optional_qty']) ? $this->data[$key]['optional_qty'] : false; - $total = $p->price * $qty; - - if($qty) - { - $this->bundle->push([ - 'description' => $p->notes, - 'product_key' => $p->product_key, - 'unit_cost' => $p->price, - 'product' => nl2br(substr($p->notes, 0, 50)), - 'price' => Number::formatMoney($total, $this->subscription->company), - 'total' => $total, - 'qty' => $qty, - 'is_recurring' => false - ]); - } - - } - } + } $this->sub_total = Number::formatMoney($this->bundle->sum('total'), $this->subscription->company); $this->total = $this->sub_total; - if($this->valid_coupon) - { - - if($this->subscription->is_amount_discount) + if ($this->valid_coupon) { + if ($this->subscription->is_amount_discount) { $discount = $this->subscription->promo_discount; - else + } else { $discount = round($this->bundle->sum('total') * ($this->subscription->promo_discount / 100), 2); + } $this->discount = Number::formatMoney($discount, $this->subscription->company); $this->total = Number::formatMoney(($this->bundle->sum('total') - $discount), $this->subscription->company); $this->float_amount_total = ($this->bundle->sum('total') - $discount); - } - else { + } else { $this->float_amount_total = $this->bundle->sum('total'); $this->total = Number::formatMoney($this->float_amount_total, $this->subscription->company); - } return $this; } /** - * @return $this - * @throws PresenterException - * @throws InvalidArgumentException + * @return $this + * @throws PresenterException + * @throws InvalidArgumentException */ private function createClientContact() { - $company = $this->subscription->company; $user = $this->subscription->user; $user->setCompany($company); @@ -459,18 +424,19 @@ class BillingPortalPurchasev2 extends Component Auth::guard('contact')->loginUsingId($this->contact->id, true); return $this; - } + } /** - * @param mixed $propertyName - * - * @return BillingPortalPurchasev2 + * @param mixed $propertyName + * + * @return BillingPortalPurchasev2 */ public function updated($propertyName) :self { - if(in_array($propertyName, ['login','email'])) + if (in_array($propertyName, ['login','email'])) { return $this; + } $this->buildBundle(); @@ -486,11 +452,13 @@ class BillingPortalPurchasev2 extends Component { nlog("total amount = {$this->float_amount_total}"); - if($this->float_amount_total == 0) + if ($this->float_amount_total == 0) { $this->methods = []; + } - if($this->contact && $this->float_amount_total >= 1) + if ($this->contact && $this->float_amount_total >= 1) { $this->methods = $this->contact->client->service()->getPaymentMethods($this->float_amount_total); + } return $this; } @@ -519,16 +487,13 @@ class BillingPortalPurchasev2 extends Component */ public function handleBeforePaymentEvents() :self { - $eligibility_check = $this->subscription->service()->isEligible($this->contact); - if(is_array($eligibility_check) && $eligibility_check['message'] != 'Success'){ - + if (is_array($eligibility_check) && $eligibility_check['message'] != 'Success') { $this->is_eligible = false; $this->not_eligible_message = $eligibility_check['message']; return $this; - } $data = [ @@ -565,13 +530,12 @@ class BillingPortalPurchasev2 extends Component $this->emit('beforePaymentEventsCompleted'); return $this; - } /** * Starts the trial - * + * * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse */ public function handleTrial() @@ -586,22 +550,19 @@ class BillingPortalPurchasev2 extends Component } /** - * When the subscription total comes to $0 we + * When the subscription total comes to $0 we * pass back a $0 Invoice. * * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse */ public function handlePaymentNotRequired() { - $eligibility_check = $this->subscription->service()->isEligible($this->contact); - if(is_array($eligibility_check) && $eligibility_check['message'] != 'Success'){ - + if (is_array($eligibility_check) && $eligibility_check['message'] != 'Success') { $this->is_eligible = false; $this->not_eligible_message = $eligibility_check['message']; return $this; - } $invoice = $this->subscription @@ -612,16 +573,15 @@ class BillingPortalPurchasev2 extends Component ->adjustInventory() ->save(); - $invoice->number = null; + $invoice->number = null; - $invoice->service() - ->markPaid() - ->save(); - - return $this->subscription - ->service() - ->handleNoPaymentFlow($invoice, $this->bundle, $this->contact); + $invoice->service() + ->markPaid() + ->save(); + return $this->subscription + ->service() + ->handleNoPaymentFlow($invoice, $this->bundle, $this->contact); } @@ -655,7 +615,6 @@ class BillingPortalPurchasev2 extends Component public function store() { - } /** @@ -691,25 +650,22 @@ class BillingPortalPurchasev2 extends Component } } - if(array_key_exists('currency_id', $this->request_data)) { - - $currency = Cache::get('currencies')->filter(function ($item){ + if (array_key_exists('currency_id', $this->request_data)) { + $currency = Cache::get('currencies')->filter(function ($item) { return $item->id == $this->request_data['currency_id']; })->first(); - if($currency) + if ($currency) { $data['settings']->currency_id = $currency->id; - - } - elseif($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) { - - $currency = Cache::get('currencies')->filter(function ($item){ + } + } elseif ($this->subscription->group_settings && property_exists($this->subscription->group_settings->settings, 'currency_id')) { + $currency = Cache::get('currencies')->filter(function ($item) { return $item->id == $this->subscription->group_settings->settings->currency_id; })->first(); - if($currency) + if ($currency) { $data['settings']->currency_id = $currency->id; - + } } if (array_key_exists('locale', $this->request_data)) { @@ -749,5 +705,4 @@ class BillingPortalPurchasev2 extends Component return render('components.livewire.billing-portal-purchasev2'); } - } diff --git a/app/Http/Livewire/DocumentsTable.php b/app/Http/Livewire/DocumentsTable.php index f808004d2e5b..277886344ce6 100644 --- a/app/Http/Livewire/DocumentsTable.php +++ b/app/Http/Livewire/DocumentsTable.php @@ -83,7 +83,7 @@ class DocumentsTable extends Component break; case 'expenses': - // $this->query = $this->expenses(); + // $this->query = $this->expenses(); break; case 'invoices': diff --git a/app/Http/Livewire/PurchaseOrdersTable.php b/app/Http/Livewire/PurchaseOrdersTable.php index cb5f1120dc12..438f368e7745 100644 --- a/app/Http/Livewire/PurchaseOrdersTable.php +++ b/app/Http/Livewire/PurchaseOrdersTable.php @@ -16,7 +16,6 @@ use App\Libraries\MultiDB; use App\Models\Invoice; use App\Models\PurchaseOrder; use App\Utils\Traits\WithSorting; -use Carbon\Carbon; use Livewire\Component; use Livewire\WithPagination; diff --git a/app/Http/Livewire/QuotesTable.php b/app/Http/Livewire/QuotesTable.php index 8ed587326661..69d9677c83c9 100644 --- a/app/Http/Livewire/QuotesTable.php +++ b/app/Http/Livewire/QuotesTable.php @@ -15,7 +15,6 @@ namespace App\Http\Livewire; use App\Libraries\MultiDB; use App\Models\Company; use App\Models\Quote; -use App\Utils\Traits\WithSorting; use Livewire\Component; use Livewire\WithPagination; @@ -29,7 +28,7 @@ class QuotesTable extends Component public Company $company; - public string $sort = 'status_id'; + public string $sort = 'status_id'; public bool $sort_asc = true; @@ -56,16 +55,13 @@ class QuotesTable extends Component public function render() { - $query = Quote::query() ->with('client.contacts', 'company') ->orderBy($this->sort, $this->sort_asc ? 'asc' : 'desc'); if (count($this->status) > 0) { - /* Special filter for expired*/ if (in_array('-1', $this->status)) { - $query->where(function ($query) { $query->whereDate('due_date', '<=', now()->startOfDay()) ->whereNotNull('due_date') diff --git a/app/Http/Livewire/RecurringInvoices/UpdateAutoBilling.php b/app/Http/Livewire/RecurringInvoices/UpdateAutoBilling.php index f7183ec3b52a..da7831e4065d 100644 --- a/app/Http/Livewire/RecurringInvoices/UpdateAutoBilling.php +++ b/app/Http/Livewire/RecurringInvoices/UpdateAutoBilling.php @@ -28,7 +28,7 @@ class UpdateAutoBilling extends Component Invoice::where('recurring_id', $this->invoice->id) ->whereIn('status_id', [2,3]) - ->where('is_deleted',0) + ->where('is_deleted', 0) ->where('balance', '>', 0) ->update(['auto_bill_enabled' => $this->invoice->auto_bill_enabled]); } diff --git a/app/Http/Livewire/RequiredClientInfo.php b/app/Http/Livewire/RequiredClientInfo.php index a2286249e584..f4d0c1a13f79 100644 --- a/app/Http/Livewire/RequiredClientInfo.php +++ b/app/Http/Livewire/RequiredClientInfo.php @@ -149,8 +149,7 @@ class RequiredClientInfo extends Component $this->client = $this->contact->client; - if($this->company->settings->show_accept_invoice_terms && request()->query('hash')) - { + if ($this->company->settings->show_accept_invoice_terms && request()->query('hash')) { $this->show_terms = true; $this->terms_accepted = false; $this->show_form = true; @@ -158,19 +157,16 @@ class RequiredClientInfo extends Component $hash = Cache::get(request()->input('hash')); $this->invoice = Invoice::find($this->decodePrimaryKey($hash['invoice_id'])); - } count($this->fields) > 0 || $this->show_terms ? $this->checkFields() : $this->show_form = false; - } public function toggleTermsAccepted() { $this->terms_accepted = !$this->terms_accepted; - } public function handleSubmit(array $data): bool @@ -209,7 +205,6 @@ class RequiredClientInfo extends Component private function updateClientDetails(array $data): bool { - $client = []; $contact = []; @@ -232,13 +227,12 @@ class RequiredClientInfo extends Component ->push(); if ($contact_update && $client_update) { - $cg = CompanyGateway::find($this->company_gateway_id); - if($cg && $cg->update_details){ + if ($cg && $cg->update_details) { $payment_gateway = $cg->driver($this->client)->init(); - // if(method_exists($payment_gateway, "updateCustomer")) + // if(method_exists($payment_gateway, "updateCustomer")) // $payment_gateway->updateCustomer(); } @@ -269,7 +263,6 @@ class RequiredClientInfo extends Component } } } - } public function showCopyBillingCheckbox(): bool diff --git a/app/Http/Livewire/SubscriptionPlanSwitch.php b/app/Http/Livewire/SubscriptionPlanSwitch.php index 8a1f92128dc1..484493179b42 100644 --- a/app/Http/Livewire/SubscriptionPlanSwitch.php +++ b/app/Http/Livewire/SubscriptionPlanSwitch.php @@ -105,7 +105,9 @@ class SubscriptionPlanSwitch extends Component 'hash' => $this->hash, ]); - Cache::put($this->hash, [ + Cache::put( + $this->hash, + [ 'subscription_id' => $this->target->hashed_id, 'target_id' => $this->target->hashed_id, 'recurring_invoice' => $this->recurring_invoice->hashed_id, @@ -113,7 +115,7 @@ class SubscriptionPlanSwitch extends Component 'invoice_id' => $this->state['invoice']->hashed_id, 'context' => 'change_plan', now()->addMinutes(60), ] - ); + ); $this->state['payment_initialised'] = true; } else { diff --git a/app/Http/Livewire/WepaySignup.php b/app/Http/Livewire/WepaySignup.php index d4c747d83e65..7ef0b68ea0bd 100644 --- a/app/Http/Livewire/WepaySignup.php +++ b/app/Http/Livewire/WepaySignup.php @@ -20,7 +20,6 @@ use App\Models\CompanyGateway; use App\Models\GatewayType; use App\Models\User; use App\PaymentDrivers\WePayPaymentDriver; -use Illuminate\Support\Facades\Hash; use Livewire\Component; use WePay; diff --git a/app/Http/Middleware/ContactAccount.php b/app/Http/Middleware/ContactAccount.php index ce932f397c7d..1cecef46a1cd 100644 --- a/app/Http/Middleware/ContactAccount.php +++ b/app/Http/Middleware/ContactAccount.php @@ -11,7 +11,6 @@ namespace App\Http\Middleware; -use App\Libraries\MultiDB; use App\Models\Account; use App\Utils\Ninja; use Closure; diff --git a/app/Http/Middleware/ContactKeyLogin.php b/app/Http/Middleware/ContactKeyLogin.php index a8bb99e170e8..b45f1c465ca6 100644 --- a/app/Http/Middleware/ContactKeyLogin.php +++ b/app/Http/Middleware/ContactKeyLogin.php @@ -68,9 +68,9 @@ 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->company->settings->enable_client_portal_password) + if ($client_contact->company->settings->enable_client_portal_password) { return redirect()->route('client.login', ['company_key' => $client_contact->company->company_key]); + } if (empty($client_contact->email)) { $client_contact->email = Str::random(6).'@example.com'; @@ -88,9 +88,9 @@ class ContactKeyLogin } } elseif ($request->segment(2) && $request->segment(2) == 'key_login' && $request->segment(3)) { if ($client_contact = ClientContact::with('company')->where('contact_key', $request->segment(3))->first()) { - - if($client_contact->company->settings->enable_client_portal_password) + if ($client_contact->company->settings->enable_client_portal_password) { return redirect()->route('client.login', ['company_key' => $client_contact->company->company_key]); + } if (empty($client_contact->email)) { $client_contact->email = Str::random(6).'@example.com'; @@ -135,9 +135,9 @@ class ContactKeyLogin } } elseif ($request->segment(3)) { if ($client_contact = ClientContact::with('company')->where('contact_key', $request->segment(3))->first()) { - - if($client_contact->company->settings->enable_client_portal_password) + if ($client_contact->company->settings->enable_client_portal_password) { return redirect()->route('client.login', ['company_key' => $client_contact->company->company_key]); + } if (empty($client_contact->email)) { $client_contact->email = Str::random(6).'@example.com'; diff --git a/app/Http/Middleware/Cors.php b/app/Http/Middleware/Cors.php index f5cb51145651..869157ea686e 100644 --- a/app/Http/Middleware/Cors.php +++ b/app/Http/Middleware/Cors.php @@ -4,7 +4,6 @@ namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Response; -use Symfony\Component\HttpFoundation\BinaryFileResponse; class Cors { diff --git a/app/Http/Middleware/Locale.php b/app/Http/Middleware/Locale.php index e203a4d03233..cea5b9b8f7b6 100644 --- a/app/Http/Middleware/Locale.php +++ b/app/Http/Middleware/Locale.php @@ -14,7 +14,6 @@ namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Auth; class Locale { @@ -27,7 +26,6 @@ class Locale */ public function handle($request, Closure $next) { - /*LOCALE SET */ if ($request->has('lang')) { $locale = $request->input('lang'); diff --git a/app/Http/Middleware/PasswordProtection.php b/app/Http/Middleware/PasswordProtection.php index ddd0c51aa8ff..2c3aa7773b72 100644 --- a/app/Http/Middleware/PasswordProtection.php +++ b/app/Http/Middleware/PasswordProtection.php @@ -32,7 +32,6 @@ class PasswordProtection */ public function handle($request, Closure $next) { - $error = [ 'message' => 'Invalid Password', 'errors' => new stdClass, @@ -40,38 +39,33 @@ class PasswordProtection $timeout = auth()->user()->company()->default_password_timeout; - if($timeout == 0) + if ($timeout == 0) { $timeout = 30*60*1000*1000; - else + } else { $timeout = $timeout/1000; + } //test if password if base64 encoded $x_api_password = $request->header('X-API-PASSWORD'); - if($request->header('X-API-PASSWORD-BASE64')) - { + if ($request->header('X-API-PASSWORD-BASE64')) { $x_api_password = base64_decode($request->header('X-API-PASSWORD-BASE64')); } // If no password supplied - then we just check if their authentication is in cache // if (Cache::get(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in') && !$x_api_password) { - Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout); return $next($request); - - }elseif( $request->header('X-API-OAUTH-PASSWORD') && strlen($request->header('X-API-OAUTH-PASSWORD')) >=1){ - + } elseif ($request->header('X-API-OAUTH-PASSWORD') && strlen($request->header('X-API-OAUTH-PASSWORD')) >=1) { //user is attempting to reauth with OAuth - check the token value //todo expand this to include all OAuth providers - if(auth()->user()->oauth_provider_id == 'google') - { + if (auth()->user()->oauth_provider_id == 'google') { $user = false; $google = new Google(); $user = $google->getTokenResponse(request()->header('X-API-OAUTH-PASSWORD')); if (is_array($user)) { - $query = [ 'oauth_user_id' => $google->harvestSubField($user), 'oauth_provider_id'=> 'google' @@ -79,67 +73,47 @@ class PasswordProtection //If OAuth and user also has a password set - check both if ($existing_user = MultiDB::hasUser($query) && auth()->user()->company()->oauth_password_required && auth()->user()->has_password && Hash::check(auth()->user()->password, $x_api_password)) { - nlog("existing user with password"); Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout); return $next($request); - } - elseif($existing_user = MultiDB::hasUser($query) && !auth()->user()->company()->oauth_password_required){ - + } elseif ($existing_user = MultiDB::hasUser($query) && !auth()->user()->company()->oauth_password_required) { nlog("existing user without password"); Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout); - return $next($request); + return $next($request); } } - - } - elseif(auth()->user()->oauth_provider_id == 'microsoft') - { - try{ - $payload = json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', request()->header('X-API-OAUTH-PASSWORD'))[1])))); - } - catch(\Exception $e){ + } elseif (auth()->user()->oauth_provider_id == 'microsoft') { + try { + $payload = json_decode(base64_decode(str_replace('_', '/', str_replace('-', '+', explode('.', request()->header('X-API-OAUTH-PASSWORD'))[1])))); + } catch(\Exception $e) { nlog("could not decode microsoft response"); return response()->json(['message' => 'Could not decode the response from Microsoft'], 412); } - if($payload->preferred_username == auth()->user()->email){ - + if ($payload->preferred_username == auth()->user()->email) { Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout); return $next($request); } - } - elseif(auth()->user()->oauth_provider_id == 'apple') - { - + } elseif (auth()->user()->oauth_provider_id == 'apple') { $user = Socialite::driver('apple')->userFromToken($request->header('X-API-OAUTH-PASSWORD')); - if($user && ($user->email == auth()->user()->email)){ - + if ($user && ($user->email == auth()->user()->email)) { Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout); return $next($request); } - } return response()->json($error, 412); - - - }elseif ($x_api_password && Hash::check($x_api_password, auth()->user()->password)) { - + } elseif ($x_api_password && Hash::check($x_api_password, auth()->user()->password)) { Cache::put(auth()->user()->hashed_id.'_'.auth()->user()->account_id.'_logged_in', Str::random(64), $timeout); return $next($request); - } else { - return response()->json($error, 412); } - - } -} \ No newline at end of file +} diff --git a/app/Http/Middleware/QueryLogging.php b/app/Http/Middleware/QueryLogging.php index 2e8a6d052ab9..a41de37b2cb2 100644 --- a/app/Http/Middleware/QueryLogging.php +++ b/app/Http/Middleware/QueryLogging.php @@ -33,7 +33,6 @@ class QueryLogging */ public function handle(Request $request, Closure $next) { - // Enable query logging for development if (! Ninja::isHosted() || ! config('beacon.enabled')) { return $next($request); @@ -69,7 +68,7 @@ class QueryLogging $ip = request()->ip(); } - LightLogs::create(new DbQuery($request->method(), substr(urldecode($request->url()),0,180), $count, $time, $ip)) + LightLogs::create(new DbQuery($request->method(), substr(urldecode($request->url()), 0, 180), $count, $time, $ip)) ->batch(); } diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index b73804aec818..96640d0780c1 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -42,7 +42,7 @@ class RedirectIfAuthenticated case 'vendor': if (Auth::guard($guard)->check()) { //TODO create routes for vendor - // return redirect()->route('vendor.dashboard'); + // return redirect()->route('vendor.dashboard'); } break; default: diff --git a/app/Http/Middleware/SessionDomains.php b/app/Http/Middleware/SessionDomains.php index 4e7b7ddfd22a..261f84217c01 100644 --- a/app/Http/Middleware/SessionDomains.php +++ b/app/Http/Middleware/SessionDomains.php @@ -14,7 +14,6 @@ namespace App\Http\Middleware; use App\Utils\Ninja; use Closure; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cookie; class SessionDomains { diff --git a/app/Http/Middleware/SetInviteDb.php b/app/Http/Middleware/SetInviteDb.php index a6df51daa7ca..07dc7b4419d1 100644 --- a/app/Http/Middleware/SetInviteDb.php +++ b/app/Http/Middleware/SetInviteDb.php @@ -53,7 +53,6 @@ class SetInviteDb /* Try and determine the DB from the invitation key STRING*/ if (config('ninja.db.multi_db_enabled')) { - // nlog("/ Try and determine the DB from the invitation key /"); $hashids = new Hashids(config('ninja.hash_salt'), 10); diff --git a/app/Http/Middleware/StartupCheck.php b/app/Http/Middleware/StartupCheck.php index d4b3686ab91f..31d091e8a4ee 100644 --- a/app/Http/Middleware/StartupCheck.php +++ b/app/Http/Middleware/StartupCheck.php @@ -39,7 +39,6 @@ class StartupCheck foreach ($cached_tables as $name => $class) { if ($request->has('clear_cache') || ! Cache::has($name)) { - // check that the table exists in case the migration is pending if (! Schema::hasTable((new $class())->getTable())) { continue; diff --git a/app/Http/Middleware/TokenAuth.php b/app/Http/Middleware/TokenAuth.php index abd52376f098..00858a707b0a 100644 --- a/app/Http/Middleware/TokenAuth.php +++ b/app/Http/Middleware/TokenAuth.php @@ -11,7 +11,6 @@ namespace App\Http\Middleware; -use App\Events\User\UserLoggedIn; use App\Models\CompanyToken; use App\Models\User; use App\Utils\Ninja; @@ -70,7 +69,7 @@ class TokenAuth /* | This method binds the db to the jobs created using this - | session + | session */ app('queue')->createPayloadUsing(function () use ($company_token) { return ['db' => $company_token->company->db]; diff --git a/app/Http/Middleware/UserVerified.php b/app/Http/Middleware/UserVerified.php index f92209cab001..c951c13f3a6f 100644 --- a/app/Http/Middleware/UserVerified.php +++ b/app/Http/Middleware/UserVerified.php @@ -11,11 +11,9 @@ namespace App\Http\Middleware; -use App\Libraries\MultiDB; use App\Models\User; use App\Utils\Ninja; use Closure; -use Hashids\Hashids; use Illuminate\Http\Request; /** diff --git a/app/Http/Middleware/VendorContactKeyLogin.php b/app/Http/Middleware/VendorContactKeyLogin.php index c599ba7aac45..ae7e93ca1169 100644 --- a/app/Http/Middleware/VendorContactKeyLogin.php +++ b/app/Http/Middleware/VendorContactKeyLogin.php @@ -11,7 +11,6 @@ namespace App\Http\Middleware; -use App\Http\ViewComposers\PortalComposer; use App\Libraries\MultiDB; use App\Models\Vendor; use App\Models\VendorContact; @@ -148,8 +147,6 @@ class VendorContactKeyLogin private function setRedirectPath() { - return 'vendor/purchase_orders'; - } } diff --git a/app/Http/Middleware/VendorLocale.php b/app/Http/Middleware/VendorLocale.php index 580449a6a4a4..a64fc1ec41f5 100644 --- a/app/Http/Middleware/VendorLocale.php +++ b/app/Http/Middleware/VendorLocale.php @@ -14,7 +14,6 @@ namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Auth; class VendorLocale { diff --git a/app/Http/Middleware/VerifyHash.php b/app/Http/Middleware/VerifyHash.php index f572221bac1f..f06e5bca4ccc 100644 --- a/app/Http/Middleware/VerifyHash.php +++ b/app/Http/Middleware/VerifyHash.php @@ -2,10 +2,7 @@ namespace App\Http\Middleware; -use App\Models\Account; -use App\Models\Company; use App\Models\PaymentHash; -use App\Utils\Ninja; use Closure; use Illuminate\Http\Request; @@ -20,16 +17,14 @@ class VerifyHash */ public function handle($request, Closure $next) { - - if($request->has('payment_hash')){ - + if ($request->has('payment_hash')) { $ph = PaymentHash::with('fee_invoice')->where('hash', $request->payment_hash)->first(); - if($ph) + if ($ph) { auth()->guard('contact')->loginUsingId($ph->fee_invoice->invitations->first()->contact->id, true); + } return $next($request); - } abort(404, 'Unable to verify payment hash'); diff --git a/app/Http/Requests/Account/UpdateAccountRequest.php b/app/Http/Requests/Account/UpdateAccountRequest.php index c0373220c1e6..a55c1d7708c6 100644 --- a/app/Http/Requests/Account/UpdateAccountRequest.php +++ b/app/Http/Requests/Account/UpdateAccountRequest.php @@ -12,10 +12,6 @@ namespace App\Http\Requests\Account; use App\Http\Requests\Request; -use App\Http\ValidationRules\Account\BlackListRule; -use App\Http\ValidationRules\Account\EmailBlackListRule; -use App\Http\ValidationRules\NewUniqueUserRule; -use App\Utils\Ninja; class UpdateAccountRequest extends Request { diff --git a/app/Http/Requests/BankIntegration/AdminBankIntegrationRequest.php b/app/Http/Requests/BankIntegration/AdminBankIntegrationRequest.php index 7f9b8d3bed65..ffe01a3f2cf6 100644 --- a/app/Http/Requests/BankIntegration/AdminBankIntegrationRequest.php +++ b/app/Http/Requests/BankIntegration/AdminBankIntegrationRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\BankIntegration; use App\Http\Requests\Request; -use App\Models\BankIntegration; class AdminBankIntegrationRequest extends Request { diff --git a/app/Http/Requests/BankIntegration/BulkBankIntegrationRequest.php b/app/Http/Requests/BankIntegration/BulkBankIntegrationRequest.php index 6c424ed829c6..965b245608f0 100644 --- a/app/Http/Requests/BankIntegration/BulkBankIntegrationRequest.php +++ b/app/Http/Requests/BankIntegration/BulkBankIntegrationRequest.php @@ -27,11 +27,9 @@ class BulkBankIntegrationRequest extends Request public function rules() { - return [ 'ids' => 'required|bail|array', 'action' => 'in:archive,restore,delete' ]; - } } diff --git a/app/Http/Requests/BankIntegration/StoreBankIntegrationRequest.php b/app/Http/Requests/BankIntegration/StoreBankIntegrationRequest.php index 8e19c44aa7ac..753bf6fdc66b 100644 --- a/app/Http/Requests/BankIntegration/StoreBankIntegrationRequest.php +++ b/app/Http/Requests/BankIntegration/StoreBankIntegrationRequest.php @@ -31,7 +31,6 @@ class StoreBankIntegrationRequest extends Request public function rules() { - $rules = [ 'bank_account_name' => 'required|min:3', 'auto_sync' => 'sometimes|bool' @@ -44,8 +43,9 @@ class StoreBankIntegrationRequest extends Request { $input = $this->all(); - if((!array_key_exists('provider_name', $input) || strlen($input['provider_name']) == 0) && array_key_exists('bank_account_name', $input)) + if ((!array_key_exists('provider_name', $input) || strlen($input['provider_name']) == 0) && array_key_exists('bank_account_name', $input)) { $input['provider_name'] = $input['bank_account_name']; + } $this->replace($input); } @@ -54,5 +54,4 @@ class StoreBankIntegrationRequest extends Request { return []; } - } diff --git a/app/Http/Requests/BankIntegration/UpdateBankIntegrationRequest.php b/app/Http/Requests/BankIntegration/UpdateBankIntegrationRequest.php index 15e73ef2c74a..15b600ac8117 100644 --- a/app/Http/Requests/BankIntegration/UpdateBankIntegrationRequest.php +++ b/app/Http/Requests/BankIntegration/UpdateBankIntegrationRequest.php @@ -49,5 +49,4 @@ class UpdateBankIntegrationRequest extends Request $this->replace($input); } - } diff --git a/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php b/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php index 5254b79d91b7..bc784e850bbe 100644 --- a/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php +++ b/app/Http/Requests/BankTransaction/AdminBankTransactionRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\BankTransaction; use App\Http\Requests\Request; -use App\Models\BankTransaction; class AdminBankTransactionRequest extends Request { diff --git a/app/Http/Requests/BankTransaction/BulkBankTransactionRequest.php b/app/Http/Requests/BankTransaction/BulkBankTransactionRequest.php index 4b55fa697624..a95fb7fd23a3 100644 --- a/app/Http/Requests/BankTransaction/BulkBankTransactionRequest.php +++ b/app/Http/Requests/BankTransaction/BulkBankTransactionRequest.php @@ -27,11 +27,9 @@ class BulkBankTransactionRequest extends Request public function rules() { - return [ 'ids' => 'required|bail|array', 'action' => 'in:archive,restore,delete,convert_matched' ]; - } } diff --git a/app/Http/Requests/BankTransaction/ImportBankTransactionsRequest.php b/app/Http/Requests/BankTransaction/ImportBankTransactionsRequest.php index c07d6953f047..4eb0f3da1ffc 100644 --- a/app/Http/Requests/BankTransaction/ImportBankTransactionsRequest.php +++ b/app/Http/Requests/BankTransaction/ImportBankTransactionsRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\BankTransaction; use App\Http\Requests\Request; -use App\Models\BankTransaction; class ImportBankTransactionsRequest extends Request { @@ -28,7 +27,6 @@ class ImportBankTransactionsRequest extends Request public function rules() { - $rules = [ 'transactions' => 'bail|array', 'transactions.*.id' => 'bail|required', @@ -39,29 +37,28 @@ class ImportBankTransactionsRequest extends Request $rules['transactions.*.vendor_id'] = 'bail|sometimes|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; return $rules; - } public function prepareForValidation() { $inputs = $this->all(); - foreach($inputs['transactions'] as $key => $input) - { - - if(array_key_exists('id', $inputs['transactions'][$key])) + foreach ($inputs['transactions'] as $key => $input) { + if (array_key_exists('id', $inputs['transactions'][$key])) { $inputs['transactions'][$key]['id'] = $this->decodePrimaryKey($input['id']); + } - if(array_key_exists('ninja_category_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['ninja_category_id']) >= 1) + if (array_key_exists('ninja_category_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['ninja_category_id']) >= 1) { $inputs['transactions'][$key]['ninja_category_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['ninja_category_id']); + } - if(array_key_exists('vendor_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['vendor_id']) >= 1) + if (array_key_exists('vendor_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['vendor_id']) >= 1) { $inputs['transactions'][$key]['vendor_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['vendor_id']); + } // $input = $this->decodePrimaryKeys($input); } $this->replace($inputs); - } } diff --git a/app/Http/Requests/BankTransaction/MatchBankTransactionRequest.php b/app/Http/Requests/BankTransaction/MatchBankTransactionRequest.php index 2ec471cfea86..12946ad42d9d 100644 --- a/app/Http/Requests/BankTransaction/MatchBankTransactionRequest.php +++ b/app/Http/Requests/BankTransaction/MatchBankTransactionRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\BankTransaction; use App\Http\Requests\Request; -use App\Models\BankTransaction; use App\Models\Expense; use App\Models\Payment; @@ -30,7 +29,6 @@ class MatchBankTransactionRequest extends Request public function rules() { - $rules = [ 'transactions' => 'bail|array', 'transactions.*.invoice_ids' => 'nullable|string|sometimes', @@ -43,49 +41,46 @@ class MatchBankTransactionRequest extends Request $rules['transactions.*.expense_id'] = 'bail|sometimes|nullable|exists:expenses,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; return $rules; - } public function prepareForValidation() { $inputs = $this->all(); - foreach($inputs['transactions'] as $key => $input) - { - - if(array_key_exists('id', $inputs['transactions'][$key])) + foreach ($inputs['transactions'] as $key => $input) { + if (array_key_exists('id', $inputs['transactions'][$key])) { $inputs['transactions'][$key]['id'] = $this->decodePrimaryKey($input['id']); + } - if(array_key_exists('ninja_category_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['ninja_category_id']) >= 1) + if (array_key_exists('ninja_category_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['ninja_category_id']) >= 1) { $inputs['transactions'][$key]['ninja_category_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['ninja_category_id']); + } - if(array_key_exists('vendor_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['vendor_id']) >= 1) + if (array_key_exists('vendor_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['vendor_id']) >= 1) { $inputs['transactions'][$key]['vendor_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['vendor_id']); + } - if(array_key_exists('payment_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['payment_id']) >= 1){ + if (array_key_exists('payment_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['payment_id']) >= 1) { $inputs['transactions'][$key]['payment_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['payment_id']); $p = Payment::withTrashed()->where('company_id', auth()->user()->company()->id)->where('id', $inputs['transactions'][$key]['payment_id'])->first(); /*Ensure we don't relink an existing payment*/ - if(!$p || is_numeric($p->transaction_id)){ + if (!$p || is_numeric($p->transaction_id)) { unset($inputs['transactions'][$key]); } - } - if(array_key_exists('expense_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['expense_id']) >= 1){ + if (array_key_exists('expense_id', $inputs['transactions'][$key]) && strlen($inputs['transactions'][$key]['expense_id']) >= 1) { $inputs['transactions'][$key]['expense_id'] = $this->decodePrimaryKey($inputs['transactions'][$key]['expense_id']); $e = Expense::withTrashed()->where('company_id', auth()->user()->company()->id)->where('id', $inputs['transactions'][$key]['expense_id'])->first(); /*Ensure we don't relink an existing expense*/ - if(!$e || is_numeric($e->transaction_id)) + if (!$e || is_numeric($e->transaction_id)) { unset($inputs['transactions'][$key]['expense_id']); - + } } - } $this->replace($inputs); - } } diff --git a/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php b/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php index 2c6523a6dbfe..266aa4eb0328 100644 --- a/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php +++ b/app/Http/Requests/BankTransaction/StoreBankTransactionRequest.php @@ -31,7 +31,6 @@ class StoreBankTransactionRequest extends Request public function rules() { - $rules = []; $rules['bank_integration_id'] = 'bail|required|exists:bank_integrations,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; @@ -43,13 +42,12 @@ class StoreBankTransactionRequest extends Request { $input = $this->all(); - if(array_key_exists('bank_integration_id', $input) && $input['bank_integration_id'] == "") - unset($input['bank_integration_id']); - elseif(array_key_exists('bank_integration_id', $input) && strlen($input['bank_integration_id']) > 1 && !is_numeric($input['bank_integration_id'])) - $input['bank_integration_id'] = $this->decodePrimaryKey($input['bank_integration_id']); + if (array_key_exists('bank_integration_id', $input) && $input['bank_integration_id'] == "") { + unset($input['bank_integration_id']); + } elseif (array_key_exists('bank_integration_id', $input) && strlen($input['bank_integration_id']) > 1 && !is_numeric($input['bank_integration_id'])) { + $input['bank_integration_id'] = $this->decodePrimaryKey($input['bank_integration_id']); + } $this->replace($input); } - - } diff --git a/app/Http/Requests/BankTransaction/UpdateBankTransactionRequest.php b/app/Http/Requests/BankTransaction/UpdateBankTransactionRequest.php index e4da4dfc5fad..c774e8a1dd75 100644 --- a/app/Http/Requests/BankTransaction/UpdateBankTransactionRequest.php +++ b/app/Http/Requests/BankTransaction/UpdateBankTransactionRequest.php @@ -36,14 +36,17 @@ class UpdateBankTransactionRequest extends Request 'amount' => 'numeric|required', ]; - if (isset($this->currency_id)) + if (isset($this->currency_id)) { $rules['currency_id'] = 'sometimes|exists:currencies,id'; + } - if(isset($this->vendor_id)) + if (isset($this->vendor_id)) { $rules['vendor_id'] = 'bail|required|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } - if(isset($this->expense_id)) + if (isset($this->expense_id)) { $rules['expense_id'] = 'bail|required|exists:expenses,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } $rules['bank_integration_id'] = 'bail|required|exists:bank_integrations,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; @@ -56,24 +59,28 @@ class UpdateBankTransactionRequest extends Request $input = $this->all(); - if(array_key_exists('baseType', $input) && strlen($input['baseType']) > 1) - $input['base_type'] = $input['baseType']; //== 'deposit' ? 'CREDIT' : 'DEBIT'; + if (array_key_exists('baseType', $input) && strlen($input['baseType']) > 1) { + $input['base_type'] = $input['baseType']; + } //== 'deposit' ? 'CREDIT' : 'DEBIT'; - if(array_key_exists('vendor_id', $input) && strlen($input['vendor_id']) > 1) - $input['vendor_id'] = $this->decodePrimaryKey($input['vendor_id']); + if (array_key_exists('vendor_id', $input) && strlen($input['vendor_id']) > 1) { + $input['vendor_id'] = $this->decodePrimaryKey($input['vendor_id']); + } - if(array_key_exists('expense_id', $input) && strlen($input['expense_id']) > 1) - $input['expense_id'] = $this->decodePrimaryKey($input['expense_id']); + if (array_key_exists('expense_id', $input) && strlen($input['expense_id']) > 1) { + $input['expense_id'] = $this->decodePrimaryKey($input['expense_id']); + } - if(array_key_exists('ninja_category_id', $input) && strlen($input['ninja_category_id']) > 1) - $input['ninja_category_id'] = $this->decodePrimaryKey($input['ninja_category_id']); + if (array_key_exists('ninja_category_id', $input) && strlen($input['ninja_category_id']) > 1) { + $input['ninja_category_id'] = $this->decodePrimaryKey($input['ninja_category_id']); + } - if(array_key_exists('bank_integration_id', $input) && $input['bank_integration_id'] == "") - unset($input['bank_integration_id']); - elseif(array_key_exists('bank_integration_id', $input) && strlen($input['bank_integration_id']) > 1) - $input['bank_integration_id'] = $this->decodePrimaryKey($input['bank_integration_id']); + if (array_key_exists('bank_integration_id', $input) && $input['bank_integration_id'] == "") { + unset($input['bank_integration_id']); + } elseif (array_key_exists('bank_integration_id', $input) && strlen($input['bank_integration_id']) > 1) { + $input['bank_integration_id'] = $this->decodePrimaryKey($input['bank_integration_id']); + } $this->replace($input); } - } diff --git a/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php b/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php index 6e6509ee7615..1d5ae4b5b6f4 100644 --- a/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php +++ b/app/Http/Requests/BankTransactionRule/BulkBankTransactionRuleRequest.php @@ -27,11 +27,9 @@ class BulkBankTransactionRuleRequest extends Request public function rules() { - return [ 'ids' => 'required|bail|array', 'action' => 'in:archive,restore,delete' ]; - } } diff --git a/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php b/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php index 1a3341edfe4b..f0d9997252b7 100644 --- a/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php +++ b/app/Http/Requests/BankTransactionRule/StoreBankTransactionRuleRequest.php @@ -11,10 +11,10 @@ namespace App\Http\Requests\BankTransactionRule; -use App\Models\Account; use App\Http\Requests\Request; -use App\Utils\Traits\MakesHash; +use App\Models\Account; use App\Models\BankTransactionRule; +use App\Utils\Traits\MakesHash; class StoreBankTransactionRuleRequest extends Request { @@ -27,7 +27,8 @@ class StoreBankTransactionRuleRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', BankTransactionRule::class) && auth()->user()->account->hasFeature(Account::FEATURE_API);; + return auth()->user()->can('create', BankTransactionRule::class) && auth()->user()->account->hasFeature(Account::FEATURE_API); + ; } public function rules() @@ -44,14 +45,17 @@ class StoreBankTransactionRuleRequest extends Request 'applies_to' => 'bail|sometimes|string', ]; - if(isset($this->category_id)) + if (isset($this->category_id)) { $rules['category_id'] = 'bail|sometimes|exists:expense_categories,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } - if(isset($this->vendor_id)) + if (isset($this->vendor_id)) { $rules['vendor_id'] = 'bail|sometimes|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } - if(isset($this->client_id)) + if (isset($this->client_id)) { $rules['client_id'] = 'bail|sometimes|exists:clients,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } return $rules; @@ -65,7 +69,4 @@ class StoreBankTransactionRuleRequest extends Request $this->replace($input); } - - - } diff --git a/app/Http/Requests/BankTransactionRule/UpdateBankTransactionRuleRequest.php b/app/Http/Requests/BankTransactionRule/UpdateBankTransactionRuleRequest.php index c3d358479c3f..0ab11577fdae 100644 --- a/app/Http/Requests/BankTransactionRule/UpdateBankTransactionRuleRequest.php +++ b/app/Http/Requests/BankTransactionRule/UpdateBankTransactionRuleRequest.php @@ -42,14 +42,17 @@ class UpdateBankTransactionRuleRequest extends Request 'applies_to' => 'bail|sometimes|string', ]; - if(isset($this->category_id)) + if (isset($this->category_id)) { $rules['category_id'] = 'bail|sometimes|exists:expense_categories,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } - if(isset($this->vendor_id)) + if (isset($this->vendor_id)) { $rules['vendor_id'] = 'bail|sometimes|exists:vendors,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } - if(isset($this->client_id)) + if (isset($this->client_id)) { $rules['client_id'] = 'bail|sometimes|exists:clients,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } return $rules; @@ -63,5 +66,4 @@ class UpdateBankTransactionRuleRequest extends Request $this->replace($input); } - } diff --git a/app/Http/Requests/Chart/ShowChartRequest.php b/app/Http/Requests/Chart/ShowChartRequest.php index ce7f09113c4c..83754f2a86e0 100644 --- a/app/Http/Requests/Chart/ShowChartRequest.php +++ b/app/Http/Requests/Chart/ShowChartRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\Chart; use App\Http\Requests\Request; -use App\Models\Activity; class ShowChartRequest extends Request { diff --git a/app/Http/Requests/Client/AdjustClientLedgerRequest.php b/app/Http/Requests/Client/AdjustClientLedgerRequest.php index bea9d767e6cc..5ef789ff3143 100644 --- a/app/Http/Requests/Client/AdjustClientLedgerRequest.php +++ b/app/Http/Requests/Client/AdjustClientLedgerRequest.php @@ -13,7 +13,6 @@ namespace App\Http\Requests\Client; use App\Http\Requests\Request; use App\Utils\Traits\MakesHash; -use Illuminate\Validation\Rule; class AdjustClientLedgerRequest extends Request { diff --git a/app/Http/Requests/Client/BulkClientRequest.php b/app/Http/Requests/Client/BulkClientRequest.php index d02b8b932a77..b77c09a5277d 100644 --- a/app/Http/Requests/Client/BulkClientRequest.php +++ b/app/Http/Requests/Client/BulkClientRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\Client; use App\Http\Requests\Request; -use App\Models\Client; use App\Utils\Traits\MakesHash; use Illuminate\Validation\Rule; @@ -32,20 +31,19 @@ class BulkClientRequest extends Request public function rules() { - return [ - 'ids' => ['required','bail','array',Rule::exists('clients','id')->where('company_id', auth()->user()->company()->id)], + 'ids' => ['required','bail','array',Rule::exists('clients', 'id')->where('company_id', auth()->user()->company()->id)], 'action' => 'in:archive,restore,delete' ]; - } public function prepareForValidation() { $input = $this->all(); - if(isset($input['ids'])) + if (isset($input['ids'])) { $input['ids'] = $this->transformKeys($input['ids']); + } $this->replace($input); } diff --git a/app/Http/Requests/Client/StoreClientRequest.php b/app/Http/Requests/Client/StoreClientRequest.php index 2fcd04abdb04..91c03091659f 100644 --- a/app/Http/Requests/Client/StoreClientRequest.php +++ b/app/Http/Requests/Client/StoreClientRequest.php @@ -97,24 +97,25 @@ class StoreClientRequest extends Request $settings = (array)ClientSettings::defaults(); /* Stub settings if they don't exist */ - if(!array_key_exists('settings', $input)) + if (!array_key_exists('settings', $input)) { $input['settings'] = []; - elseif(is_object($input['settings'])) + } elseif (is_object($input['settings'])) { $input['settings'] = (array)$input['settings']; + } /* Merge default into base settings */ $input['settings'] = array_merge($input['settings'], $settings); /* Type and property enforcement */ - foreach ($input['settings'] as $key => $value) - { + foreach ($input['settings'] as $key => $value) { if ($key == 'default_task_rate') { $value = floatval($value); $input['settings'][$key] = $value; } - if($key == 'translations') + if ($key == 'translations') { unset($input['settings']['translations']); + } } /* Convert hashed IDs to IDs*/ @@ -129,7 +130,6 @@ class StoreClientRequest extends Request } else { $input['settings']['currency_id'] = (string) auth()->user()->company()->settings->currency_id; } - } elseif (! array_key_exists('currency_id', $input['settings'])) { $input['settings']['currency_id'] = (string) auth()->user()->company()->settings->currency_id; } @@ -141,8 +141,9 @@ class StoreClientRequest extends Request if (isset($input['language_code'])) { $input['settings']['language_id'] = $this->getLanguageId($input['language_code']); - if(strlen($input['settings']['language_id']) == 0) + if (strlen($input['settings']['language_id']) == 0) { unset($input['settings']['language_id']); + } } if (isset($input['country_code'])) { diff --git a/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php index 37d3c8fb906e..39eab01b6c21 100644 --- a/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php +++ b/app/Http/Requests/ClientGatewayToken/CreateClientGatewayTokenRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\ClientGatewayToken; use App\Http\Requests\Request; -use App\Models\ClientGatewayToken; class CreateClientGatewayTokenRequest extends Request { diff --git a/app/Http/Requests/ClientGatewayToken/ListClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/ListClientGatewayTokenRequest.php index d9664b4a79a3..affe6cc570f9 100644 --- a/app/Http/Requests/ClientGatewayToken/ListClientGatewayTokenRequest.php +++ b/app/Http/Requests/ClientGatewayToken/ListClientGatewayTokenRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\ClientGatewayToken; use App\Http\Requests\Request; -use App\Models\ClientGatewayToken; class ListClientGatewayTokenRequest extends Request { diff --git a/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php index 77cf214b1eeb..ff022150af9d 100644 --- a/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php +++ b/app/Http/Requests/ClientGatewayToken/StoreClientGatewayTokenRequest.php @@ -11,15 +11,9 @@ namespace App\Http\Requests\ClientGatewayToken; -use App\DataMapper\ClientSettings; use App\Http\Requests\Request; -use App\Http\ValidationRules\Ninja\CanStoreClientsRule; -use App\Http\ValidationRules\ValidClientGroupSettingsRule; use App\Models\Client; -use App\Models\GroupSetting; use App\Utils\Traits\MakesHash; -use Illuminate\Support\Facades\Cache; -use Illuminate\Validation\Rule; class StoreClientGatewayTokenRequest extends Request { diff --git a/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php b/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php index 89a9ae7eb09d..2499aa2c12f6 100644 --- a/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php +++ b/app/Http/Requests/ClientGatewayToken/UpdateClientGatewayTokenRequest.php @@ -11,12 +11,8 @@ namespace App\Http\Requests\ClientGatewayToken; -use App\DataMapper\CompanySettings; use App\Http\Requests\Request; -use App\Http\ValidationRules\ValidClientGroupSettingsRule; -use App\Utils\Traits\ChecksEntityStatus; use App\Utils\Traits\MakesHash; -use Illuminate\Validation\Rule; class UpdateClientGatewayTokenRequest extends Request { diff --git a/app/Http/Requests/ClientPortal/RegisterRequest.php b/app/Http/Requests/ClientPortal/RegisterRequest.php index 437ff679673d..52a37b985ac7 100644 --- a/app/Http/Requests/ClientPortal/RegisterRequest.php +++ b/app/Http/Requests/ClientPortal/RegisterRequest.php @@ -64,7 +64,6 @@ class RegisterRequest extends FormRequest public function company() { - //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(); diff --git a/app/Http/Requests/ClientPortal/Subscriptions/ShowPlanSwitchRequest.php b/app/Http/Requests/ClientPortal/Subscriptions/ShowPlanSwitchRequest.php index 1a906018d87d..6aa86843f739 100644 --- a/app/Http/Requests/ClientPortal/Subscriptions/ShowPlanSwitchRequest.php +++ b/app/Http/Requests/ClientPortal/Subscriptions/ShowPlanSwitchRequest.php @@ -16,7 +16,6 @@ use Illuminate\Foundation\Http\FormRequest; class ShowPlanSwitchRequest extends FormRequest { - /** * Determine if the user is authorized to make this request. * @@ -41,8 +40,6 @@ class ShowPlanSwitchRequest extends FormRequest protected function failedAuthorization() { - throw new ClientPortalAuthorizationException('Unable to change plans due to a restriction on this product.', 400); - } } diff --git a/app/Http/Requests/Company/StoreCompanyRequest.php b/app/Http/Requests/Company/StoreCompanyRequest.php index ae3ccf0194c1..b9219f000dd2 100644 --- a/app/Http/Requests/Company/StoreCompanyRequest.php +++ b/app/Http/Requests/Company/StoreCompanyRequest.php @@ -11,7 +11,6 @@ namespace App\Http\Requests\Company; -use App\DataMapper\CompanySettings; use App\Http\Requests\Request; use App\Http\ValidationRules\Company\ValidCompanyQuantity; use App\Http\ValidationRules\Company\ValidSubdomain; @@ -61,8 +60,9 @@ class StoreCompanyRequest extends Request { $input = $this->all(); - if(!isset($input['name'])) + if (!isset($input['name'])) { $input['name'] = 'Untitled Company'; + } if (array_key_exists('google_analytics_url', $input)) { $input['google_analytics_key'] = $input['google_analytics_url']; diff --git a/app/Http/Requests/Company/UpdateCompanyRequest.php b/app/Http/Requests/Company/UpdateCompanyRequest.php index f27ec426a83f..c2228b1c5052 100644 --- a/app/Http/Requests/Company/UpdateCompanyRequest.php +++ b/app/Http/Requests/Company/UpdateCompanyRequest.php @@ -71,7 +71,6 @@ class UpdateCompanyRequest extends Request public function prepareForValidation() { - $input = $this->all(); if (array_key_exists('portal_domain', $input) && strlen($input['portal_domain']) > 1) { @@ -100,16 +99,15 @@ class UpdateCompanyRequest extends Request { $account = $this->company->account; - if(Ninja::isHosted()) - { - foreach($this->protected_input as $protected_var) - { + if (Ninja::isHosted()) { + foreach ($this->protected_input as $protected_var) { $settings[$protected_var] = str_replace("script", "", $settings[$protected_var]); } } - if(isset($settings['email_style_custom'])) + if (isset($settings['email_style_custom'])) { $settings['email_style_custom'] = str_replace(['{{','}}'], ['',''], $settings['email_style_custom']); + } if (! $account->isFreeHostedClient()) { return $settings; @@ -128,8 +126,7 @@ class UpdateCompanyRequest extends Request private function addScheme($url, $scheme = 'https://') { - if(Ninja::isHosted()) - { + if (Ninja::isHosted()) { $url = str_replace('http://', '', $url); $url = parse_url($url, PHP_URL_SCHEME) === null ? $scheme.$url : $url; } diff --git a/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php index 9a1ec51e5788..444bf89291fe 100644 --- a/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php +++ b/app/Http/Requests/CompanyGateway/BulkCompanyGatewayRequest.php @@ -31,24 +31,20 @@ class BulkCompanyGatewayRequest extends Request public function rules() { - return [ - 'ids' => ['required','bail','array',Rule::exists('company_gateways','id')->where('company_id', auth()->user()->company()->id)], + 'ids' => ['required','bail','array',Rule::exists('company_gateways', 'id')->where('company_id', auth()->user()->company()->id)], 'action' => 'required|bail|in:archive,restore,delete' ]; - } public function prepareForValidation() { $input = $this->all(); - if(isset($input['ids'])) + if (isset($input['ids'])) { $input['ids'] = $this->transformKeys($input['ids']); + } $this->replace($input); } - - - } diff --git a/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php b/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php index 04f31d08ca5c..5f148f504354 100644 --- a/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php +++ b/app/Http/Requests/CompanyGateway/StoreCompanyGatewayRequest.php @@ -34,7 +34,7 @@ class StoreCompanyGatewayRequest extends Request public function rules() { $rules = [ - 'gateway_key' => ['bail', 'required','alpha_num',Rule::exists('gateways','key')], + 'gateway_key' => ['bail', 'required','alpha_num',Rule::exists('gateways', 'key')], 'fees_and_limits' => new ValidCompanyGatewayFeesAndLimitsRule(), ]; @@ -68,5 +68,4 @@ class StoreCompanyGatewayRequest extends Request $this->replace($input); } - } diff --git a/app/Http/Requests/Credit/BulkCreditRequest.php b/app/Http/Requests/Credit/BulkCreditRequest.php index 0a04dee09273..fd04b4216320 100644 --- a/app/Http/Requests/Credit/BulkCreditRequest.php +++ b/app/Http/Requests/Credit/BulkCreditRequest.php @@ -36,7 +36,7 @@ class BulkCreditRequest extends FormRequest public function rules() { return [ - 'ids' => ['required','bail','array',Rule::exists('credits','id')->where('company_id', auth()->user()->company()->id)], + 'ids' => ['required','bail','array',Rule::exists('credits', 'id')->where('company_id', auth()->user()->company()->id)], 'action' => 'required|bail|in:archive,restore,delete,email,bulk_download,bulk_print,mark_paid,clone_to_credit,history,mark_sent,download,send_email' ]; } @@ -45,10 +45,10 @@ class BulkCreditRequest extends FormRequest { $input = $this->all(); - if(isset($input['ids'])) + if (isset($input['ids'])) { $input['ids'] = $this->transformKeys($input['ids']); + } $this->replace($input); } - } diff --git a/app/Http/Requests/Design/StoreDesignRequest.php b/app/Http/Requests/Design/StoreDesignRequest.php index 73e494e09844..15e9cabd8bf9 100644 --- a/app/Http/Requests/Design/StoreDesignRequest.php +++ b/app/Http/Requests/Design/StoreDesignRequest.php @@ -11,8 +11,8 @@ namespace App\Http\Requests\Design; -use App\Models\Account; use App\Http\Requests\Request; +use App\Models\Account; class StoreDesignRequest extends Request { @@ -23,7 +23,8 @@ class StoreDesignRequest extends Request */ public function authorize() : bool { - return auth()->user()->isAdmin() && auth()->user()->account->hasFeature(Account::FEATURE_API);; + return auth()->user()->isAdmin() && auth()->user()->account->hasFeature(Account::FEATURE_API); + ; } public function rules() diff --git a/app/Http/Requests/Email/SendEmailRequest.php b/app/Http/Requests/Email/SendEmailRequest.php index 19ca5499f45a..bc5ec63d6ef0 100644 --- a/app/Http/Requests/Email/SendEmailRequest.php +++ b/app/Http/Requests/Email/SendEmailRequest.php @@ -57,11 +57,13 @@ class SendEmailRequest extends Request unset($input['template']); } - if(array_key_exists('entity_id', $input)) + if (array_key_exists('entity_id', $input)) { $input['entity_id'] = $this->decodePrimaryKey($input['entity_id']); + } - if(array_key_exists('entity', $input)) + if (array_key_exists('entity', $input)) { $input['entity'] = "App\Models\\".ucfirst(Str::camel($input['entity'])); + } $this->replace($input); } diff --git a/app/Http/Requests/Expense/StoreExpenseRequest.php b/app/Http/Requests/Expense/StoreExpenseRequest.php index b0956a85a3cc..ea8c71e0ac05 100644 --- a/app/Http/Requests/Expense/StoreExpenseRequest.php +++ b/app/Http/Requests/Expense/StoreExpenseRequest.php @@ -12,10 +12,8 @@ namespace App\Http\Requests\Expense; use App\Http\Requests\Request; -use App\Http\ValidationRules\Expense\UniqueExpenseNumberRule; use App\Models\Expense; use App\Models\Project; -use App\Models\PurchaseOrder; use App\Utils\Traits\MakesHash; use Illuminate\Validation\Rule; @@ -68,14 +66,11 @@ class StoreExpenseRequest extends Request if (array_key_exists('project_id', $input) && isset($input['project_id'])) { $project = Project::withTrashed()->where('id', $input['project_id'])->company()->first(); - if($project){ + if ($project) { $input['client_id'] = $project->client_id; - } - else - { + } else { unset($input['project_id']); } - } diff --git a/app/Http/Requests/Expense/UpdateExpenseRequest.php b/app/Http/Requests/Expense/UpdateExpenseRequest.php index e3ac76c89558..a8b0ee968250 100644 --- a/app/Http/Requests/Expense/UpdateExpenseRequest.php +++ b/app/Http/Requests/Expense/UpdateExpenseRequest.php @@ -68,14 +68,11 @@ class UpdateExpenseRequest extends Request if (array_key_exists('project_id', $input) && isset($input['project_id'])) { $project = Project::withTrashed()->where('id', $input['project_id'])->company()->first(); - if($project){ + if ($project) { $input['client_id'] = $project->client_id; - } - else - { + } else { unset($input['project_id']); } - } $this->replace($input); diff --git a/app/Http/Requests/Gateways/Mollie/Mollie3dsRequest.php b/app/Http/Requests/Gateways/Mollie/Mollie3dsRequest.php index 880312fc29d1..d3f4f5d7b7a6 100644 --- a/app/Http/Requests/Gateways/Mollie/Mollie3dsRequest.php +++ b/app/Http/Requests/Gateways/Mollie/Mollie3dsRequest.php @@ -13,7 +13,6 @@ namespace App\Http\Requests\Gateways\Mollie; use App\Models\Client; -use App\Models\ClientGatewayToken; use App\Models\Company; use App\Models\CompanyGateway; use App\Models\PaymentHash; diff --git a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php index 7e15f9a66a2e..ec629276068a 100644 --- a/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php +++ b/app/Http/Requests/GroupSetting/StoreGroupSettingRequest.php @@ -11,11 +11,11 @@ namespace App\Http\Requests\GroupSetting; +use App\DataMapper\ClientSettings; +use App\Http\Requests\Request; +use App\Http\ValidationRules\ValidClientGroupSettingsRule; use App\Models\Account; use App\Models\GroupSetting; -use App\Http\Requests\Request; -use App\DataMapper\ClientSettings; -use App\Http\ValidationRules\ValidClientGroupSettingsRule; class StoreGroupSettingRequest extends Request { diff --git a/app/Http/Requests/Invoice/ActionInvoiceRequest.php b/app/Http/Requests/Invoice/ActionInvoiceRequest.php index fc3bc1abbefb..30e078336b8b 100644 --- a/app/Http/Requests/Invoice/ActionInvoiceRequest.php +++ b/app/Http/Requests/Invoice/ActionInvoiceRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\Invoice; use App\Http\Requests\Request; -use App\Models\Invoice; use App\Utils\Traits\Invoice\ActionsInvoice; use App\Utils\Traits\MakesHash; @@ -70,4 +69,4 @@ class ActionInvoiceRequest extends Request 'action' => $this->error_msg, ]; } -} \ No newline at end of file +} diff --git a/app/Http/Requests/Invoice/BulkInvoiceRequest.php b/app/Http/Requests/Invoice/BulkInvoiceRequest.php index 7235d305f1e6..dbccd463803e 100644 --- a/app/Http/Requests/Invoice/BulkInvoiceRequest.php +++ b/app/Http/Requests/Invoice/BulkInvoiceRequest.php @@ -15,7 +15,6 @@ use App\Http\Requests\Request; class BulkInvoiceRequest extends Request { - public function authorize() : bool { return true; @@ -28,5 +27,4 @@ class BulkInvoiceRequest extends Request 'ids' => 'required' ]; } - } diff --git a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php index 0197f15869c0..0fbcf8cb3402 100644 --- a/app/Http/Requests/Invoice/UpdateInvoiceRequest.php +++ b/app/Http/Requests/Invoice/UpdateInvoiceRequest.php @@ -12,10 +12,8 @@ namespace App\Http\Requests\Invoice; use App\Http\Requests\Request; -use App\Http\ValidationRules\Invoice\InvoiceBalanceSanity; use App\Http\ValidationRules\Invoice\LockedInvoiceRule; use App\Http\ValidationRules\Project\ValidProjectForClient; -use App\Models\Invoice; use App\Utils\Traits\ChecksEntityStatus; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; diff --git a/app/Http/Requests/Login/LoginRequest.php b/app/Http/Requests/Login/LoginRequest.php index 63372bb94df8..7d0ab21d8cb0 100644 --- a/app/Http/Requests/Login/LoginRequest.php +++ b/app/Http/Requests/Login/LoginRequest.php @@ -46,5 +46,4 @@ class LoginRequest extends Request 'password' => 'required|max:1000', ]; } - } diff --git a/app/Http/Requests/Payment/StorePaymentRequest.php b/app/Http/Requests/Payment/StorePaymentRequest.php index 9614199f76b7..908c3fd65ad1 100644 --- a/app/Http/Requests/Payment/StorePaymentRequest.php +++ b/app/Http/Requests/Payment/StorePaymentRequest.php @@ -43,7 +43,7 @@ class StorePaymentRequest extends Request $invoices_total = 0; $credits_total = 0; - if (isset($input['client_id']) && is_string($input['client_id']) ) { + if (isset($input['client_id']) && is_string($input['client_id'])) { $input['client_id'] = $this->decodePrimaryKey($input['client_id']); } @@ -53,9 +53,9 @@ class StorePaymentRequest extends Request if (isset($input['invoices']) && is_array($input['invoices']) !== false) { foreach ($input['invoices'] as $key => $value) { - - if(is_string($value['invoice_id'])) + if (is_string($value['invoice_id'])) { $input['invoices'][$key]['invoice_id'] = $this->decodePrimaryKey($value['invoice_id']); + } if (array_key_exists('amount', $value)) { $invoices_total += $value['amount']; diff --git a/app/Http/Requests/Payments/PaymentNotificationWebhookRequest.php b/app/Http/Requests/Payments/PaymentNotificationWebhookRequest.php index 4b4bd406fe5a..f2e9a66fccca 100644 --- a/app/Http/Requests/Payments/PaymentNotificationWebhookRequest.php +++ b/app/Http/Requests/Payments/PaymentNotificationWebhookRequest.php @@ -14,11 +14,6 @@ namespace App\Http\Requests\Payments; use App\Http\Requests\Request; use App\Libraries\MultiDB; -use App\Models\Client; -use App\Models\Company; -use App\Models\CompanyGateway; -use App\Models\Payment; -use App\Models\PaymentHash; use App\Utils\Traits\MakesHash; class PaymentNotificationWebhookRequest extends Request diff --git a/app/Http/Requests/Payments/PaymentWebhookRequest.php b/app/Http/Requests/Payments/PaymentWebhookRequest.php index 0d338af471d4..f2e00d40dec3 100644 --- a/app/Http/Requests/Payments/PaymentWebhookRequest.php +++ b/app/Http/Requests/Payments/PaymentWebhookRequest.php @@ -14,7 +14,6 @@ namespace App\Http\Requests\Payments; use App\Http\Requests\Request; use App\Libraries\MultiDB; -use App\Models\Client; use App\Models\Company; use App\Models\CompanyGateway; use App\Models\Payment; @@ -48,7 +47,6 @@ class PaymentWebhookRequest extends Request MultiDB::findAndSetDbByCompanyKey($this->company_key); return CompanyGateway::withTrashed()->find($this->decodePrimaryKey($this->company_gateway_id)); - } /** diff --git a/app/Http/Requests/Preview/DesignPreviewRequest.php b/app/Http/Requests/Preview/DesignPreviewRequest.php index 46c3d0c01154..3d9a6cb973df 100644 --- a/app/Http/Requests/Preview/DesignPreviewRequest.php +++ b/app/Http/Requests/Preview/DesignPreviewRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\Preview; use App\Http\Requests\Request; -use App\Http\ValidationRules\Project\ValidProjectForClient; use App\Models\Credit; use App\Models\Invoice; use App\Models\PurchaseOrder; @@ -20,7 +19,6 @@ use App\Models\Quote; use App\Models\RecurringInvoice; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; -use Illuminate\Validation\Rule; class DesignPreviewRequest extends Request { @@ -34,10 +32,10 @@ class DesignPreviewRequest extends Request */ public function authorize() : bool { - return auth()->user()->can('create', Invoice::class) || - auth()->user()->can('create', Quote::class) || - auth()->user()->can('create', RecurringInvoice::class) || - auth()->user()->can('create', Credit::class) || + return auth()->user()->can('create', Invoice::class) || + auth()->user()->can('create', Quote::class) || + auth()->user()->can('create', RecurringInvoice::class) || + auth()->user()->can('create', Credit::class) || auth()->user()->can('create', PurchaseOrder::class); } diff --git a/app/Http/Requests/Preview/PreviewInvoiceRequest.php b/app/Http/Requests/Preview/PreviewInvoiceRequest.php index 59453725be65..75375c620934 100644 --- a/app/Http/Requests/Preview/PreviewInvoiceRequest.php +++ b/app/Http/Requests/Preview/PreviewInvoiceRequest.php @@ -12,14 +12,12 @@ namespace App\Http\Requests\Preview; use App\Http\Requests\Request; -use App\Http\ValidationRules\Project\ValidProjectForClient; use App\Models\Credit; use App\Models\Invoice; use App\Models\Quote; use App\Models\RecurringInvoice; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; -use Illuminate\Validation\Rule; class PreviewInvoiceRequest extends Request { diff --git a/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php b/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php index 6d72da9a3c88..eae0e42b36b0 100644 --- a/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php +++ b/app/Http/Requests/Preview/PreviewPurchaseOrderRequest.php @@ -12,15 +12,9 @@ namespace App\Http\Requests\Preview; use App\Http\Requests\Request; -use App\Http\ValidationRules\Project\ValidProjectForClient; -use App\Models\Credit; -use App\Models\Invoice; use App\Models\PurchaseOrder; -use App\Models\Quote; -use App\Models\RecurringInvoice; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; -use Illuminate\Validation\Rule; class PreviewPurchaseOrderRequest extends Request { @@ -55,7 +49,7 @@ class PreviewPurchaseOrderRequest extends Request $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; $input['amount'] = 0; $input['balance'] = 0; - $input['number'] = ctrans('texts.live_preview') . " #". rand(0,1000); + $input['number'] = ctrans('texts.live_preview') . " #". rand(0, 1000); $this->replace($input); } diff --git a/app/Http/Requests/PurchaseOrder/BulkPurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/BulkPurchaseOrderRequest.php index 0790444a1a49..28a581ffd3d8 100644 --- a/app/Http/Requests/PurchaseOrder/BulkPurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/BulkPurchaseOrderRequest.php @@ -15,7 +15,6 @@ use App\Http\Requests\Request; class BulkPurchaseOrderRequest extends Request { - /** * Determine if the user is authorized to make this request. * @@ -34,5 +33,4 @@ class BulkPurchaseOrderRequest extends Request 'action' => 'in:archive,restore,delete,email,bulk_download,bulk_print,mark_sent,download,send_email,add_to_inventory,expense,cancel' ]; } - } diff --git a/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php index 3fa224149fa1..21c82dda16c0 100644 --- a/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/StorePurchaseOrderRequest.php @@ -11,7 +11,6 @@ namespace App\Http\Requests\PurchaseOrder; - use App\Http\Requests\Request; use App\Models\PurchaseOrder; use App\Utils\Traits\CleanLineItems; @@ -57,13 +56,13 @@ class StorePurchaseOrderRequest extends Request $input = $this->decodePrimaryKeys($input); - if (isset($input['line_items']) && is_array($input['line_items'])) + if (isset($input['line_items']) && is_array($input['line_items'])) { $input['line_items'] = isset($input['line_items']) ? $this->cleanItems($input['line_items']) : []; + } $input['amount'] = 0; $input['balance'] = 0; $this->replace($input); } - } diff --git a/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php b/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php index e0a40251b7c2..a534153f3076 100644 --- a/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php +++ b/app/Http/Requests/PurchaseOrder/UploadPurchaseOrderRequest.php @@ -27,13 +27,12 @@ class UploadPurchaseOrderRequest extends Request public function rules() { + $rules = []; - $rules = []; - - if($this->input('documents')) + if ($this->input('documents')) { $rules['documents'] = 'file|mimes:csv,png,ai,jpeg,tiff,pdf,gif,psd,txt,doc,xls,ppt,xlsx,docx,pptx|max:2000000'; + } - return $rules; - + return $rules; } } diff --git a/app/Http/Requests/RecurringExpense/StoreRecurringExpenseRequest.php b/app/Http/Requests/RecurringExpense/StoreRecurringExpenseRequest.php index 2fc1f44d07d2..978989b3730f 100644 --- a/app/Http/Requests/RecurringExpense/StoreRecurringExpenseRequest.php +++ b/app/Http/Requests/RecurringExpense/StoreRecurringExpenseRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\RecurringExpense; use App\Http\Requests\Request; -use App\Http\ValidationRules\RecurringExpense\UniqueRecurringExpenseNumberRule; use App\Models\RecurringExpense; use App\Utils\Traits\MakesHash; use Illuminate\Validation\Rule; diff --git a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php index cee0ccd888ab..6b92361e9566 100644 --- a/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/StoreRecurringInvoiceRequest.php @@ -18,7 +18,6 @@ use App\Models\Client; use App\Models\RecurringInvoice; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; -use Illuminate\Http\UploadedFile; class StoreRecurringInvoiceRequest extends Request { @@ -74,7 +73,7 @@ class StoreRecurringInvoiceRequest extends Request { $input = $this->all(); - if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])){ + if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])) { $input['due_date_days'] = 'terms'; } diff --git a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php index 8b2343180a73..bbaeed17f9f6 100644 --- a/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php +++ b/app/Http/Requests/RecurringInvoice/UpdateRecurringInvoiceRequest.php @@ -16,7 +16,6 @@ use App\Http\ValidationRules\Project\ValidProjectForClient; use App\Utils\Traits\ChecksEntityStatus; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; -use Illuminate\Http\UploadedFile; use Illuminate\Validation\Rule; class UpdateRecurringInvoiceRequest extends Request @@ -68,7 +67,7 @@ class UpdateRecurringInvoiceRequest extends Request { $input = $this->all(); - if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])){ + if (array_key_exists('due_date_days', $input) && is_null($input['due_date_days'])) { $input['due_date_days'] = 'terms'; } diff --git a/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php index 5e783683861f..588ccaa80e9a 100644 --- a/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/StoreRecurringQuoteRequest.php @@ -17,7 +17,6 @@ use App\Models\Client; use App\Models\RecurringQuote; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; -use Illuminate\Http\UploadedFile; class StoreRecurringQuoteRequest extends Request { diff --git a/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php b/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php index b63a2e215aa5..9c58ad24a20e 100644 --- a/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php +++ b/app/Http/Requests/RecurringQuote/UpdateRecurringQuoteRequest.php @@ -15,7 +15,6 @@ use App\Http\Requests\Request; use App\Utils\Traits\ChecksEntityStatus; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; -use Illuminate\Http\UploadedFile; use Illuminate\Validation\Rule; class UpdateRecurringQuoteRequest extends Request diff --git a/app/Http/Requests/Report/GenericReportRequest.php b/app/Http/Requests/Report/GenericReportRequest.php index c17326cfe537..0789ec649476 100644 --- a/app/Http/Requests/Report/GenericReportRequest.php +++ b/app/Http/Requests/Report/GenericReportRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\Report; use App\Http\Requests\Request; -use Illuminate\Validation\Rule; class GenericReportRequest extends Request { @@ -28,7 +27,6 @@ class GenericReportRequest extends Request public function rules() { - return [ 'date_range' => 'bail|required|string', 'end_date' => 'bail|required_if:date_range,custom|nullable|date', @@ -58,7 +56,7 @@ class GenericReportRequest extends Request $input['start_date'] = null; $input['end_date'] = null; } -nlog($input); + nlog($input); $this->replace($input); } diff --git a/app/Http/Requests/Report/ProductSalesReportRequest.php b/app/Http/Requests/Report/ProductSalesReportRequest.php index c0399b8335f5..87b0f5ddf22e 100644 --- a/app/Http/Requests/Report/ProductSalesReportRequest.php +++ b/app/Http/Requests/Report/ProductSalesReportRequest.php @@ -13,7 +13,6 @@ namespace App\Http\Requests\Report; use App\Http\Requests\Request; use App\Utils\Traits\MakesHash; -use Illuminate\Validation\Rule; class ProductSalesReportRequest extends Request { @@ -31,7 +30,6 @@ class ProductSalesReportRequest extends Request public function rules() { - return [ 'date_range' => 'bail|required|string', 'end_date' => 'bail|required_if:date_range,custom|nullable|date', @@ -63,8 +61,9 @@ class ProductSalesReportRequest extends Request $input['end_date'] = null; } - if(array_key_exists('client_id', $input) && strlen($input['client_id']) >=1) + if (array_key_exists('client_id', $input) && strlen($input['client_id']) >=1) { $input['client_id'] = $this->decodePrimaryKey($input['client_id']); + } $this->replace($input); } diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index a26ed66e8536..7a8c300ecb2b 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -11,7 +11,6 @@ namespace App\Http\Requests; -use App\Http\Requests\RuntimeFormRequest; use App\Http\ValidationRules\User\RelatedUserRule; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Http\FormRequest; @@ -154,7 +153,6 @@ class Request extends FormRequest if (array_key_exists('vendor_contact_id', $input['invitations'][$key]) && is_string($input['invitations'][$key]['vendor_contact_id'])) { $input['invitations'][$key]['vendor_contact_id'] = $this->decodePrimaryKey($input['invitations'][$key]['vendor_contact_id']); } - } } @@ -198,8 +196,9 @@ class Request extends FormRequest public function checkTimeLog(array $log): bool { - if(count($log) == 0) + if (count($log) == 0) { return true; + } /*Get first value of all arrays*/ $result = array_column($log, 0); @@ -210,41 +209,44 @@ class Request extends FormRequest $new_array = []; /*Rebuild the array in order*/ - foreach($result as $key => $value) + foreach ($result as $key => $value) { $new_array[] = $log[$key]; + } /*Iterate through the array and perform checks*/ - foreach($new_array as $key => $array) - { + foreach ($new_array as $key => $array) { /*Flag which helps us know if there is a NEXT timelog*/ $next = false; /* If there are more than 1 time log in the array, ensure the last timestamp is not zero*/ - if(count($new_array) >1 && $array[1] == 0) + if (count($new_array) >1 && $array[1] == 0) { return false; + } - /* Check if the start time is greater than the end time */ - /* Ignore the last value for now, we'll do a separate check for this */ - if($array[0] > $array[1] && $array[1] != 0) + /* Check if the start time is greater than the end time */ + /* Ignore the last value for now, we'll do a separate check for this */ + if ($array[0] > $array[1] && $array[1] != 0) { return false; + } /* Find the next time log value - if it exists */ - if(array_key_exists($key+1, $new_array)) + if (array_key_exists($key+1, $new_array)) { $next = $new_array[$key+1]; + } /* check the next time log and ensure the start time is GREATER than the end time of the previous record */ - if($next && $next[0] < $array[1]) + if ($next && $next[0] < $array[1]) { return false; + } /* Get the last row of the timelog*/ $last_row = end($new_array); /*If the last value is NOT zero, ensure start time is not GREATER than the endtime */ - if($last_row[1] != 0 && $last_row[0] > $last_row[1]) + if ($last_row[1] != 0 && $last_row[0] > $last_row[1]) { return false; + } return true; } - } - } diff --git a/app/Http/Requests/StripeConnect/InitializeStripeConnectRequest.php b/app/Http/Requests/StripeConnect/InitializeStripeConnectRequest.php index 43770e0cdf4b..80791b424812 100644 --- a/app/Http/Requests/StripeConnect/InitializeStripeConnectRequest.php +++ b/app/Http/Requests/StripeConnect/InitializeStripeConnectRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\StripeConnect; -use App\Models\ClientContact; use App\Models\Company; use App\Models\User; use Illuminate\Foundation\Http\FormRequest; diff --git a/app/Http/Requests/Subscription/DestroySubscriptionRequest.php b/app/Http/Requests/Subscription/DestroySubscriptionRequest.php index a12ccf6740ce..20015d6260ed 100644 --- a/app/Http/Requests/Subscription/DestroySubscriptionRequest.php +++ b/app/Http/Requests/Subscription/DestroySubscriptionRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\Subscription; use App\Http\Requests\Request; -use Illuminate\Foundation\Http\FormRequest; class DestroySubscriptionRequest extends Request { diff --git a/app/Http/Requests/Subscription/EditSubscriptionRequest.php b/app/Http/Requests/Subscription/EditSubscriptionRequest.php index b219d4eca76d..3b5c0e67e097 100644 --- a/app/Http/Requests/Subscription/EditSubscriptionRequest.php +++ b/app/Http/Requests/Subscription/EditSubscriptionRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\Subscription; use App\Http\Requests\Request; -use Illuminate\Foundation\Http\FormRequest; class EditSubscriptionRequest extends Request { diff --git a/app/Http/Requests/Subscription/ShowSubscriptionRequest.php b/app/Http/Requests/Subscription/ShowSubscriptionRequest.php index c8896e7e1673..50a2b7318055 100644 --- a/app/Http/Requests/Subscription/ShowSubscriptionRequest.php +++ b/app/Http/Requests/Subscription/ShowSubscriptionRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\Subscription; use App\Http\Requests\Request; -use Illuminate\Foundation\Http\FormRequest; class ShowSubscriptionRequest extends Request { diff --git a/app/Http/Requests/Subscription/StoreSubscriptionRequest.php b/app/Http/Requests/Subscription/StoreSubscriptionRequest.php index aa781f351da1..2a358ac37a94 100644 --- a/app/Http/Requests/Subscription/StoreSubscriptionRequest.php +++ b/app/Http/Requests/Subscription/StoreSubscriptionRequest.php @@ -11,9 +11,9 @@ namespace App\Http\Requests\Subscription; +use App\Http\Requests\Request; use App\Models\Account; use App\Models\Subscription; -use App\Http\Requests\Request; use Illuminate\Validation\Rule; class StoreSubscriptionRequest extends Request @@ -37,8 +37,8 @@ class StoreSubscriptionRequest extends Request { $rules = [ 'name' => ['required', Rule::unique('subscriptions')->where('company_id', auth()->user()->company()->id)], - 'group_id' => ['bail','sometimes', 'nullable', Rule::exists('group_settings','id')->where('company_id', auth()->user()->company()->id)], - 'assigned_user_id' => ['bail','sometimes', 'nullable', Rule::exists('users','id')->where('account_id', auth()->user()->account_id)], + 'group_id' => ['bail','sometimes', 'nullable', Rule::exists('group_settings', 'id')->where('company_id', auth()->user()->company()->id)], + 'assigned_user_id' => ['bail','sometimes', 'nullable', Rule::exists('users', 'id')->where('account_id', auth()->user()->account_id)], 'product_ids' => 'bail|sometimes|nullable|string', 'recurring_product_ids' => 'bail|sometimes|nullable|string', 'is_recurring' => 'bail|sometimes|bool', diff --git a/app/Http/Requests/Subscription/UpdateSubscriptionRequest.php b/app/Http/Requests/Subscription/UpdateSubscriptionRequest.php index 9b6493c15a7c..811d38000c67 100644 --- a/app/Http/Requests/Subscription/UpdateSubscriptionRequest.php +++ b/app/Http/Requests/Subscription/UpdateSubscriptionRequest.php @@ -38,8 +38,8 @@ class UpdateSubscriptionRequest extends Request { $rules = [ 'name' => ['bail','sometimes', Rule::unique('subscriptions')->where('company_id', auth()->user()->company()->id)->ignore($this->subscription->id)], - 'group_id' => ['bail','sometimes', 'nullable', Rule::exists('group_settings','id')->where('company_id', auth()->user()->company()->id)], - 'assigned_user_id' => ['bail','sometimes', 'nullable', Rule::exists('users','id')->where('account_id', auth()->user()->account_id)], + 'group_id' => ['bail','sometimes', 'nullable', Rule::exists('group_settings', 'id')->where('company_id', auth()->user()->company()->id)], + 'assigned_user_id' => ['bail','sometimes', 'nullable', Rule::exists('users', 'id')->where('account_id', auth()->user()->account_id)], 'product_ids' => 'bail|sometimes|nullable|string', 'recurring_product_ids' => 'bail|sometimes|nullable|string', 'is_recurring' => 'bail|sometimes|bool', diff --git a/app/Http/Requests/Task/SortTaskRequest.php b/app/Http/Requests/Task/SortTaskRequest.php index 1edfea8c45d5..20ae64370cd4 100644 --- a/app/Http/Requests/Task/SortTaskRequest.php +++ b/app/Http/Requests/Task/SortTaskRequest.php @@ -23,7 +23,6 @@ class SortTaskRequest extends Request public function authorize() : bool { return true; - } public function rules() diff --git a/app/Http/Requests/Task/StoreTaskRequest.php b/app/Http/Requests/Task/StoreTaskRequest.php index 0d0247902050..b5d160316e08 100644 --- a/app/Http/Requests/Task/StoreTaskRequest.php +++ b/app/Http/Requests/Task/StoreTaskRequest.php @@ -39,23 +39,24 @@ class StoreTaskRequest extends Request $rules['number'] = Rule::unique('tasks')->where('company_id', auth()->user()->company()->id); } - if(isset($this->client_id)) + if (isset($this->client_id)) { $rules['client_id'] = 'bail|required|exists:clients,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } - if(isset($this->project_id)) + if (isset($this->project_id)) { $rules['project_id'] = 'bail|required|exists:projects,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } $rules['timelog'] = ['bail','array',function ($attribute, $values, $fail) { - - foreach($values as $k) - { - if(!is_int($k[0]) || !is_int($k[1])) - $fail('The '.$attribute.' - '.print_r($k,1).' is invalid. Unix timestamps only.'); + foreach ($values as $k) { + if (!is_int($k[0]) || !is_int($k[1])) { + $fail('The '.$attribute.' - '.print_r($k, 1).' is invalid. Unix timestamps only.'); + } } - if(!$this->checkTimeLog($values)) + if (!$this->checkTimeLog($values)) { $fail('Please correct overlapping values'); - + } }]; @@ -74,15 +75,12 @@ class StoreTaskRequest extends Request /* Ensure the project is related */ if (array_key_exists('project_id', $input) && isset($input['project_id'])) { $project = Project::withTrashed()->where('id', $input['project_id'])->company()->first(); -; - if($project){ + ; + if ($project) { $input['client_id'] = $project->client_id; - } - else - { + } else { unset($input['project_id']); } - } $this->replace($input); diff --git a/app/Http/Requests/Task/UpdateTaskRequest.php b/app/Http/Requests/Task/UpdateTaskRequest.php index 2046a5e8f868..8917e44643d4 100644 --- a/app/Http/Requests/Task/UpdateTaskRequest.php +++ b/app/Http/Requests/Task/UpdateTaskRequest.php @@ -29,10 +29,12 @@ class UpdateTaskRequest extends Request * @return bool */ public function authorize() : bool - {nlog("oioi"); + { + nlog("oioi"); //prevent locked tasks from updating - if($this->task->invoice_id && $this->task->company->invoice_task_lock) + if ($this->task->invoice_id && $this->task->company->invoice_task_lock) { return false; + } return auth()->user()->can('edit', $this->task); } @@ -45,23 +47,24 @@ class UpdateTaskRequest extends Request $rules['number'] = Rule::unique('tasks')->where('company_id', auth()->user()->company()->id)->ignore($this->task->id); } - if(isset($this->client_id)) + if (isset($this->client_id)) { $rules['client_id'] = 'bail|required|exists:clients,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } - if(isset($this->project_id)) + if (isset($this->project_id)) { $rules['project_id'] = 'bail|required|exists:projects,id,company_id,'.auth()->user()->company()->id.',is_deleted,0'; + } $rules['timelog'] = ['bail','array',function ($attribute, $values, $fail) { - - foreach($values as $k) - { - if(!is_int($k[0]) || !is_int($k[1])) - $fail('The '.$attribute.' - '.print_r($k,1).' is invalid. Unix timestamps only.'); + foreach ($values as $k) { + if (!is_int($k[0]) || !is_int($k[1])) { + $fail('The '.$attribute.' - '.print_r($k, 1).' is invalid. Unix timestamps only.'); + } } - if(!$this->checkTimeLog($values)) + if (!$this->checkTimeLog($values)) { $fail('Please correct overlapping values'); - + } }]; return $this->globalRules($rules); @@ -79,14 +82,11 @@ class UpdateTaskRequest extends Request if (array_key_exists('project_id', $input) && isset($input['project_id'])) { $project = Project::withTrashed()->where('id', $input['project_id'])->company()->first(); - if($project){ + if ($project) { $input['client_id'] = $project->client_id; - } - else - { + } else { unset($input['project_id']); } - } if (array_key_exists('color', $input) && is_null($input['color'])) { @@ -101,5 +101,4 @@ class UpdateTaskRequest extends Request { throw new AuthorizationException(ctrans('texts.task_update_authorization_error')); } - } diff --git a/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php b/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php index 8b4a343d8ea8..2d84a13f9164 100644 --- a/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/CreateSchedulerRequest.php @@ -24,5 +24,4 @@ class CreateSchedulerRequest extends Request { return auth()->user()->isAdmin(); } - } diff --git a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php index 656e5f5fe3e6..9061d57912d6 100644 --- a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php @@ -13,7 +13,6 @@ namespace App\Http\Requests\TaskScheduler; use App\Http\Requests\Request; use App\Http\ValidationRules\Scheduler\ValidClientIds; -use App\Models\Client; use App\Utils\Traits\MakesHash; use Illuminate\Validation\Rule; @@ -32,7 +31,6 @@ class StoreSchedulerRequest extends Request public function rules() { - $rules = [ 'name' => ['bail', 'required', Rule::unique('schedulers')->where('company_id', auth()->user()->company()->id)], 'is_paused' => 'bail|sometimes|boolean', @@ -45,19 +43,16 @@ class StoreSchedulerRequest extends Request ]; return $rules; - } public function prepareForValidation() { - $input = $this->all(); - if (array_key_exists('next_run', $input) && is_string($input['next_run'])) + if (array_key_exists('next_run', $input) && is_string($input['next_run'])) { $this->merge(['next_run_client' => $input['next_run']]); + } return $input; } - - } diff --git a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php index bc1d02b0553a..02a5e69b5351 100644 --- a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php @@ -27,7 +27,6 @@ class UpdateSchedulerRequest extends Request public function rules(): array { - $rules = [ 'name' => ['bail', 'sometimes', Rule::unique('schedulers')->where('company_id', auth()->user()->company()->id)->ignore($this->task_scheduler->id)], 'is_paused' => 'bail|sometimes|boolean', @@ -39,19 +38,16 @@ class UpdateSchedulerRequest extends Request ]; return $rules; - } public function prepareForValidation() { - $input = $this->all(); - if (array_key_exists('next_run', $input) && is_string($input['next_run'])) + if (array_key_exists('next_run', $input) && is_string($input['next_run'])) { $this->merge(['next_run_client' => $input['next_run']]); + } return $input; - } - } diff --git a/app/Http/Requests/TaskStatus/ActionTaskStatusRequest.php b/app/Http/Requests/TaskStatus/ActionTaskStatusRequest.php index 3df02d2dde86..1091c06e22af 100644 --- a/app/Http/Requests/TaskStatus/ActionTaskStatusRequest.php +++ b/app/Http/Requests/TaskStatus/ActionTaskStatusRequest.php @@ -27,11 +27,9 @@ class ActionTaskStatusRequest extends Request public function rules() { - return [ 'ids' => 'required|bail|array', 'action' => 'in:archive,restore,delete' ]; - } } diff --git a/app/Http/Requests/Token/UpdateTokenRequest.php b/app/Http/Requests/Token/UpdateTokenRequest.php index 20f572e28bf7..584dce16b22f 100644 --- a/app/Http/Requests/Token/UpdateTokenRequest.php +++ b/app/Http/Requests/Token/UpdateTokenRequest.php @@ -34,5 +34,4 @@ class UpdateTokenRequest extends Request 'name' => 'required', ]; } - } diff --git a/app/Http/Requests/Twilio/Confirm2faRequest.php b/app/Http/Requests/Twilio/Confirm2faRequest.php index b6da44d00171..d686e6345463 100644 --- a/app/Http/Requests/Twilio/Confirm2faRequest.php +++ b/app/Http/Requests/Twilio/Confirm2faRequest.php @@ -14,10 +14,8 @@ namespace App\Http\Requests\Twilio; use App\Http\Requests\Request; use App\Libraries\MultiDB; - class Confirm2faRequest extends Request { - /** * Determine if the user is authorized to make this request. * @@ -30,7 +28,6 @@ class Confirm2faRequest extends Request public function rules() { - return [ 'code' => 'required', 'email' => 'required|exists:users,email', @@ -41,10 +38,10 @@ class Confirm2faRequest extends Request { $input = $this->all(); - if(array_key_exists('email', $input)) + if (array_key_exists('email', $input)) { MultiDB::userFindAndSetDb($input['email']); + } $this->replace($input); } - } diff --git a/app/Http/Requests/Twilio/ConfirmSmsRequest.php b/app/Http/Requests/Twilio/ConfirmSmsRequest.php index 1ed81d622739..8ef72e05c655 100644 --- a/app/Http/Requests/Twilio/ConfirmSmsRequest.php +++ b/app/Http/Requests/Twilio/ConfirmSmsRequest.php @@ -13,10 +13,8 @@ namespace App\Http\Requests\Twilio; use App\Http\Requests\Request; - class ConfirmSmsRequest extends Request { - /** * Determine if the user is authorized to make this request. * @@ -29,10 +27,8 @@ class ConfirmSmsRequest extends Request public function rules() { - return [ 'code' => 'required', ]; } - } diff --git a/app/Http/Requests/Twilio/Generate2faRequest.php b/app/Http/Requests/Twilio/Generate2faRequest.php index f4cbaa196a4a..d34190faaabc 100644 --- a/app/Http/Requests/Twilio/Generate2faRequest.php +++ b/app/Http/Requests/Twilio/Generate2faRequest.php @@ -14,10 +14,8 @@ namespace App\Http\Requests\Twilio; use App\Http\Requests\Request; use App\Libraries\MultiDB; - class Generate2faRequest extends Request { - /** * Determine if the user is authorized to make this request. * @@ -31,21 +29,19 @@ class Generate2faRequest extends Request public function rules() { - return [ 'email' => 'required|exists:users,email', ]; - } public function prepareForValidation() { $input = $this->all(); - if(array_key_exists('email', $input)) + if (array_key_exists('email', $input)) { MultiDB::userFindAndSetDb($input['email']); + } $this->replace($input); } - } diff --git a/app/Http/Requests/Twilio/GenerateSmsRequest.php b/app/Http/Requests/Twilio/GenerateSmsRequest.php index deeef41cafaa..c503cc12b5bb 100644 --- a/app/Http/Requests/Twilio/GenerateSmsRequest.php +++ b/app/Http/Requests/Twilio/GenerateSmsRequest.php @@ -13,10 +13,8 @@ namespace App\Http\Requests\Twilio; use App\Http\Requests\Request; - class GenerateSmsRequest extends Request { - /** * Determine if the user is authorized to make this request. * @@ -30,10 +28,8 @@ class GenerateSmsRequest extends Request public function rules() { - return [ 'phone' => 'required|regex:^\+[1-9]\d{1,14}$^', ]; - } } diff --git a/app/Http/Requests/TwoFactor/EnableTwoFactorRequest.php b/app/Http/Requests/TwoFactor/EnableTwoFactorRequest.php index bddd6f23dd94..9c6293c8bd20 100644 --- a/app/Http/Requests/TwoFactor/EnableTwoFactorRequest.php +++ b/app/Http/Requests/TwoFactor/EnableTwoFactorRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\TwoFactor; use App\Http\Requests\Request; -use Illuminate\Validation\Rule; class EnableTwoFactorRequest extends Request { @@ -23,7 +22,8 @@ class EnableTwoFactorRequest extends Request */ public function authorize() : bool { - return true;; + return true; + ; } public function rules() @@ -36,6 +36,5 @@ class EnableTwoFactorRequest extends Request public function prepareForValidation() { - } } diff --git a/app/Http/Requests/User/BulkUserRequest.php b/app/Http/Requests/User/BulkUserRequest.php index 109e86c5f758..1ae2ee8dca63 100644 --- a/app/Http/Requests/User/BulkUserRequest.php +++ b/app/Http/Requests/User/BulkUserRequest.php @@ -13,7 +13,6 @@ namespace App\Http\Requests\User; use App\Http\Requests\Request; use App\Http\ValidationRules\Ninja\CanRestoreUserRule; -use App\Http\ValidationRules\UniqueUserRule; use App\Utils\Ninja; class BulkUserRequest extends Request diff --git a/app/Http/Requests/User/StoreUserRequest.php b/app/Http/Requests/User/StoreUserRequest.php index 4b6ed76574f8..179b6238809a 100644 --- a/app/Http/Requests/User/StoreUserRequest.php +++ b/app/Http/Requests/User/StoreUserRequest.php @@ -11,7 +11,6 @@ namespace App\Http\Requests\User; -use App\DataMapper\DefaultSettings; use App\Factory\UserFactory; use App\Http\Requests\Request; use App\Http\ValidationRules\Ninja\CanAddUserRule; @@ -21,7 +20,6 @@ use App\Http\ValidationRules\ValidUserForCompany; use App\Libraries\MultiDB; use App\Models\User; use App\Utils\Ninja; -use Illuminate\Validation\Rule; class StoreUserRequest extends Request { @@ -51,9 +49,9 @@ class StoreUserRequest extends Request if (Ninja::isHosted()) { $rules['id'] = new CanAddUserRule(); - if($this->phone && isset($this->phone)) + if ($this->phone && isset($this->phone)) { $rules['phone'] = ['bail', 'string', 'sometimes', new HasValidPhoneNumber()]; - + } } return $rules; diff --git a/app/Http/Requests/User/UpdateUserRequest.php b/app/Http/Requests/User/UpdateUserRequest.php index 69dd646752d5..2bbc24e21e85 100644 --- a/app/Http/Requests/User/UpdateUserRequest.php +++ b/app/Http/Requests/User/UpdateUserRequest.php @@ -18,7 +18,6 @@ use App\Utils\Ninja; class UpdateUserRequest extends Request { - private bool $phone_has_changed = false; /** @@ -43,8 +42,9 @@ class UpdateUserRequest extends Request $rules['email'] = ['email', 'sometimes', new UniqueUserRule($this->user, $input['email'])]; } - if(Ninja::isHosted() && $this->phone_has_changed && $this->phone && isset($this->phone)) + if (Ninja::isHosted() && $this->phone_has_changed && $this->phone && isset($this->phone)) { $rules['phone'] = ['sometimes', 'bail', 'string', new HasValidPhoneNumber()]; + } return $rules; } @@ -65,14 +65,14 @@ class UpdateUserRequest extends Request $input['last_name'] = strip_tags($input['last_name']); } - if(array_key_exists('phone', $input) && isset($input['phone']) && strlen($input['phone']) > 1 && ($this->user->phone != $input['phone'])){ + if (array_key_exists('phone', $input) && isset($input['phone']) && strlen($input['phone']) > 1 && ($this->user->phone != $input['phone'])) { $this->phone_has_changed = true; } - if(array_key_exists('oauth_provider_id', $input) && $input['oauth_provider_id'] == '') + if (array_key_exists('oauth_provider_id', $input) && $input['oauth_provider_id'] == '') { $input['oauth_user_id'] = ''; + } $this->replace($input); } - } diff --git a/app/Http/Requests/Vendor/StoreVendorRequest.php b/app/Http/Requests/Vendor/StoreVendorRequest.php index a35baa725b2d..dc67adcbffa4 100644 --- a/app/Http/Requests/Vendor/StoreVendorRequest.php +++ b/app/Http/Requests/Vendor/StoreVendorRequest.php @@ -12,7 +12,6 @@ namespace App\Http\Requests\Vendor; use App\Http\Requests\Request; -use App\Http\ValidationRules\ValidVendorGroupSettingsRule; use App\Models\Vendor; use App\Utils\Traits\MakesHash; use Illuminate\Validation\Rule; @@ -42,8 +41,9 @@ class StoreVendorRequest extends Request $rules['contacts.*.email'] = 'bail|nullable|distinct|sometimes|email'; - if (isset($this->number)) + if (isset($this->number)) { $rules['number'] = Rule::unique('vendors')->where('company_id', $user->company()->id); + } $rules['currency_id'] = 'bail|required|exists:currencies,id'; @@ -58,7 +58,7 @@ class StoreVendorRequest extends Request $input = $this->all(); - if(!array_key_exists('currency_id', $input) || empty($input['currency_id'])){ + if (!array_key_exists('currency_id', $input) || empty($input['currency_id'])) { $input['currency_id'] = $user->company()->settings->currency_id; } diff --git a/app/Http/Requests/Vendor/UpdateVendorRequest.php b/app/Http/Requests/Vendor/UpdateVendorRequest.php index a02e72a3b443..8beda8c22eef 100644 --- a/app/Http/Requests/Vendor/UpdateVendorRequest.php +++ b/app/Http/Requests/Vendor/UpdateVendorRequest.php @@ -64,8 +64,9 @@ class UpdateVendorRequest extends Request $input['assigned_user_id'] = $this->decodePrimaryKey($input['assigned_user_id']); } - if(array_key_exists('country_id', $input) && is_null($input['country_id'])) + if (array_key_exists('country_id', $input) && is_null($input['country_id'])) { unset($input['country_id']); + } $input = $this->decodePrimaryKeys($input); diff --git a/app/Http/Requests/Webhook/StoreWebhookRequest.php b/app/Http/Requests/Webhook/StoreWebhookRequest.php index 7fd5d372c24a..b6f0ed24bf1b 100644 --- a/app/Http/Requests/Webhook/StoreWebhookRequest.php +++ b/app/Http/Requests/Webhook/StoreWebhookRequest.php @@ -11,8 +11,8 @@ namespace App\Http\Requests\Webhook; -use App\Models\Account; use App\Http\Requests\Request; +use App\Models\Account; class StoreWebhookRequest extends Request { @@ -40,10 +40,11 @@ class StoreWebhookRequest extends Request { $input = $this->all(); - if(!isset($input['rest_method'])) + if (!isset($input['rest_method'])) { $input['rest_method'] = 'post'; - // if(isset($input['headers']) && count($input['headers']) == 0) - // $input['headers'] = null; + } + // if(isset($input['headers']) && count($input['headers']) == 0) + // $input['headers'] = null; $this->replace($input); } diff --git a/app/Http/Requests/Webhook/UpdateWebhookRequest.php b/app/Http/Requests/Webhook/UpdateWebhookRequest.php index 21b46163a16b..d8fd2ed783cd 100644 --- a/app/Http/Requests/Webhook/UpdateWebhookRequest.php +++ b/app/Http/Requests/Webhook/UpdateWebhookRequest.php @@ -44,10 +44,11 @@ class UpdateWebhookRequest extends Request { $input = $this->all(); - if(!isset($input['rest_method'])) + if (!isset($input['rest_method'])) { $input['rest_method'] = 'post'; + } - // if(isset($input['headers']) && count($input['headers']) == 0) + // if(isset($input['headers']) && count($input['headers']) == 0) // $input['headers'] = null; $this->replace($input); diff --git a/app/Http/Requests/Yodlee/YodleeAdminRequest.php b/app/Http/Requests/Yodlee/YodleeAdminRequest.php index b161e14d8539..0ef06a68aa88 100644 --- a/app/Http/Requests/Yodlee/YodleeAdminRequest.php +++ b/app/Http/Requests/Yodlee/YodleeAdminRequest.php @@ -15,7 +15,6 @@ use App\Http\Requests\Request; class YodleeAdminRequest extends Request { - /** * Determine if the user is authorized to make this request. * @@ -35,5 +34,4 @@ class YodleeAdminRequest extends Request { return []; } - -} \ No newline at end of file +} diff --git a/app/Http/Requests/Yodlee/YodleeAuthRequest.php b/app/Http/Requests/Yodlee/YodleeAuthRequest.php index 37709a095ec6..ff267c5f98f5 100644 --- a/app/Http/Requests/Yodlee/YodleeAuthRequest.php +++ b/app/Http/Requests/Yodlee/YodleeAuthRequest.php @@ -19,7 +19,6 @@ use Illuminate\Support\Facades\Cache; class YodleeAuthRequest extends Request { - /** * Determine if the user is authorized to make this request. * @@ -56,15 +55,12 @@ class YodleeAuthRequest extends Request MultiDB::findAndSetDbByCompanyKey($this->getTokenContent()['company_key']); return User::findOrFail($this->getTokenContent()['user_id']); - } public function getCompany() { - MultiDB::findAndSetDbByCompanyKey($this->getTokenContent()['company_key']); return Company::where('company_key', $this->getTokenContent()['company_key'])->firstOrFail(); - } -} \ No newline at end of file +} diff --git a/app/Http/ValidationRules/Account/BlackListRule.php b/app/Http/ValidationRules/Account/BlackListRule.php index 90cb41ac2a76..c79d1270afef 100644 --- a/app/Http/ValidationRules/Account/BlackListRule.php +++ b/app/Http/ValidationRules/Account/BlackListRule.php @@ -11,7 +11,6 @@ namespace App\Http\ValidationRules\Account; -use App\Libraries\MultiDB; use Illuminate\Contracts\Validation\Rule; /** diff --git a/app/Http/ValidationRules/Account/EmailBlackListRule.php b/app/Http/ValidationRules/Account/EmailBlackListRule.php index 23448f89fe39..43e3451d1b6c 100644 --- a/app/Http/ValidationRules/Account/EmailBlackListRule.php +++ b/app/Http/ValidationRules/Account/EmailBlackListRule.php @@ -11,7 +11,6 @@ namespace App\Http\ValidationRules\Account; -use App\Libraries\MultiDB; use Illuminate\Contracts\Validation\Rule; /** diff --git a/app/Http/ValidationRules/Company/ValidCompanyQuantity.php b/app/Http/ValidationRules/Company/ValidCompanyQuantity.php index c8e257add07c..aae4328f4e8d 100644 --- a/app/Http/ValidationRules/Company/ValidCompanyQuantity.php +++ b/app/Http/ValidationRules/Company/ValidCompanyQuantity.php @@ -26,7 +26,6 @@ class ValidCompanyQuantity implements Rule */ public function passes($attribute, $value) { - if (Ninja::isSelfHost()) { return auth()->user()->company()->account->companies->count() < 10; } diff --git a/app/Http/ValidationRules/Credit/ValidCreditsRules.php b/app/Http/ValidationRules/Credit/ValidCreditsRules.php index 8a2c9b2c7f20..7b6fc32aed88 100644 --- a/app/Http/ValidationRules/Credit/ValidCreditsRules.php +++ b/app/Http/ValidationRules/Credit/ValidCreditsRules.php @@ -53,8 +53,7 @@ class ValidCreditsRules implements Rule $total_credit_amount = array_sum(array_column($this->input['credits'], 'amount')); - if($total_credit_amount <= 0){ - + if ($total_credit_amount <= 0) { $this->error_msg = "Total of credits must be more than zero."; return false; diff --git a/app/Http/ValidationRules/Ninja/CanAddUserRule.php b/app/Http/ValidationRules/Ninja/CanAddUserRule.php index adccb9c1de08..6e19dbd09b14 100644 --- a/app/Http/ValidationRules/Ninja/CanAddUserRule.php +++ b/app/Http/ValidationRules/Ninja/CanAddUserRule.php @@ -31,7 +31,6 @@ class CanAddUserRule implements Rule */ public function passes($attribute, $value) { - /* If the user is active then we can add them to the company */ if (User::where('email', request()->input('email'))->where('account_id', auth()->user()->account_id)->where('is_deleted', 0)->exists()) { return true; diff --git a/app/Http/ValidationRules/Ninja/CanRestoreUserRule.php b/app/Http/ValidationRules/Ninja/CanRestoreUserRule.php index c3c1d2525b61..a73e4ce555e1 100644 --- a/app/Http/ValidationRules/Ninja/CanRestoreUserRule.php +++ b/app/Http/ValidationRules/Ninja/CanRestoreUserRule.php @@ -12,7 +12,6 @@ namespace App\Http\ValidationRules\Ninja; use App\Models\CompanyUser; -use App\Models\User; use Illuminate\Contracts\Validation\Rule; /** diff --git a/app/Http/ValidationRules/Scheduler/ValidClientIds.php b/app/Http/ValidationRules/Scheduler/ValidClientIds.php index 8326db809e25..64086bc5e906 100644 --- a/app/Http/ValidationRules/Scheduler/ValidClientIds.php +++ b/app/Http/ValidationRules/Scheduler/ValidClientIds.php @@ -28,9 +28,7 @@ class ValidClientIds implements Rule */ public function passes($attribute, $value) { - return Client::where('company_id', auth()->user()->company()->id)->whereIn('id', $this->transformKeys($value))->count() == count($value); - } /** diff --git a/app/Http/ValidationRules/User/HasValidPhoneNumber.php b/app/Http/ValidationRules/User/HasValidPhoneNumber.php index 997e26e5510b..72c6b79d0f45 100644 --- a/app/Http/ValidationRules/User/HasValidPhoneNumber.php +++ b/app/Http/ValidationRules/User/HasValidPhoneNumber.php @@ -11,8 +11,6 @@ namespace App\Http\ValidationRules\User; -use App\Models\CompanyUser; -use App\Models\User; use Illuminate\Contracts\Validation\Rule; /** @@ -26,8 +24,8 @@ class HasValidPhoneNumber implements Rule { } - public function message() - { + public function message() + { return [ 'phone' => ctrans('texts.phone_validation_error'), ]; @@ -40,44 +38,41 @@ class HasValidPhoneNumber implements Rule */ public function passes($attribute, $value) { + $sid = config('ninja.twilio_account_sid'); + $token = config('ninja.twilio_auth_token'); - $sid = config('ninja.twilio_account_sid'); - $token = config('ninja.twilio_auth_token'); + if (!$sid) { + return true; + } - if(!$sid) - return true; - - if(is_null($value)) + if (is_null($value)) { return false; + } - $twilio = new \Twilio\Rest\Client($sid, $token); + $twilio = new \Twilio\Rest\Client($sid, $token); - $country = auth()->user()->account?->companies()?->first()?->country(); + $country = auth()->user()->account?->companies()?->first()?->country(); - if(!$country || strlen(auth()->user()->phone) < 2) - return true; + if (!$country || strlen(auth()->user()->phone) < 2) { + return true; + } - $countryCode = $country->iso_3166_2; + $countryCode = $country->iso_3166_2; - try{ - - $phone_number = $twilio->lookups->v1->phoneNumbers($value) - ->fetch(["countryCode" => $countryCode]); + try { + $phone_number = $twilio->lookups->v1->phoneNumbers($value) + ->fetch(["countryCode" => $countryCode]); $user = auth()->user(); request()->merge(['validated_phone' => $phone_number->phoneNumber ]); - $user->verified_phone_number = false; + $user->verified_phone_number = false; $user->save(); return true; - - } - catch(\Exception $e) { - return false; - } - + } catch(\Exception $e) { + return false; + } } - } diff --git a/app/Http/ValidationRules/ValidAmount.php b/app/Http/ValidationRules/ValidAmount.php index 6f296e4f205a..4438b935ad9b 100644 --- a/app/Http/ValidationRules/ValidAmount.php +++ b/app/Http/ValidationRules/ValidAmount.php @@ -11,7 +11,6 @@ namespace App\Http\ValidationRules; -use App\Libraries\MultiDB; use Illuminate\Contracts\Validation\Rule; /** diff --git a/app/Http/ValidationRules/ValidRefundableInvoices.php b/app/Http/ValidationRules/ValidRefundableInvoices.php index f430ebad5806..d14b37844689 100644 --- a/app/Http/ValidationRules/ValidRefundableInvoices.php +++ b/app/Http/ValidationRules/ValidRefundableInvoices.php @@ -71,7 +71,6 @@ class ValidRefundableInvoices implements Rule foreach ($this->input['invoices'] as $val) { if ($val['invoice_id'] == $invoice->id) { - //$pivot_record = $invoice->payments->where('id', $invoice->id)->first(); $pivot_record = $payment->paymentables->where('paymentable_id', $invoice->id)->first(); diff --git a/app/Http/ViewComposers/PortalComposer.php b/app/Http/ViewComposers/PortalComposer.php index 6203df8e9a66..10261419bffd 100644 --- a/app/Http/ViewComposers/PortalComposer.php +++ b/app/Http/ViewComposers/PortalComposer.php @@ -14,7 +14,6 @@ namespace App\Http\ViewComposers; use App\Utils\Ninja; use App\Utils\TranslationHelper; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; use Illuminate\View\View; /** diff --git a/app/Import/Definitions/BankTransactionMap.php b/app/Import/Definitions/BankTransactionMap.php index 138f8d5d0ad0..b6482926ee8c 100644 --- a/app/Import/Definitions/BankTransactionMap.php +++ b/app/Import/Definitions/BankTransactionMap.php @@ -44,4 +44,4 @@ class BankTransactionMap 9 => 'texts.type', ]; } -} \ No newline at end of file +} diff --git a/app/Import/Providers/BaseImport.php b/app/Import/Providers/BaseImport.php index 938115dfe010..1d1954dfa0c5 100644 --- a/app/Import/Providers/BaseImport.php +++ b/app/Import/Providers/BaseImport.php @@ -15,7 +15,6 @@ use App\Factory\ClientFactory; use App\Factory\InvoiceFactory; use App\Factory\PaymentFactory; use App\Factory\QuoteFactory; -use App\Http\Requests\Invoice\StoreInvoiceRequest; use App\Http\Requests\Quote\StoreQuoteRequest; use App\Import\ImportException; use App\Jobs\Mail\NinjaMailerJob; @@ -31,12 +30,9 @@ use App\Repositories\PaymentRepository; use App\Repositories\QuoteRepository; use App\Utils\Traits\CleanLineItems; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Validator; -use Illuminate\Support\Str; use League\Csv\Reader; use League\Csv\Statement; -use Symfony\Component\HttpFoundation\ParameterBag; class BaseImport { @@ -152,7 +148,7 @@ class BaseImport private function runValidation($data) - { + { $_syn_request_class = new $this->request_name; $_syn_request_class->setContainer(app()); $_syn_request_class->initialize($data); @@ -163,7 +159,6 @@ class BaseImport $_syn_request_class->setValidator($validator); return $validator; - } public function ingest($data, $entity_type) @@ -173,8 +168,7 @@ class BaseImport $is_free_hosted_client = $this->company->account->isFreeHostedClient(); $hosted_client_count = $this->company->account->hosted_client_count; - if($this->factory_name == 'App\Factory\ClientFactory' && $is_free_hosted_client && (count($data) > $hosted_client_count)) - { + if ($this->factory_name == 'App\Factory\ClientFactory' && $is_free_hosted_client && (count($data) > $hosted_client_count)) { $this->error_array[$entity_type][] = [ $entity_type => 'client', 'error' => 'Error, you are attempting to import more clients than your plan allows', @@ -184,12 +178,12 @@ class BaseImport } foreach ($data as $key => $record) { - try { $entity = $this->transformer->transform($record); - if(!$entity) + if (!$entity) { continue; + } $validator = $this->runValidation($entity); @@ -226,9 +220,8 @@ class BaseImport 'error' => $message, ]; - nlog("Ingest {$ex->getMessage()}"); - nlog($record); - + nlog("Ingest {$ex->getMessage()}"); + nlog($record); } } @@ -415,7 +408,6 @@ class BaseImport } return $count; - } private function actionInvoiceStatus( @@ -568,11 +560,9 @@ class BaseImport 'error' => $message, ]; } - } return $count; - } protected function getUserIDForRecord($record) diff --git a/app/Import/Providers/Csv.php b/app/Import/Providers/Csv.php index 7ecb4417dadb..895b874634d2 100644 --- a/app/Import/Providers/Csv.php +++ b/app/Import/Providers/Csv.php @@ -27,9 +27,7 @@ use App\Http\Requests\Payment\StorePaymentRequest; use App\Http\Requests\Product\StoreProductRequest; use App\Http\Requests\Quote\StoreQuoteRequest; use App\Http\Requests\Vendor\StoreVendorRequest; -use App\Import\ImportException; -use App\Import\Providers\BaseImport; -use App\Import\Providers\ImportInterface; +use App\Import\Transformer\Bank\BankTransformer; use App\Import\Transformer\Csv\ClientTransformer; use App\Import\Transformer\Csv\ExpenseTransformer; use App\Import\Transformer\Csv\InvoiceTransformer; @@ -37,7 +35,6 @@ use App\Import\Transformer\Csv\PaymentTransformer; use App\Import\Transformer\Csv\ProductTransformer; use App\Import\Transformer\Csv\QuoteTransformer; use App\Import\Transformer\Csv\VendorTransformer; -use App\Import\Transformer\Bank\BankTransformer; use App\Repositories\BankTransactionRepository; use App\Repositories\ClientRepository; use App\Repositories\ExpenseRepository; @@ -48,8 +45,6 @@ use App\Repositories\QuoteRepository; use App\Repositories\VendorRepository; use App\Services\Bank\BankMatchingService; use App\Utils\Traits\MakesHash; -use Illuminate\Support\Facades\Validator; -use Symfony\Component\HttpFoundation\ParameterBag; class Csv extends BaseImport implements ImportInterface { @@ -81,16 +76,12 @@ class Csv extends BaseImport implements ImportInterface $data = $this->getCsvData($entity_type); - if (is_array($data)) - { - + if (is_array($data)) { $data = $this->preTransformCsv($data, $entity_type); - foreach($data as $key => $value) - { + foreach ($data as $key => $value) { $data[$key]['transaction.bank_integration_id'] = $this->decodePrimaryKey($this->request['bank_integration_id']); } - } if (empty($data)) { @@ -111,7 +102,6 @@ class Csv extends BaseImport implements ImportInterface nlog("bank matching co id = {$this->company->id}"); (new BankMatchingService($this->company->id, $this->company->db))->handle(); - } public function client() diff --git a/app/Import/Providers/Freshbooks.php b/app/Import/Providers/Freshbooks.php index e3d02b621652..d6df4a9b2b07 100644 --- a/app/Import/Providers/Freshbooks.php +++ b/app/Import/Providers/Freshbooks.php @@ -73,7 +73,6 @@ class Freshbooks extends BaseImport public function invoice() { - //make sure we update and create products with wave $initial_update_products_value = $this->company->update_products; $this->company->update_products = true; diff --git a/app/Import/Providers/Invoice2Go.php b/app/Import/Providers/Invoice2Go.php index 0d56666f5139..48a656a7cbcc 100644 --- a/app/Import/Providers/Invoice2Go.php +++ b/app/Import/Providers/Invoice2Go.php @@ -11,12 +11,9 @@ namespace App\Import\Providers; -use App\Factory\ClientFactory; use App\Factory\InvoiceFactory; -use App\Http\Requests\Client\StoreClientRequest; use App\Http\Requests\Invoice\StoreInvoiceRequest; use App\Import\Transformer\Invoice2Go\InvoiceTransformer; -use App\Repositories\ClientRepository; use App\Repositories\InvoiceRepository; class Invoice2Go extends BaseImport @@ -45,7 +42,6 @@ class Invoice2Go extends BaseImport public function invoice() { - //make sure we update and create products with wave $initial_update_products_value = $this->company->update_products; $this->company->update_products = true; diff --git a/app/Import/Providers/Invoicely.php b/app/Import/Providers/Invoicely.php index bec43bb35623..b92ea01732be 100644 --- a/app/Import/Providers/Invoicely.php +++ b/app/Import/Providers/Invoicely.php @@ -72,7 +72,6 @@ class Invoicely extends BaseImport public function invoice() { - //make sure we update and create products with wave $initial_update_products_value = $this->company->update_products; $this->company->update_products = true; diff --git a/app/Import/Providers/Wave.php b/app/Import/Providers/Wave.php index 1794304d1131..9543c704a2e9 100644 --- a/app/Import/Providers/Wave.php +++ b/app/Import/Providers/Wave.php @@ -85,13 +85,11 @@ class Wave extends BaseImport implements ImportInterface public function product() { - //done automatically inside the invoice() method as we need to harvest the products from the line items } public function invoice() { - //make sure we update and create products with wave $initial_update_products_value = $this->company->update_products; $this->company->update_products = true; @@ -170,7 +168,7 @@ class Wave extends BaseImport implements ImportInterface $data = $this->getCsvData($entity_type); - if(!$data){ + if (!$data) { $this->entity_count['expense'] = 0; return; } @@ -279,6 +277,5 @@ class Wave extends BaseImport implements ImportInterface } return $count; - } } diff --git a/app/Import/Providers/Zoho.php b/app/Import/Providers/Zoho.php index 9c245471a789..38a2e829b959 100644 --- a/app/Import/Providers/Zoho.php +++ b/app/Import/Providers/Zoho.php @@ -74,7 +74,6 @@ class Zoho extends BaseImport public function invoice() { - //make sure we update and create products with wave $initial_update_products_value = $this->company->update_products; $this->company->update_products = true; diff --git a/app/Import/Transformer/Bank/BankTransformer.php b/app/Import/Transformer/Bank/BankTransformer.php index 648967063dd4..bff66a30e895 100644 --- a/app/Import/Transformer/Bank/BankTransformer.php +++ b/app/Import/Transformer/Bank/BankTransformer.php @@ -11,10 +11,7 @@ namespace App\Import\Transformer\Bank; -use App\Import\ImportException; use App\Import\Transformer\BaseTransformer; -use App\Models\BankTransaction; -use App\Utils\Number; /** * Class BankTransformer. @@ -28,11 +25,11 @@ class BankTransformer extends BaseTransformer */ public function transform($transaction) { - $now = now(); + $now = now(); - $transformed = [ + $transformed = [ 'bank_integration_id' => $transaction['transaction.bank_integration_id'], - 'transaction_id' => $this->getNumber($transaction,'transaction.transaction_id'), + 'transaction_id' => $this->getNumber($transaction, 'transaction.transaction_id'), 'amount' => abs($this->getFloat($transaction, 'transaction.amount')), 'currency_id' => $this->getCurrencyByCode($transaction, 'transaction.currency'), 'account_type' => strlen($this->getString($transaction, 'transaction.account_type')) > 1 ? $this->getString($transaction, 'transaction.account_type') : 'bank', @@ -55,27 +52,30 @@ class BankTransformer extends BaseTransformer private function calculateType($transaction) { + if (array_key_exists('transaction.base_type', $transaction) && (($transaction['transaction.base_type'] == 'CREDIT') || strtolower($transaction['transaction.base_type']) == 'deposit')) { + return 'CREDIT'; + } - if(array_key_exists('transaction.base_type', $transaction) && (($transaction['transaction.base_type'] == 'CREDIT') || strtolower($transaction['transaction.base_type']) == 'deposit')) - return 'CREDIT'; + if (array_key_exists('transaction.base_type', $transaction) && (($transaction['transaction.base_type'] == 'DEBIT') || strtolower($transaction['transaction.base_type']) == 'withdrawal')) { + return 'DEBIT'; + } - if(array_key_exists('transaction.base_type', $transaction) && (($transaction['transaction.base_type'] == 'DEBIT') || strtolower($transaction['transaction.base_type']) == 'withdrawal')) - return 'DEBIT'; + if (array_key_exists('transaction.category_id', $transaction)) { + return 'DEBIT'; + } - if(array_key_exists('transaction.category_id', $transaction)) - return 'DEBIT'; + if (array_key_exists('transaction.category_type', $transaction) && $transaction['transaction.category_type'] == 'Income') { + return 'CREDIT'; + } - if(array_key_exists('transaction.category_type', $transaction) && $transaction['transaction.category_type'] == 'Income') - return 'CREDIT'; + if (array_key_exists('transaction.category_type', $transaction)) { + return 'DEBIT'; + } - if(array_key_exists('transaction.category_type', $transaction)) - return 'DEBIT'; - - if(array_key_exists('transaction.amount', $transaction) && is_numeric($transaction['transaction.amount']) && $transaction['transaction.amount'] > 0) - return 'CREDIT'; - - return 'DEBIT'; + if (array_key_exists('transaction.amount', $transaction) && is_numeric($transaction['transaction.amount']) && $transaction['transaction.amount'] > 0) { + return 'CREDIT'; + } + return 'DEBIT'; } - -} \ No newline at end of file +} diff --git a/app/Import/Transformer/BaseTransformer.php b/app/Import/Transformer/BaseTransformer.php index 437486b72dcf..989f821145ec 100644 --- a/app/Import/Transformer/BaseTransformer.php +++ b/app/Import/Transformer/BaseTransformer.php @@ -14,21 +14,19 @@ namespace App\Import\Transformer; use App\Factory\ExpenseCategoryFactory; use App\Factory\ProjectFactory; use App\Factory\VendorFactory; +use App\Models\Client; use App\Models\ClientContact; use App\Models\Country; -use App\Models\ExpenseCategory; -use App\Models\PaymentType; -use App\Models\User; use App\Models\Expense; -use App\Models\Project; +use App\Models\ExpenseCategory; use App\Models\Invoice; -use App\Models\Quote; -use App\Models\Client; -use App\Models\TaxRate; +use App\Models\PaymentType; use App\Models\Product; +use App\Models\Project; +use App\Models\Quote; +use App\Models\TaxRate; use App\Models\Vendor; use App\Utils\Number; -use Exception; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Cache; @@ -46,26 +44,19 @@ class BaseTransformer public function parseDate($date) { - - try{ - + try { $parsed_date = Carbon::parse($date); return $parsed_date->format('Y-m-d'); - - } - catch(\Exception $e){ - + } catch(\Exception $e) { $parsed_date = date('Y-m-d', strtotime($date)); - if($parsed_date == '1970-01-01') + if ($parsed_date == '1970-01-01') { return now()->format('Y-m-d'); + } return $parsed_date; - } - - } public function getInvoiceTypeId($data, $field) @@ -107,7 +98,6 @@ class BaseTransformer public function getClient($client_name, $client_email) { - if (! empty($client_name)) { $client_id_search = Client::where('company_id', $this->company->id) ->where('is_deleted', false) diff --git a/app/Import/Transformer/Csv/ExpenseTransformer.php b/app/Import/Transformer/Csv/ExpenseTransformer.php index 5bca96630429..2aee2e7dda45 100644 --- a/app/Import/Transformer/Csv/ExpenseTransformer.php +++ b/app/Import/Transformer/Csv/ExpenseTransformer.php @@ -42,7 +42,7 @@ class ExpenseTransformer extends BaseTransformer 'client_id' => isset($data['expense.client']) ? $this->getClientId($data['expense.client']) : null, - 'date' => strlen($this->getString($data, 'expense.date') > 1) ? date('Y-m-d', strtotime(str_replace("/","-",$data['expense.date']))) : now()->format('Y-m-d'), + 'date' => strlen($this->getString($data, 'expense.date') > 1) ? date('Y-m-d', strtotime(str_replace("/", "-", $data['expense.date']))) : now()->format('Y-m-d'), 'public_notes' => $this->getString($data, 'expense.public_notes'), 'private_notes' => $this->getString($data, 'expense.private_notes'), 'category_id' => isset($data['expense.category']) @@ -55,7 +55,7 @@ class ExpenseTransformer extends BaseTransformer ? $this->getPaymentTypeId($data['expense.payment_type']) : null, 'payment_date' => isset($data['expense.payment_date']) - ? date('Y-m-d', strtotime(str_replace("/","-",$data['expense.payment_date']))) + ? date('Y-m-d', strtotime(str_replace("/", "-", $data['expense.payment_date']))) : null, 'custom_value1' => $this->getString($data, 'expense.custom_value1'), 'custom_value2' => $this->getString($data, 'expense.custom_value2'), diff --git a/app/Import/Transformer/Csv/InvoiceTransformer.php b/app/Import/Transformer/Csv/InvoiceTransformer.php index 07da5f3b4879..76447deb7f71 100644 --- a/app/Import/Transformer/Csv/InvoiceTransformer.php +++ b/app/Import/Transformer/Csv/InvoiceTransformer.php @@ -13,7 +13,6 @@ namespace App\Import\Transformer\Csv; use App\Import\ImportException; use App\Import\Transformer\BaseTransformer; -use App\Import\Transformer\Csv\ClientTransformer; use App\Models\Invoice; /** @@ -222,7 +221,7 @@ class InvoiceTransformer extends BaseTransformer $record, 'item.custom_value4' ), - 'type_id' => $this->getInvoiceTypeId( $record, 'item.type_id' ), + 'type_id' => $this->getInvoiceTypeId($record, 'item.type_id'), ]; } diff --git a/app/Import/Transformer/Csv/QuoteTransformer.php b/app/Import/Transformer/Csv/QuoteTransformer.php index 8c1add9da979..dab125073a1f 100644 --- a/app/Import/Transformer/Csv/QuoteTransformer.php +++ b/app/Import/Transformer/Csv/QuoteTransformer.php @@ -13,7 +13,6 @@ namespace App\Import\Transformer\Csv; use App\Import\ImportException; use App\Import\Transformer\BaseTransformer; -use App\Import\Transformer\Csv\ClientTransformer; use App\Models\Quote; /** @@ -57,10 +56,10 @@ class QuoteTransformer extends BaseTransformer 'discount' => $this->getFloat($quote_data, 'quote.discount'), 'po_number' => $this->getString($quote_data, 'quote.po_number'), 'date' => isset($quote_data['quote.date']) - ? date('Y-m-d', strtotime(str_replace("/","-",$quote_data['quote.date']))) + ? date('Y-m-d', strtotime(str_replace("/", "-", $quote_data['quote.date']))) : now()->format('Y-m-d'), 'due_date' => isset($quote_data['quote.due_date']) - ? date('Y-m-d', strtotime(str_replace("/","-",$quote_data['quote.due_date']))) + ? date('Y-m-d', strtotime(str_replace("/", "-", $quote_data['quote.due_date']))) : null, 'terms' => $this->getString($quote_data, 'quote.terms'), 'public_notes' => $this->getString( diff --git a/app/Import/Transformer/Freshbooks/InvoiceTransformer.php b/app/Import/Transformer/Freshbooks/InvoiceTransformer.php index 316779875761..e072206e9c2f 100644 --- a/app/Import/Transformer/Freshbooks/InvoiceTransformer.php +++ b/app/Import/Transformer/Freshbooks/InvoiceTransformer.php @@ -14,7 +14,6 @@ namespace App\Import\Transformer\Freshbooks; use App\Import\ImportException; use App\Import\Transformer\BaseTransformer; use App\Models\Invoice; -use App\Utils\Number; /** * Class InvoiceTransformer. @@ -82,8 +81,9 @@ class InvoiceTransformer extends BaseTransformer //Line Subtotal public function calcTaxRate($record, $field) { - if(isset($record['Line Subtotal']) && $record['Line Subtotal'] > 0) + if (isset($record['Line Subtotal']) && $record['Line Subtotal'] > 0) { return ($record[$field] / $record['Line Subtotal']) * 100; + } $tax_amount1 = isset($record['Tax 1 Amount']) ? $record['Tax 1 Amount'] : 0; @@ -93,11 +93,11 @@ class InvoiceTransformer extends BaseTransformer $subtotal = $line_total - $tax_amount2 - $tax_amount1; - if($subtotal > 0) + if ($subtotal > 0) { return $record[$field] / $subtotal * 100; + } return 0; - } /** @return float */ diff --git a/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php b/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php index f5b18674cd95..b7b35926a44e 100644 --- a/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php +++ b/app/Import/Transformer/Invoice2Go/InvoiceTransformer.php @@ -28,7 +28,6 @@ class InvoiceTransformer extends BaseTransformer */ public function transform($invoice_data) { - if (!isset($invoice_data['DocumentNumber'])) { throw new ImportException('DocumentNumber key not found in this import file.'); } diff --git a/app/Import/Transformer/Wave/ExpenseTransformer.php b/app/Import/Transformer/Wave/ExpenseTransformer.php index db7a3e2671fc..497d214bc6d6 100644 --- a/app/Import/Transformer/Wave/ExpenseTransformer.php +++ b/app/Import/Transformer/Wave/ExpenseTransformer.php @@ -11,7 +11,6 @@ namespace App\Import\Transformer\Wave; -use App\Import\ImportException; use App\Import\Transformer\BaseTransformer; /** diff --git a/app/Import/Transformer/Zoho/InvoiceTransformer.php b/app/Import/Transformer/Zoho/InvoiceTransformer.php index 90f7f28c7bd5..56f26bd3c75a 100644 --- a/app/Import/Transformer/Zoho/InvoiceTransformer.php +++ b/app/Import/Transformer/Zoho/InvoiceTransformer.php @@ -58,7 +58,6 @@ class InvoiceTransformer extends BaseTransformer $line_items = []; foreach ($line_items_data as $record) { - $item_notes_key = array_key_exists('Item Description', $record) ? 'Item Description' : 'Item Desc'; $line_items[] = [ diff --git a/app/Jobs/Account/CreateAccount.php b/app/Jobs/Account/CreateAccount.php index c416b1eb798e..756c744e3765 100644 --- a/app/Jobs/Account/CreateAccount.php +++ b/app/Jobs/Account/CreateAccount.php @@ -18,25 +18,16 @@ use App\Jobs\Company\CreateCompany; use App\Jobs\Company\CreateCompanyPaymentTerms; use App\Jobs\Company\CreateCompanyTaskStatuses; use App\Jobs\Company\CreateCompanyToken; -use App\Jobs\Mail\NinjaMailer; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\User\CreateUser; use App\Jobs\Util\VersionCheck; -use App\Mail\Admin\AccountCreatedObject; -use App\Mail\Admin\VerifyUserObject; use App\Models\Account; -use App\Models\Timezone; -use App\Notifications\Ninja\NewAccountCreated; use App\Utils\Ninja; use App\Utils\Traits\User\LoginCache; use Illuminate\Foundation\Bus\Dispatchable; -use Illuminate\Http\Request; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; -use Symfony\Component\HttpFoundation\Response; use Turbo124\Beacon\Facades\LightLogs; class CreateAccount @@ -86,7 +77,7 @@ class CreateAccount $sp794f3f->hosted_company_count = config('ninja.quotas.free.max_companies'); $sp794f3f->account_sms_verified = true; - if(in_array($this->getDomain($this->request['email']), ['givmail.com','yopmail.com','gmail.com', 'hotmail.com', 'outlook.com', 'yahoo.com', 'aol.com', 'mail.ru','brand-app.biz','proton.me','ema-sofia.eu'])){ + if (in_array($this->getDomain($this->request['email']), ['givmail.com','yopmail.com','gmail.com', 'hotmail.com', 'outlook.com', 'yahoo.com', 'aol.com', 'mail.ru','brand-app.biz','proton.me','ema-sofia.eu'])) { $sp794f3f->account_sms_verified = false; } @@ -96,7 +87,7 @@ class CreateAccount $sp794f3f->save(); - $sp035a66 = (new CreateCompany($this->request,$sp794f3f))->handle(); + $sp035a66 = (new CreateCompany($this->request, $sp794f3f))->handle(); $sp035a66->load('account'); $sp794f3f->default_company_id = $sp035a66->id; $sp794f3f->save(); @@ -164,7 +155,7 @@ class CreateAccount private function getDomain($email) { - if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) { + if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // split on @ and return last value of array (the domain) $domain = explode('@', $email); @@ -175,5 +166,4 @@ class CreateAccount return 'gmail.com'; } - } diff --git a/app/Jobs/Bank/MatchBankTransactions.php b/app/Jobs/Bank/MatchBankTransactions.php index 708206c15a3f..42a03df4925c 100644 --- a/app/Jobs/Bank/MatchBankTransactions.php +++ b/app/Jobs/Bank/MatchBankTransactions.php @@ -19,15 +19,12 @@ use App\Factory\PaymentFactory; use App\Helpers\Bank\Yodlee\Yodlee; use App\Libraries\Currency\Conversion\CurrencyApi; use App\Libraries\MultiDB; -use App\Models\BankIntegration; use App\Models\BankTransaction; use App\Models\Company; -use App\Models\Currency; use App\Models\Expense; use App\Models\ExpenseCategory; use App\Models\Invoice; use App\Models\Payment; -use App\Services\Bank\BankMatchingService; use App\Utils\Ninja; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; @@ -71,13 +68,11 @@ class MatchBankTransactions implements ShouldQueue */ public function __construct(int $company_id, string $db, array $input) { - $this->company_id = $company_id; $this->db = $db; $this->input = $input['transactions']; $this->categories = collect(); $this->bts = collect(); - } /** @@ -88,43 +83,41 @@ class MatchBankTransactions implements ShouldQueue */ public function handle() { - MultiDB::setDb($this->db); $this->company = Company::find($this->company_id); - if($this->company->account->bank_integration_account_id) + if ($this->company->account->bank_integration_account_id) { $yodlee = new Yodlee($this->company->account->bank_integration_account_id); - else + } else { $yodlee = false; + } $bank_categories = Cache::get('bank_categories'); - if(!$bank_categories && $yodlee){ + if (!$bank_categories && $yodlee) { $_categories = $yodlee->getTransactionCategories(); $this->categories = collect($_categories->transactionCategory); Cache::forever('bank_categories', $this->categories); - } - else { + } else { $this->categories = collect($bank_categories); } - foreach($this->input as $input) - { + foreach ($this->input as $input) { nlog($input); - if(array_key_exists('invoice_ids', $input) && strlen($input['invoice_ids']) >= 1) + if (array_key_exists('invoice_ids', $input) && strlen($input['invoice_ids']) >= 1) { $this->matchInvoicePayment($input); - elseif(array_key_exists('payment_id', $input) && strlen($input['payment_id']) >= 1) + } elseif (array_key_exists('payment_id', $input) && strlen($input['payment_id']) >= 1) { $this->linkPayment($input); - elseif(array_key_exists('expense_id', $input) && strlen($input['expense_id']) >= 1) + } elseif (array_key_exists('expense_id', $input) && strlen($input['expense_id']) >= 1) { $this->linkExpense($input); - elseif((array_key_exists('vendor_id', $input) && strlen($input['vendor_id']) >= 1) || (array_key_exists('ninja_category_id', $input) && strlen($input['ninja_category_id']) >= 1)) + } elseif ((array_key_exists('vendor_id', $input) && strlen($input['vendor_id']) >= 1) || (array_key_exists('ninja_category_id', $input) && strlen($input['ninja_category_id']) >= 1)) { $this->matchExpense($input); + } } return BankTransaction::whereIn('id', $this->bts); - } private function getInvoices(string $invoice_hashed_ids) @@ -133,15 +126,12 @@ class MatchBankTransactions implements ShouldQueue $invoices = explode(",", $invoice_hashed_ids); - if(count($invoices) >= 1) - { - - foreach($invoices as $invoice){ - - if(is_string($invoice) && strlen($invoice) > 1) + if (count($invoices) >= 1) { + foreach ($invoices as $invoice) { + if (is_string($invoice) && strlen($invoice) > 1) { $collection->push($this->decodePrimaryKey($invoice)); + } } - } return $collection; @@ -149,32 +139,28 @@ class MatchBankTransactions implements ShouldQueue private function checkPayable($invoices) :bool { - - foreach($invoices as $invoice){ - + foreach ($invoices as $invoice) { $invoice->service()->markSent(); - if(!$invoice->isPayable()) + if (!$invoice->isPayable()) { return false; - + } } return true; - } private function linkExpense($input) { - $this->bt = BankTransaction::find($input['id']); - if(!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) + if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) { return $this; + } $expense = Expense::withTrashed()->find($input['expense_id']); - if($expense && !$expense->transaction_id) { - + if ($expense && !$expense->transaction_id) { $expense->transaction_id = $this->bt->id; $expense->save(); @@ -185,25 +171,22 @@ class MatchBankTransactions implements ShouldQueue $this->bt->save(); $this->bts->push($this->bt->id); - } return $this; - } private function linkPayment($input) { - $this->bt = BankTransaction::find($input['id']); - if(!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) + if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) { return $this; + } $payment = Payment::withTrashed()->find($input['payment_id']); - if($payment && !$payment->transaction_id) { - + if ($payment && !$payment->transaction_id) { $payment->transaction_id = $this->bt->id; $payment->save(); @@ -219,34 +202,34 @@ class MatchBankTransactions implements ShouldQueue } private function matchInvoicePayment($input) :self - { + { $this->bt = BankTransaction::find($input['id']); - if(!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) - return $this; + if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) { + return $this; + } $_invoices = Invoice::withTrashed()->find($this->getInvoices($input['invoice_ids'])); $amount = $this->bt->amount; - if($_invoices && $this->checkPayable($_invoices)){ - + if ($_invoices && $this->checkPayable($_invoices)) { $this->createPayment($_invoices, $amount); $this->bts->push($this->bt->id); - } return $this; } 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']); - if(!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) - return $this; + if (!$this->bt || $this->bt->status_id == BankTransaction::STATUS_CONVERTED) { + return $this; + } $expense = ExpenseFactory::create($this->bt->company_id, $this->bt->user_id); $expense->category_id = $this->resolveCategory($input); @@ -258,8 +241,9 @@ class MatchBankTransactions implements ShouldQueue $expense->transaction_reference = $this->bt->description; $expense->transaction_id = $this->bt->id; - if(array_key_exists('vendor_id', $input)) + if (array_key_exists('vendor_id', $input)) { $expense->vendor_id = $input['vendor_id']; + } $expense->invoice_documents = $this->company->invoice_expense_documents; $expense->should_be_invoiced = $this->company->mark_expenses_invoiceable; @@ -267,8 +251,9 @@ class MatchBankTransactions implements ShouldQueue $this->bt->expense_id = $expense->id; - if(array_key_exists('vendor_id', $input)) + if (array_key_exists('vendor_id', $input)) { $this->bt->vendor_id = $input['vendor_id']; + } $this->bt->status_id = BankTransaction::STATUS_CONVERTED; $this->bt->save(); @@ -282,47 +267,39 @@ class MatchBankTransactions implements ShouldQueue { $this->available_balance = $amount; - \DB::connection(config('database.default'))->transaction(function () use($invoices) { - - $invoices->each(function ($invoice) use ($invoices){ - + \DB::connection(config('database.default'))->transaction(function () use ($invoices) { + $invoices->each(function ($invoice) use ($invoices) { $this->invoice = Invoice::withTrashed()->where('id', $invoice->id)->lockForUpdate()->first(); - $_amount = false; + $_amount = false; - if(floatval($this->invoice->balance) < floatval($this->available_balance) && $this->available_balance > 0) - { - $_amount = $this->invoice->balance; - $this->applied_amount += $this->invoice->balance; - $this->available_balance = $this->available_balance - $this->invoice->balance; - } - elseif(floatval($this->invoice->balance) >= floatval($this->available_balance) && $this->available_balance > 0) - { - $_amount = $this->available_balance; - $this->applied_amount += $this->available_balance; - $this->available_balance = 0; - } + if (floatval($this->invoice->balance) < floatval($this->available_balance) && $this->available_balance > 0) { + $_amount = $this->invoice->balance; + $this->applied_amount += $this->invoice->balance; + $this->available_balance = $this->available_balance - $this->invoice->balance; + } elseif (floatval($this->invoice->balance) >= floatval($this->available_balance) && $this->available_balance > 0) { + $_amount = $this->available_balance; + $this->applied_amount += $this->available_balance; + $this->available_balance = 0; + } - if($_amount) - { - - $this->attachable_invoices[] = ['id' => $this->invoice->id, 'amount' => $_amount]; - - $this->invoice - ->service() - ->setExchangeRate() - ->updateBalance($_amount * -1) - ->updatePaidToDate($_amount) - ->setCalculatedStatus() - ->save(); - } - - }); + if ($_amount) { + $this->attachable_invoices[] = ['id' => $this->invoice->id, 'amount' => $_amount]; + $this->invoice + ->service() + ->setExchangeRate() + ->updateBalance($_amount * -1) + ->updatePaidToDate($_amount) + ->setCalculatedStatus() + ->save(); + } + }); }, 2); - if(!$this->invoice) + if (!$this->invoice) { return; + } /* Create Payment */ $payment = PaymentFactory::create($this->invoice->company_id, $this->invoice->user_id); @@ -345,19 +322,17 @@ class MatchBankTransactions implements ShouldQueue $payment->service()->applyNumber()->save(); - if($payment->client->getSetting('send_email_on_mark_paid')) + if ($payment->client->getSetting('send_email_on_mark_paid')) { $payment->service()->sendEmail(); + } $this->setExchangeRate($payment); /* Create a payment relationship to the invoice entity */ - foreach($this->attachable_invoices as $attachable_invoice) - { - + foreach ($this->attachable_invoices as $attachable_invoice) { $payment->invoices()->attach($attachable_invoice['id'], [ 'amount' => $attachable_invoice['amount'], ]); - } event('eloquent.created: App\Models\Payment', $payment); @@ -396,7 +371,7 @@ class MatchBankTransactions implements ShouldQueue private function resolveCategory($input) :?int { - if(array_key_exists('ninja_category_id', $input) && (int)$input['ninja_category_id'] > 1){ + if (array_key_exists('ninja_category_id', $input) && (int)$input['ninja_category_id'] > 1) { $this->bt->ninja_category_id = $input['ninja_category_id']; $this->bt->save(); @@ -407,11 +382,11 @@ class MatchBankTransactions implements ShouldQueue $ec = ExpenseCategory::where('company_id', $this->bt->company_id)->where('bank_category_id', $this->bt->category_id)->first(); - if($ec) + if ($ec) { return $ec->id; + } - if($category) - { + if ($category) { $ec = ExpenseCategoryFactory::create($this->bt->company_id, $this->bt->user_id); $ec->bank_category_id = $this->bt->category_id; $ec->name = $category->highLevelCategoryName; @@ -447,9 +422,4 @@ class MatchBankTransactions implements ShouldQueue { return [new WithoutOverlapping($this->company_id)]; } - - - - - -} \ No newline at end of file +} diff --git a/app/Jobs/Bank/ProcessBankTransactions.php b/app/Jobs/Bank/ProcessBankTransactions.php index 74d996f0fd14..bb49547f4b3c 100644 --- a/app/Jobs/Bank/ProcessBankTransactions.php +++ b/app/Jobs/Bank/ProcessBankTransactions.php @@ -22,7 +22,6 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Carbon; class ProcessBankTransactions implements ShouldQueue { @@ -49,7 +48,6 @@ class ProcessBankTransactions implements ShouldQueue $this->bank_integration = $bank_integration; $this->from_date = $bank_integration->from_date; $this->company = $this->bank_integration->company; - } /** @@ -60,41 +58,33 @@ class ProcessBankTransactions implements ShouldQueue */ public function handle() { - set_time_limit(0); //Loop through everything until we are up to date $this->from_date = $this->from_date ?: '2021-01-01'; - do{ - + do { try { $this->processTransactions(); - } - catch(\Exception $e) { + } catch(\Exception $e) { nlog("{$this->bank_integration_account_id} - exited abnormally => ". $e->getMessage()); return; } - - } - while($this->stop_loop); + } while ($this->stop_loop); BankMatchingService::dispatch($this->company->id, $this->company->db); - } private function processTransactions() { - $yodlee = new Yodlee($this->bank_integration_account_id); - if(!$yodlee->getAccount($this->bank_integration->bank_account_id)) - { - $this->bank_integration->disabled_upstream = true; - $this->bank_integration->save(); - $this->stop_loop = false; - return; + if (!$yodlee->getAccount($this->bank_integration->bank_account_id)) { + $this->bank_integration->disabled_upstream = true; + $this->bank_integration->save(); + $this->stop_loop = false; + return; } $data = [ @@ -111,11 +101,10 @@ class ProcessBankTransactions implements ShouldQueue $count = $transaction_count->transaction->TOTAL->count; //get transactions array - $transactions = $yodlee->getTransactions($data); + $transactions = $yodlee->getTransactions($data); //if no transactions, update the from_date and move on - if(count($transactions) == 0){ - + if (count($transactions) == 0) { $this->bank_integration->from_date = now()->subDays(2); $this->bank_integration->disabled_upstream = false; $this->bank_integration->save(); @@ -135,15 +124,14 @@ 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()) + foreach ($transactions as $transaction) { + if (BankTransaction::where('transaction_id', $transaction['transaction_id'])->where('company_id', $this->company->id)->withTrashed()->exists()) { continue; + } //this should be much faster to insert than using ::create() $bt = \DB::table('bank_transactions')->insert( - array_merge($transaction,[ + array_merge($transaction, [ 'company_id' => $this->company->id, 'user_id' => $user_id, 'bank_integration_id' => $this->bank_integration->id, @@ -151,19 +139,15 @@ class ProcessBankTransactions implements ShouldQueue 'updated_at' => $now, ]) ); - } $this->skip = $this->skip + 500; - if($count < 500){ + if ($count < 500) { $this->stop_loop = false; $this->bank_integration->from_date = now()->subDays(2); $this->bank_integration->save(); - } - } - -} \ No newline at end of file +} diff --git a/app/Jobs/Company/CompanyExport.php b/app/Jobs/Company/CompanyExport.php index 871b396b4b16..574a6b3257de 100644 --- a/app/Jobs/Company/CompanyExport.php +++ b/app/Jobs/Company/CompanyExport.php @@ -13,16 +13,13 @@ namespace App\Jobs\Company; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; -use App\Jobs\Util\UnlinkFile; use App\Libraries\MultiDB; use App\Mail\DownloadBackup; -use App\Mail\DownloadInvoices; use App\Models\Company; use App\Models\CreditInvitation; use App\Models\InvoiceInvitation; use App\Models\PurchaseOrderInvitation; use App\Models\QuoteInvitation; -use App\Models\RecurringInvoice; use App\Models\RecurringInvoiceInvitation; use App\Models\User; use App\Models\VendorContact; @@ -36,8 +33,6 @@ use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Storage; -use function Amp\call; - class CompanyExport implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, MakesHash; @@ -71,7 +66,6 @@ class CompanyExport implements ShouldQueue */ public function handle() { - MultiDB::setDb($this->company->db); $this->company = Company::where('company_key', $this->company->company_key)->first(); @@ -81,8 +75,7 @@ class CompanyExport implements ShouldQueue $this->export_data['app_version'] = config('ninja.app_version'); $this->export_data['storage_url'] = Storage::url(''); - $this->export_data['activities'] = $this->company->all_activities->map(function ($activity){ - + $this->export_data['activities'] = $this->company->all_activities->map(function ($activity) { $activity = $this->transformArrayOfKeys($activity, [ 'user_id', 'company_id', @@ -104,7 +97,6 @@ class CompanyExport implements ShouldQueue ]); return $activity; - })->makeHidden(['id'])->all(); // $this->export_data['backups'] = $this->company->all_activities()->with('backup')->cursor()->map(function ($activity){ @@ -120,149 +112,120 @@ class CompanyExport implements ShouldQueue // })->all(); - $this->export_data['users'] = $this->company->users()->withTrashed()->cursor()->map(function ($user){ - + $this->export_data['users'] = $this->company->users()->withTrashed()->cursor()->map(function ($user) { $user->account_id = $this->encodePrimaryKey($user->account_id); // $user->id = $this->encodePrimaryKey($user->id); return $user->makeVisible(['id']); - })->all(); - $this->export_data['client_contacts'] = $this->company->client_contacts->map(function ($client_contact){ - + $this->export_data['client_contacts'] = $this->company->client_contacts->map(function ($client_contact) { $client_contact = $this->transformArrayOfKeys($client_contact, ['company_id', 'user_id', 'client_id']); - return $client_contact->makeVisible([ - 'password', - 'remember_token', - 'user_id', - 'company_id', - 'client_id', - 'google_2fa_secret', - 'id', - 'oauth_provider_id', - 'oauth_user_id', - 'token', - 'hashed_id', - ]); - + return $client_contact->makeVisible([ + 'password', + 'remember_token', + 'user_id', + 'company_id', + 'client_id', + 'google_2fa_secret', + 'id', + 'oauth_provider_id', + 'oauth_user_id', + 'token', + 'hashed_id', + ]); })->all(); - $this->export_data['client_gateway_tokens'] = $this->company->client_gateway_tokens->map(function ($client_gateway_token){ - + $this->export_data['client_gateway_tokens'] = $this->company->client_gateway_tokens->map(function ($client_gateway_token) { $client_gateway_token = $this->transformArrayOfKeys($client_gateway_token, ['company_id', 'client_id', 'company_gateway_id']); return $client_gateway_token->makeVisible(['id']); - })->all(); - $this->export_data['clients'] = $this->company->clients()->orderBy('number', 'DESC')->cursor()->map(function ($client){ - + $this->export_data['clients'] = $this->company->clients()->orderBy('number', 'DESC')->cursor()->map(function ($client) { $client = $this->transformArrayOfKeys($client, ['company_id', 'user_id', 'assigned_user_id', 'group_settings_id']); return $client->makeVisible(['id','private_notes','user_id','company_id','last_login','hashed_id']); - })->all(); $this->export_data['company'] = $this->company->toArray(); $this->export_data['company']['company_key'] = $this->createHash(); - $this->export_data['company_gateways'] = $this->company->company_gateways()->withTrashed()->cursor()->map(function ($company_gateway){ - + $this->export_data['company_gateways'] = $this->company->company_gateways()->withTrashed()->cursor()->map(function ($company_gateway) { $company_gateway = $this->transformArrayOfKeys($company_gateway, ['company_id', 'user_id']); $company_gateway->config = decrypt($company_gateway->config); return $company_gateway->makeVisible(['id']); - })->all(); - $this->export_data['company_tokens'] = $this->company->tokens->map(function ($token){ - + $this->export_data['company_tokens'] = $this->company->tokens->map(function ($token) { $token = $this->transformArrayOfKeys($token, ['company_id', 'account_id', 'user_id']); return $token; - })->all(); - $this->export_data['company_ledger'] = $this->company->ledger->map(function ($ledger){ - + $this->export_data['company_ledger'] = $this->company->ledger->map(function ($ledger) { $ledger = $this->transformArrayOfKeys($ledger, ['activity_id', 'client_id', 'company_id', 'account_id', 'user_id','company_ledgerable_id']); return $ledger; - })->all(); - $this->export_data['company_users'] = $this->company->company_users()->without(['user','account'])->cursor()->map(function ($company_user){ - + $this->export_data['company_users'] = $this->company->company_users()->without(['user','account'])->cursor()->map(function ($company_user) { $company_user = $this->transformArrayOfKeys($company_user, ['company_id', 'account_id', 'user_id']); return $company_user; - })->all(); - $this->export_data['credits'] = $this->company->credits()->orderBy('number', 'DESC')->cursor()->map(function ($credit){ - + $this->export_data['credits'] = $this->company->credits()->orderBy('number', 'DESC')->cursor()->map(function ($credit) { $credit = $this->transformBasicEntities($credit); $credit = $this->transformArrayOfKeys($credit, ['recurring_id','client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id','invoice_id']); return $credit->makeVisible(['id']); - })->all(); - $this->export_data['credit_invitations'] = CreditInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($credit){ - + $this->export_data['credit_invitations'] = CreditInvitation::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']); - })->all(); $this->export_data['designs'] = $this->company->user_designs->makeHidden(['id'])->all(); - $this->export_data['documents'] = $this->company->all_documents->map(function ($document){ - + $this->export_data['documents'] = $this->company->all_documents->map(function ($document) { $document = $this->transformArrayOfKeys($document, ['user_id', 'assigned_user_id', 'company_id', 'project_id', 'vendor_id','documentable_id']); $document->hashed_id = $this->encodePrimaryKey($document->id); return $document->makeVisible(['id']); - })->all(); - $this->export_data['expense_categories'] = $this->company->expense_categories->map(function ($expense_category){ - + $this->export_data['expense_categories'] = $this->company->expense_categories->map(function ($expense_category) { $expense_category = $this->transformArrayOfKeys($expense_category, ['user_id', 'company_id']); return $expense_category->makeVisible(['id']); - })->all(); - $this->export_data['expenses'] = $this->company->expenses()->orderBy('number', 'DESC')->cursor()->map(function ($expense){ - + $this->export_data['expenses'] = $this->company->expenses()->orderBy('number', 'DESC')->cursor()->map(function ($expense) { $expense = $this->transformBasicEntities($expense); $expense = $this->transformArrayOfKeys($expense, ['vendor_id', 'invoice_id', 'client_id', 'category_id', 'recurring_expense_id','project_id']); return $expense->makeVisible(['id']); - })->all(); - $this->export_data['group_settings'] = $this->company->group_settings->map(function ($gs){ - + $this->export_data['group_settings'] = $this->company->group_settings->map(function ($gs) { $gs = $this->transformArrayOfKeys($gs, ['user_id', 'company_id']); return $gs->makeVisible(['id']); - })->all(); - $this->export_data['invoices'] = $this->company->invoices()->orderBy('number', 'DESC')->cursor()->map(function ($invoice){ - + $this->export_data['invoices'] = $this->company->invoices()->orderBy('number', 'DESC')->cursor()->map(function ($invoice) { $invoice = $this->transformBasicEntities($invoice); $invoice = $this->transformArrayOfKeys($invoice, ['recurring_id','client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id','project_id']); @@ -271,103 +234,81 @@ class CompanyExport implements ShouldQueue 'user_id', 'client_id', 'company_id',]); - })->all(); - $this->export_data['invoice_invitations'] = InvoiceInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($invoice){ - + $this->export_data['invoice_invitations'] = InvoiceInvitation::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']); - })->all(); - $this->export_data['payment_terms'] = $this->company->user_payment_terms->map(function ($term){ - + $this->export_data['payment_terms'] = $this->company->user_payment_terms->map(function ($term) { $term = $this->transformArrayOfKeys($term, ['user_id', 'company_id']); return $term; - })->makeHidden(['id'])->all(); - $this->export_data['payments'] = $this->company->payments()->orderBy('number', 'DESC')->cursor()->map(function ($payment){ - + $this->export_data['payments'] = $this->company->payments()->orderBy('number', 'DESC')->cursor()->map(function ($payment) { $payment = $this->transformBasicEntities($payment); $payment = $this->transformArrayOfKeys($payment, ['client_id','project_id', 'vendor_id', 'client_contact_id', 'invitation_id', 'company_gateway_id', 'transaction_id']); $payment->paymentables = $this->transformPaymentable($payment); return $payment->makeVisible(['id']); - })->all(); - $this->export_data['products'] = $this->company->products->map(function ($product){ - + $this->export_data['products'] = $this->company->products->map(function ($product) { $product = $this->transformBasicEntities($product); $product = $this->transformArrayOfKeys($product, ['vendor_id','project_id']); return $product->makeVisible(['id']); - })->all(); - $this->export_data['projects'] = $this->company->projects()->orderBy('number', 'DESC')->cursor()->map(function ($project){ - + $this->export_data['projects'] = $this->company->projects()->orderBy('number', 'DESC')->cursor()->map(function ($project) { $project = $this->transformBasicEntities($project); $project = $this->transformArrayOfKeys($project, ['client_id']); return $project->makeVisible(['id']); - })->all(); - $this->export_data['quotes'] = $this->company->quotes()->orderBy('number', 'DESC')->cursor()->map(function ($quote){ - + $this->export_data['quotes'] = $this->company->quotes()->orderBy('number', 'DESC')->cursor()->map(function ($quote) { $quote = $this->transformBasicEntities($quote); $quote = $this->transformArrayOfKeys($quote, ['invoice_id','recurring_id','client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id']); return $quote->makeVisible(['id']); - })->all(); - $this->export_data['quote_invitations'] = QuoteInvitation::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($quote){ - + $this->export_data['quote_invitations'] = QuoteInvitation::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']); - })->all(); - $this->export_data['recurring_expenses'] = $this->company->recurring_expenses()->orderBy('number', 'DESC')->cursor()->map(function ($expense){ - + $this->export_data['recurring_expenses'] = $this->company->recurring_expenses()->orderBy('number', 'DESC')->cursor()->map(function ($expense) { $expense = $this->transformBasicEntities($expense); $expense = $this->transformArrayOfKeys($expense, ['vendor_id', 'invoice_id', 'client_id', 'category_id', 'project_id']); return $expense->makeVisible(['id']); - })->all(); - $this->export_data['recurring_invoices'] = $this->company->recurring_invoices()->orderBy('number', 'DESC')->cursor()->map(function ($ri){ - + $this->export_data['recurring_invoices'] = $this->company->recurring_invoices()->orderBy('number', 'DESC')->cursor()->map(function ($ri) { $ri = $this->transformBasicEntities($ri); $ri = $this->transformArrayOfKeys($ri, ['client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id']); return $ri->makeVisible(['id']); - })->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::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; - })->all(); - $this->export_data['subscriptions'] = $this->company->subscriptions->map(function ($subscription){ - + $this->export_data['subscriptions'] = $this->company->subscriptions->map(function ($subscription) { $subscription = $this->transformBasicEntities($subscription); $subscription->group_id = $this->encodePrimaryKey($subscription->group_id); @@ -378,74 +319,58 @@ class CompanyExport implements ShouldQueue 'product_ids', 'recurring_product_ids', 'group_id']); - })->all(); - $this->export_data['system_logs'] = $this->company->system_logs->map(function ($log){ - + $this->export_data['system_logs'] = $this->company->system_logs->map(function ($log) { $log->client_id = $this->encodePrimaryKey($log->client_id); $log->company_id = $this->encodePrimaryKey($log->company_id); return $log; - })->makeHidden(['id'])->all(); - $this->export_data['tasks'] = $this->company->tasks()->orderBy('number', 'DESC')->cursor()->map(function ($task){ - + $this->export_data['tasks'] = $this->company->tasks()->orderBy('number', 'DESC')->cursor()->map(function ($task) { $task = $this->transformBasicEntities($task); $task = $this->transformArrayOfKeys($task, ['client_id', 'invoice_id', 'project_id', 'status_id']); return $task->makeVisible(['id']); - })->all(); - $this->export_data['task_statuses'] = $this->company->task_statuses->map(function ($status){ - + $this->export_data['task_statuses'] = $this->company->task_statuses->map(function ($status) { $status->id = $this->encodePrimaryKey($status->id); $status->user_id = $this->encodePrimaryKey($status->user_id); $status->company_id = $this->encodePrimaryKey($status->company_id); return $status; - })->all(); - $this->export_data['tax_rates'] = $this->company->tax_rates->map(function ($rate){ - + $this->export_data['tax_rates'] = $this->company->tax_rates->map(function ($rate) { $rate->company_id = $this->encodePrimaryKey($rate->company_id); $rate->user_id = $this->encodePrimaryKey($rate->user_id); return $rate; - })->makeHidden(['id'])->all(); - $this->export_data['vendors'] = $this->company->vendors()->orderBy('number', 'DESC')->cursor()->map(function ($vendor){ - + $this->export_data['vendors'] = $this->company->vendors()->orderBy('number', 'DESC')->cursor()->map(function ($vendor) { return $this->transformBasicEntities($vendor)->makeVisible(['id']); - })->all(); - $this->export_data['vendor_contacts'] = VendorContact::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($vendor){ - + $this->export_data['vendor_contacts'] = VendorContact::where('company_id', $this->company->id)->withTrashed()->cursor()->map(function ($vendor) { $vendor = $this->transformBasicEntities($vendor); $vendor = $this->transformArrayOfKeys($vendor, ['vendor_id']); return $vendor->makeVisible(['id','user_id']); - })->all(); - $this->export_data['webhooks'] = $this->company->webhooks->map(function ($hook){ - + $this->export_data['webhooks'] = $this->company->webhooks->map(function ($hook) { $hook->user_id = $this->encodePrimaryKey($hook->user_id); $hook->company_id = $this->encodePrimaryKey($hook->company_id); return $hook; - })->makeHidden(['id'])->all(); - $this->export_data['purchase_orders'] = $this->company->purchase_orders()->orderBy('number', 'DESC')->cursor()->map(function ($purchase_order){ - + $this->export_data['purchase_orders'] = $this->company->purchase_orders()->orderBy('number', 'DESC')->cursor()->map(function ($purchase_order) { $purchase_order = $this->transformBasicEntities($purchase_order); $purchase_order = $this->transformArrayOfKeys($purchase_order, ['expense_id','client_id', 'vendor_id', 'project_id', 'design_id', 'subscription_id','project_id']); @@ -455,67 +380,53 @@ class CompanyExport implements ShouldQueue 'client_id', 'vendor_id', '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::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']); - })->all(); - $this->export_data['bank_integrations'] = $this->company->bank_integrations()->orderBy('id', 'ASC')->cursor()->map(function ($bank_integration){ - + $this->export_data['bank_integrations'] = $this->company->bank_integrations()->orderBy('id', 'ASC')->cursor()->map(function ($bank_integration) { $bank_integration = $this->transformArrayOfKeys($bank_integration, ['account_id','company_id', 'user_id']); return $bank_integration->makeVisible(['id','user_id','company_id','account_id']); - })->all(); - $this->export_data['bank_transactions'] = $this->company->bank_transactions()->orderBy('id', 'ASC')->cursor()->map(function ($bank_transaction){ - + $this->export_data['bank_transactions'] = $this->company->bank_transactions()->orderBy('id', 'ASC')->cursor()->map(function ($bank_transaction) { $bank_transaction = $this->transformArrayOfKeys($bank_transaction, ['company_id', 'user_id','bank_integration_id','expense_id','category_id','ninja_category_id','vendor_id']); return $bank_transaction->makeVisible(['id','user_id','company_id']); - })->all(); //write to tmp and email to owner(); - $this->zipAndSend(); + $this->zipAndSend(); - return true; + return true; } private function transformBasicEntities($model) { - return $this->transformArrayOfKeys($model, ['user_id', 'assigned_user_id', 'company_id']); - } private function transformArrayOfKeys($model, $keys) { - - foreach($keys as $key){ + foreach ($keys as $key) { $model->{$key} = $this->encodePrimaryKey($model->{$key}); } return $model; - } private function transformPaymentable($payment) { - $new_arr = []; - foreach($payment->paymentables as $paymentable) - { - + foreach ($payment->paymentables as $paymentable) { $paymentable->payment_id = $this->encodePrimaryKey($paymentable->payment_id); $paymentable->paymentable_id = $this->encodePrimaryKey($paymentable->paymentable_id); @@ -523,13 +434,11 @@ class CompanyExport implements ShouldQueue } return $new_arr; - } private function zipAndSend() { - - $file_name = date('Y-m-d').'_'.str_replace([" ", "/"],["_",""], $this->company->present()->name() . '_' . $this->company->company_key .'.zip'); + $file_name = date('Y-m-d').'_'.str_replace([" ", "/"], ["_",""], $this->company->present()->name() . '_' . $this->company->company_key .'.zip'); $path = 'backups'; @@ -537,22 +446,21 @@ class CompanyExport implements ShouldQueue try { mkdir(public_path('storage/backups/')); - } - catch(\Exception $e) { + } catch(\Exception $e) { nlog("could not create directory"); } $zip_path = public_path('storage/backups/'.$file_name); $zip = new \ZipArchive(); - if ($zip->open($zip_path, \ZipArchive::CREATE)!==TRUE) { + if ($zip->open($zip_path, \ZipArchive::CREATE)!==true) { nlog("cannot open {$zip_path}"); } $zip->addFromString("backup.json", json_encode($this->export_data)); $zip->close(); - if(Ninja::isHosted()) { + if (Ninja::isHosted()) { Storage::disk(config('filesystems.default'))->put('backups/'.$file_name, file_get_contents($zip_path)); } @@ -562,7 +470,8 @@ class CompanyExport implements ShouldQueue $t = app('translator'); $t->replace(Ninja::transformTranslations($this->company->settings)); - $company_reference = Company::find($this->company->id);; + $company_reference = Company::find($this->company->id); + ; $nmo = new NinjaMailerObject; $nmo->mailable = new DownloadBackup($storage_file_path, $company_reference); @@ -572,10 +481,9 @@ class CompanyExport implements ShouldQueue NinjaMailerJob::dispatch($nmo, true); - if(Ninja::isHosted()){ + if (Ninja::isHosted()) { sleep(3); unlink($zip_path); } } - } diff --git a/app/Jobs/Company/CompanyImport.php b/app/Jobs/Company/CompanyImport.php index 698399527c1f..3c5ca9d8707d 100644 --- a/app/Jobs/Company/CompanyImport.php +++ b/app/Jobs/Company/CompanyImport.php @@ -16,10 +16,7 @@ use App\Exceptions\NonExistingMigrationFile; use App\Factory\ClientContactFactory; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; -use App\Jobs\Util\UnlinkFile; use App\Libraries\MultiDB; -use App\Mail\DownloadBackup; -use App\Mail\DownloadInvoices; use App\Mail\Import\CompanyImportFailure; use App\Mail\Import\ImportCompleted; use App\Models\Activity; @@ -43,8 +40,8 @@ use App\Models\GroupSetting; use App\Models\Invoice; use App\Models\InvoiceInvitation; use App\Models\Payment; -use App\Models\PaymentTerm; use App\Models\Paymentable; +use App\Models\PaymentTerm; use App\Models\Product; use App\Models\Project; use App\Models\PurchaseOrder; @@ -66,6 +63,7 @@ use App\Utils\Ninja; use App\Utils\TempFile; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; +use function GuzzleHttp\json_encode; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; @@ -78,7 +76,6 @@ use Illuminate\Support\Str; use JsonMachine\JsonDecoder\ExtJsonDecoder; use JsonMachine\JsonMachine; use ZipArchive; -use function GuzzleHttp\json_encode; class CompanyImport implements ShouldQueue { @@ -236,17 +233,18 @@ class CompanyImport implements ShouldQueue $json = JsonMachine::fromFile($this->file_path, '/'.$key, new ExtJsonDecoder); - if($force_array) + if ($force_array) { return iterator_to_array($json); + } return $json; } public function handle() { - MultiDB::setDb($this->company->db); + MultiDB::setDb($this->company->db); - $this->company = Company::where('company_key', $this->company->company_key)->firstOrFail(); + $this->company = Company::where('company_key', $this->company->company_key)->firstOrFail(); $this->account = $this->company->account; $this->company_owner = $this->company->owner(); @@ -255,8 +253,9 @@ class CompanyImport implements ShouldQueue // $this->backup_file = Cache::get($this->hash); - if ( empty( $this->file_location ) ) + if (empty($this->file_location)) { throw new \Exception('No import data found, has the cache expired?'); + } // $this->backup_file = json_decode(file_get_contents($this->file_location)); $tmp_file = $this->unzipFile(); @@ -265,15 +264,12 @@ class CompanyImport implements ShouldQueue $this->checkUserCount(); - if(array_key_exists('import_settings', $this->request_array) && $this->request_array['import_settings'] == 'true') { - + if (array_key_exists('import_settings', $this->request_array) && $this->request_array['import_settings'] == 'true') { $this->preFlightChecks()->importSettings(); } - if(array_key_exists('import_data', $this->request_array) && $this->request_array['import_data'] == 'true') { - - try{ - + if (array_key_exists('import_data', $this->request_array) && $this->request_array['import_data'] == 'true') { + try { $this->preFlightChecks() ->purgeCompanyData() ->importCompany() @@ -292,18 +288,12 @@ class CompanyImport implements ShouldQueue $nmo->settings = $_company->settings; $nmo->to_user = $_company->owner(); NinjaMailerJob::dispatch($nmo); - - } - catch(\Exception $e){ - + } catch(\Exception $e) { info($e->getMessage()); - - } - + } } unlink($tmp_file); - } // @@ -315,23 +305,19 @@ class CompanyImport implements ShouldQueue ->clients() ->whereDoesntHave('contacts') ->cursor() - ->each(function ($client){ - - $new_contact = ClientContactFactory::create($client->company_id, $client->user_id); - $new_contact->client_id = $client->id; - $new_contact->contact_key = Str::random(40); - $new_contact->is_primary = true; - $new_contact->confirmed = true; - $new_contact->email = ' '; - $new_contact->save(); - - }); - + ->each(function ($client) { + $new_contact = ClientContactFactory::create($client->company_id, $client->user_id); + $new_contact->client_id = $client->id; + $new_contact->contact_key = Str::random(40); + $new_contact->is_primary = true; + $new_contact->confirmed = true; + $new_contact->email = ' '; + $new_contact->save(); + }); } private function unzipFile() { - $path = TempFile::filePath(Storage::disk(config('filesystems.default'))->get($this->file_location), basename($this->file_location)); $zip = new ZipArchive(); @@ -343,75 +329,68 @@ class CompanyImport implements ShouldQueue $zip->close(); $file_location = "{$file_path}/backup.json"; - if (! file_exists($file_path)) + if (! file_exists($file_path)) { throw new NonExistingMigrationFile('Backup file does not exist, or is corrupted.'); + } return $file_location; - } /** - * On the hosted platform we cannot allow the + * On the hosted platform we cannot allow the * import to start if there are users > plan number * due to entity user_id dependencies - * + * * @return bool */ private function checkUserCount() { - - if(Ninja::isSelfHost()) + if (Ninja::isSelfHost()) { $this->pre_flight_checks_pass = true; + } // $backup_users = $this->backup_file->users; $backup_users = $this->getObject('users', true); $company_users = $this->company->users; - nlog("Backup user count = ".count($backup_users)); + nlog("Backup user count = ".count($backup_users)); - if(count($backup_users) > 1){ + if (count($backup_users) > 1) { + } + nlog("backup users email = " . $backup_users[0]->email); + + if (count($backup_users) == 1 && $this->company_owner->email != $backup_users[0]->email) { + } + + $backup_users_emails = array_column($backup_users, 'email'); + + $company_users_emails = $company_users->pluck('email')->toArray(); + + $existing_user_count = count(array_intersect($backup_users_emails, $company_users_emails)); + + nlog("existing user count = {$existing_user_count}"); + + if ($existing_user_count > 1) { + if ($this->account->plan == 'pro') { } - nlog("backup users email = " . $backup_users[0]->email); - - if(count($backup_users) == 1 && $this->company_owner->email != $backup_users[0]->email) { - + if ($this->account->plan == 'enterprise') { } + } - $backup_users_emails = array_column($backup_users, 'email'); + if ($this->company->account->isFreeHostedClient() && (count($this->getObject('clients', true)) > config('ninja.quotas.free.clients'))) { + nlog("client quota busted"); - $company_users_emails = $company_users->pluck('email')->toArray(); + $client_limit = config('ninja.quotas.free.clients'); + $client_count = count($this->getObject('clients', true)); - $existing_user_count = count(array_intersect($backup_users_emails, $company_users_emails)); - - nlog("existing user count = {$existing_user_count}"); - - if($existing_user_count > 1){ - - if($this->account->plan == 'pro'){ - - } - - if($this->account->plan == 'enterprise'){ - - } - } - - if($this->company->account->isFreeHostedClient() && (count($this->getObject('clients', true)) > config('ninja.quotas.free.clients')) ){ + $this->message = "You are attempting to import ({$client_count}) clients, your current plan allows a total of ({$client_limit})"; - nlog("client quota busted"); - - $client_limit = config('ninja.quotas.free.clients'); - $client_count = count($this->getObject('clients', true)); - - $this->message = "You are attempting to import ({$client_count}) clients, your current plan allows a total of ({$client_limit})"; - - $this->pre_flight_checks_pass = false; - - } + $this->pre_flight_checks_pass = false; + } return $this; } @@ -424,24 +403,21 @@ class CompanyImport implements ShouldQueue private function preFlightChecks() { - //check the file version and perform any necessary adjustments to the file in order to proceed - needed when we change schema + //check the file version and perform any necessary adjustments to the file in order to proceed - needed when we change schema $data = (object)$this->getObject('app_version', true); - if($this->current_app_version != $data->app_version) - { + if ($this->current_app_version != $data->app_version) { //perform some magic here } - if($this->pre_flight_checks_pass === false) - { - + if ($this->pre_flight_checks_pass === false) { $this->sendImportMail($this->message); throw new \Exception($this->message); } - return $this; + return $this; } private function importSettings() @@ -489,125 +465,123 @@ class CompanyImport implements ShouldQueue private function importCompany() { //$tmp_company = $this->backup_file->company; - $tmp_company = (object)$this->getObject("company",true); + $tmp_company = (object)$this->getObject("company", true); $tmp_company->company_key = $this->createHash(); $tmp_company->db = config('database.default'); $tmp_company->account_id = $this->account->id; - if(Ninja::isHosted()) + if (Ninja::isHosted()) { $tmp_company->subdomain = MultiDB::randomSubdomainGenerator(); - else + } else { $tmp_company->subdomain = ''; + } - foreach($this->company_properties as $value){ - - if(property_exists($tmp_company, $value)) - $this->company->{$value} = $tmp_company->{$value}; - + foreach ($this->company_properties as $value) { + if (property_exists($tmp_company, $value)) { + $this->company->{$value} = $tmp_company->{$value}; + } } - if(Ninja::isHosted()) - { + if (Ninja::isHosted()) { $this->company->portal_mode = 'subdomain'; - $this->company->portal_domain = ''; + $this->company->portal_domain = ''; } $this->company->save(); - return $this; + return $this; } private function importData() { - - foreach($this->importables as $import){ - + foreach ($this->importables as $import) { $method = "import_{$import}"; nlog($method); $this->{$method}(); - } nlog("finished importing company data"); return $this; - } private function import_bank_integrations() { - $this->genericImport(BankIntegration::class, - ['assigned_user_id','account_id', 'company_id', 'id', 'hashed_id'], + $this->genericImport( + BankIntegration::class, + ['assigned_user_id','account_id', 'company_id', 'id', 'hashed_id'], [ - ['users' => 'user_id'], - ], + ['users' => 'user_id'], + ], 'bank_integrations', - 'description'); + 'description' + ); return $this; } private function import_bank_transactions() { - $this->genericImport(BankTransaction::class, - ['assigned_user_id','company_id', 'id', 'hashed_id', 'user_id'], + $this->genericImport( + BankTransaction::class, + ['assigned_user_id','company_id', 'id', 'hashed_id', 'user_id'], [ - ['users' => 'user_id'], + ['users' => 'user_id'], ['expenses' => 'expense_id'], ['vendors' => 'vendor_id'], ['expense_categories' => 'ninja_category_id'], ['expense_categories' => 'category_id'], ['bank_integrations' => 'bank_integration_id'] - ], + ], 'bank_transactions', - null); + null + ); return $this; } private function import_recurring_expenses() { -//unset / transforms / object_property / match_key - $this->genericImport(RecurringExpense::class, - ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id', 'vendor_id','recurring_expense_id'], + //unset / transforms / object_property / match_key + $this->genericImport( + RecurringExpense::class, + ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id', 'vendor_id','recurring_expense_id'], [ - ['users' => 'user_id'], - ['users' => 'assigned_user_id'], + ['users' => 'user_id'], + ['users' => 'assigned_user_id'], ['clients' => 'client_id'], ['projects' => 'project_id'], ['vendors' => 'vendor_id'], ['invoices' => 'invoice_id'], ['expense_categories' => 'category_id'], - ], + ], 'recurring_expenses', - 'number'); + 'number' + ); return $this; } private function import_payment_terms() { - - $this->genericImport(PaymentTerm::class, - ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'], - [['users' => 'user_id']], + $this->genericImport( + PaymentTerm::class, + ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'], + [['users' => 'user_id']], 'payment_terms', - 'num_days'); + 'num_days' + ); return $this; - } /* Cannot use generic as we are matching on two columns for existing data */ private function import_tax_rates() { - // foreach($this->backup_file->tax_rates as $obj) - foreach((object)$this->getObject("tax_rates") as $obj) - { - + foreach ((object)$this->getObject("tax_rates") as $obj) { $user_id = $this->transformId('users', $obj->user_id); $obj_array = (array)$obj; @@ -618,14 +592,13 @@ class CompanyImport implements ShouldQueue unset($obj_array['tax_rate_id']); $new_obj = TaxRate::firstOrNew( - ['name' => $obj->name, 'company_id' => $this->company->id, 'rate' => $obj->rate], - $obj_array, - ); + ['name' => $obj->name, 'company_id' => $this->company->id, 'rate' => $obj->rate], + $obj_array, + ); $new_obj->company_id = $this->company->id; $new_obj->user_id = $user_id; $new_obj->save(['timestamps' => false]); - } return $this; @@ -633,396 +606,406 @@ class CompanyImport implements ShouldQueue private function import_expense_categories() { - - $this->genericImport(ExpenseCategory::class, - ['user_id', 'company_id', 'id', 'hashed_id'], - [['users' => 'user_id']], + $this->genericImport( + ExpenseCategory::class, + ['user_id', 'company_id', 'id', 'hashed_id'], + [['users' => 'user_id']], 'expense_categories', - 'name'); + 'name' + ); return $this; - } private function import_task_statuses() { - - $this->genericImport(TaskStatus::class, - ['user_id', 'company_id', 'id', 'hashed_id'], - [['users' => 'user_id']], + $this->genericImport( + TaskStatus::class, + ['user_id', 'company_id', 'id', 'hashed_id'], + [['users' => 'user_id']], 'task_statuses', - 'name'); + 'name' + ); return $this; - } private function import_clients() { - - $this->genericImport(Client::class, - ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'gateway_tokens', 'contacts', 'documents','country'], - [['users' => 'user_id'], ['users' => 'assigned_user_id']], + $this->genericImport( + Client::class, + ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'gateway_tokens', 'contacts', 'documents','country'], + [['users' => 'user_id'], ['users' => 'assigned_user_id']], 'clients', - 'number'); + 'number' + ); return $this; - } private function import_client_contacts() { - - $this->genericImport(ClientContact::class, - ['user_id', 'company_id', 'id', 'hashed_id','company'], - [['users' => 'user_id'], ['clients' => 'client_id']], + $this->genericImport( + ClientContact::class, + ['user_id', 'company_id', 'id', 'hashed_id','company'], + [['users' => 'user_id'], ['clients' => 'client_id']], 'client_contacts', - 'email'); + 'email' + ); return $this; - } private function import_vendors() { - - $this->genericImport(Vendor::class, - ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'], - [['users' => 'user_id'], ['users' =>'assigned_user_id']], + $this->genericImport( + Vendor::class, + ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'], + [['users' => 'user_id'], ['users' =>'assigned_user_id']], 'vendors', - 'number'); + 'number' + ); return $this; } private function import_vendor_contacts() { - - $this->genericImport(VendorContact::class, - ['user_id', 'company_id', 'id', 'hashed_id','company','assigned_user_id'], - [['users' => 'user_id'], ['vendors' => 'vendor_id']], + $this->genericImport( + VendorContact::class, + ['user_id', 'company_id', 'id', 'hashed_id','company','assigned_user_id'], + [['users' => 'user_id'], ['vendors' => 'vendor_id']], 'vendor_contacts', - 'email'); + 'email' + ); return $this; - } private function import_projects() { - - $this->genericImport(Project::class, - ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id','client_id'], - [['users' => 'user_id'], ['users' =>'assigned_user_id'], ['clients' => 'client_id']], + $this->genericImport( + Project::class, + ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id','client_id'], + [['users' => 'user_id'], ['users' =>'assigned_user_id'], ['clients' => 'client_id']], 'projects', - 'number'); + 'number' + ); - return $this; + return $this; } private function import_products() { - - $this->genericNewClassImport(Product::class, + $this->genericNewClassImport( + Product::class, ['user_id', 'company_id', 'hashed_id', 'id'], [['users' => 'user_id'], ['users' =>'assigned_user_id'], ['vendors' => 'vendor_id'], ['projects' => 'project_id']], - 'products' + 'products' ); - return $this; + return $this; } private function import_company_gateways() { - - $this->genericNewClassImport(CompanyGateway::class, + $this->genericNewClassImport( + CompanyGateway::class, ['user_id', 'company_id', 'hashed_id', 'id'], [['users' => 'user_id']], - 'company_gateways' + 'company_gateways' ); - return $this; + return $this; } private function import_client_gateway_tokens() { + $this->genericNewClassImport( + ClientGatewayToken::class, + ['company_id', 'id', 'hashed_id','client_id'], + [['clients' => 'client_id', 'company_gateways' => 'company_gateway_id']], + 'client_gateway_tokens' + ); - $this->genericNewClassImport(ClientGatewayToken::class, - ['company_id', 'id', 'hashed_id','client_id'], - [['clients' => 'client_id', 'company_gateways' => 'company_gateway_id']], - 'client_gateway_tokens'); - - return $this; + return $this; } private function import_group_settings() { - - $this->genericImport(GroupSetting::class, - ['user_id', 'company_id', 'id', 'hashed_id'], - [['users' => 'user_id']], + $this->genericImport( + GroupSetting::class, + ['user_id', 'company_id', 'id', 'hashed_id'], + [['users' => 'user_id']], 'group_settings', - 'name'); + 'name' + ); - return $this; + return $this; } private function import_subscriptions() { - - $this->genericImport(Subscription::class, - ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'], - [['group_settings' => 'group_id'], ['users' => 'user_id'], ['users' => 'assigned_user_id']], + $this->genericImport( + Subscription::class, + ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'], + [['group_settings' => 'group_id'], ['users' => 'user_id'], ['users' => 'assigned_user_id']], 'subscriptions', - 'name'); + 'name' + ); - return $this; + return $this; } private function import_recurring_invoices() { - - $this->genericImport(RecurringInvoice::class, - ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'client_id','subscription_id','project_id','vendor_id','status'], + $this->genericImport( + RecurringInvoice::class, + ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'client_id','subscription_id','project_id','vendor_id','status'], [ - ['subscriptions' => 'subscription_id'], - ['users' => 'user_id'], + ['subscriptions' => 'subscription_id'], + ['users' => 'user_id'], ['users' => 'assigned_user_id'], ['clients' => 'client_id'], ['projects' => 'project_id'], ['vendors' => 'vendor_id'], ['clients' => 'client_id'], - ], + ], 'recurring_invoices', - 'number'); + 'number' + ); return $this; - } private function import_recurring_invoice_invitations() { - - - $this->genericImport(RecurringInvoiceInvitation::class, - ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'recurring_invoice_id'], + $this->genericImport( + RecurringInvoiceInvitation::class, + ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'recurring_invoice_id'], [ - ['users' => 'user_id'], + ['users' => 'user_id'], ['recurring_invoices' => 'recurring_invoice_id'], ['client_contacts' => 'client_contact_id'], - ], + ], 'recurring_invoice_invitations', - 'key'); + 'key' + ); return $this; - } private function import_invoices() { - - $this->genericImport(Invoice::class, - ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'], + $this->genericImport( + Invoice::class, + ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'], [ - ['users' => 'user_id'], - ['users' => 'assigned_user_id'], + ['users' => 'user_id'], + ['users' => 'assigned_user_id'], ['recurring_invoices' => 'recurring_id'], ['clients' => 'client_id'], ['subscriptions' => 'subscription_id'], ['projects' => 'project_id'], ['vendors' => 'vendor_id'], - ], + ], 'invoices', - 'number'); + 'number' + ); - return $this; + return $this; } private function import_invoice_invitations() { - - - $this->genericImport(InvoiceInvitation::class, - ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'invoice_id'], + $this->genericImport( + InvoiceInvitation::class, + ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'invoice_id'], [ - ['users' => 'user_id'], + ['users' => 'user_id'], ['invoices' => 'invoice_id'], ['client_contacts' => 'client_contact_id'], - ], + ], 'invoice_invitations', - 'key'); + 'key' + ); - return $this; + return $this; } private function import_purchase_orders() { - - $this->genericImport(PurchaseOrder::class, - ['user_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status', 'vendor_id', 'subscription_id','client_id'], + $this->genericImport( + PurchaseOrder::class, + ['user_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status', 'vendor_id', 'subscription_id','client_id'], [ - ['users' => 'user_id'], - ['users' => 'assigned_user_id'], + ['users' => 'user_id'], + ['users' => 'assigned_user_id'], ['recurring_invoices' => 'recurring_id'], ['projects' => 'project_id'], ['vendors' => 'vendor_id'], - ], + ], 'purchase_orders', - 'number'); + 'number' + ); - return $this; + return $this; } private function import_purchase_order_invitations() { - - - $this->genericImport(PurchaseOrderInvitation::class, - ['user_id', 'vendor_contact_id', 'company_id', 'id', 'hashed_id', 'purchase_order_id'], + $this->genericImport( + PurchaseOrderInvitation::class, + ['user_id', 'vendor_contact_id', 'company_id', 'id', 'hashed_id', 'purchase_order_id'], [ - ['users' => 'user_id'], + ['users' => 'user_id'], ['purchase_orders' => 'purchase_order_id'], ['vendor_contacts' => 'vendor_contact_id'], - ], + ], 'purchase_order_invitations', - 'key'); + 'key' + ); - return $this; + return $this; } private function import_quotes() { - - $this->genericImport(Quote::class, - ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'], + $this->genericImport( + Quote::class, + ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'], [ - ['users' => 'user_id'], - ['users' => 'assigned_user_id'], + ['users' => 'user_id'], + ['users' => 'assigned_user_id'], ['recurring_invoices' => 'recurring_id'], ['clients' => 'client_id'], ['subscriptions' => 'subscription_id'], ['projects' => 'project_id'], ['vendors' => 'vendor_id'], - ], + ], 'quotes', - 'number'); + 'number' + ); return $this; - } private function import_quote_invitations() { - - $this->genericImport(QuoteInvitation::class, - ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'quote_id'], + $this->genericImport( + QuoteInvitation::class, + ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'quote_id'], [ - ['users' => 'user_id'], + ['users' => 'user_id'], ['quotes' => 'quote_id'], ['client_contacts' => 'client_contact_id'], - ], + ], 'quote_invitations', - 'key'); + 'key' + ); - return $this; + return $this; } private function import_credits() { - - - $this->genericImport(Credit::class, - ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'], + $this->genericImport( + Credit::class, + ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id','status'], [ - ['users' => 'user_id'], - ['users' => 'assigned_user_id'], + ['users' => 'user_id'], + ['users' => 'assigned_user_id'], ['recurring_invoices' => 'recurring_id'], ['clients' => 'client_id'], ['subscriptions' => 'subscription_id'], ['projects' => 'project_id'], ['vendors' => 'vendor_id'], - ], + ], 'credits', - 'number'); + 'number' + ); - return $this; + return $this; } private function import_credit_invitations() { - - $this->genericImport(CreditInvitation::class, - ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'credit_id'], + $this->genericImport( + CreditInvitation::class, + ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'credit_id'], [ - ['users' => 'user_id'], + ['users' => 'user_id'], ['credits' => 'credit_id'], ['client_contacts' => 'client_contact_id'], - ], + ], 'credit_invitations', - 'key'); + 'key' + ); - return $this; + return $this; } private function import_expenses() { - - $this->genericImport(Expense::class, - ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id','vendor_id','recurring_expense_id'], + $this->genericImport( + Expense::class, + ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id','vendor_id','recurring_expense_id'], [ - ['users' => 'user_id'], - ['users' => 'assigned_user_id'], + ['users' => 'user_id'], + ['users' => 'assigned_user_id'], ['clients' => 'client_id'], ['projects' => 'project_id'], ['vendors' => 'vendor_id'], ['invoices' => 'invoice_id'], // ['recurring_expenses' => 'recurring_expense_id'], ['expense_categories' => 'category_id'], - ], + ], 'expenses', - 'number'); + 'number' + ); return $this; - } private function import_tasks() { - - $this->genericImport(Task::class, - ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'invoice_id','project_id'], + $this->genericImport( + Task::class, + ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'invoice_id','project_id'], [ - ['users' => 'user_id'], - ['users' => 'assigned_user_id'], + ['users' => 'user_id'], + ['users' => 'assigned_user_id'], ['clients' => 'client_id'], ['projects' => 'project_id'], ['invoices' => 'invoice_id'], - ], + ], 'tasks', - 'number'); + 'number' + ); - return $this; + return $this; } private function import_payments() { - - $this->genericImport(Payment::class, - ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'client_contact_id','invitation_id','vendor_id','paymentables'], + $this->genericImport( + Payment::class, + ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'client_contact_id','invitation_id','vendor_id','paymentables'], [ - ['users' => 'user_id'], - ['users' => 'assigned_user_id'], + ['users' => 'user_id'], + ['users' => 'assigned_user_id'], ['clients' => 'client_id'], ['client_contacts' => 'client_contact_id'], ['vendors' => 'vendor_id'], ['invoice_invitations' => 'invitation_id'], ['company_gateways' => 'company_gateway_id'], ['bank_transactions' => 'transaction_id'], - ], + ], 'payments', - 'number'); + 'number' + ); $this->paymentablesImport(); @@ -1031,20 +1014,20 @@ class CompanyImport implements ShouldQueue private function import_activities() { - $activities = []; - $this->genericNewClassImport(Activity::class, + $this->genericNewClassImport( + Activity::class, [ 'hashed_id', 'company_id', 'backup', 'invitation_id', 'payment_id', - ], + ], [ - ['users' => 'user_id'], + ['users' => 'user_id'], ['clients' => 'client_id'], ['client_contacts' => 'client_contact_id'], ['projects' => 'project_id'], @@ -1059,68 +1042,68 @@ class CompanyImport implements ShouldQueue ['recurring_invoices' => 'recurring_invoice_id'], // ['recurring_expenses' => 'recurring_expense_id'], // ['invitations' => 'invitation_id'], - ], - 'activities'); + ], + 'activities' + ); return $this; - } private function import_backups() { - - $this->genericImportWithoutCompany(Backup::class, - ['hashed_id','id'], + $this->genericImportWithoutCompany( + Backup::class, + ['hashed_id','id'], [ - ['activities' => 'activity_id'], - ], + ['activities' => 'activity_id'], + ], 'backups', - 'created_at'); + 'created_at' + ); - return $this; - } + return $this; + } private function import_company_ledger() { - - $this->genericImport(CompanyLedger::class, - ['company_id', 'user_id', 'client_id', 'activity_id', 'id','account_id'], + $this->genericImport( + CompanyLedger::class, + ['company_id', 'user_id', 'client_id', 'activity_id', 'id','account_id'], [ - ['users' => 'user_id'], + ['users' => 'user_id'], ['clients' => 'client_id'], // ['activities' => 'activity_id'], - ], + ], 'company_ledger', - 'created_at'); + 'created_at' + ); return $this; - } private function import_designs() { - - $this->genericImport(Design::class, - ['company_id', 'user_id', 'hashed_id'], + $this->genericImport( + Design::class, + ['company_id', 'user_id', 'hashed_id'], [ ['users' => 'user_id'], - ], + ], 'designs', - 'name'); + 'name' + ); return $this; - } private function import_documents() { - - foreach((object)$this->getObject("documents") as $document) - { + foreach ((object)$this->getObject("documents") as $document) { //todo enable this for v5.5.51 - if(!$this->transformDocumentId($document->documentable_id, $document->documentable_type)) + if (!$this->transformDocumentId($document->documentable_id, $document->documentable_type)) { continue; + } $new_document = new Document(); $new_document->user_id = $this->transformId('users', $document->user_id); @@ -1151,31 +1134,24 @@ class CompanyImport implements ShouldQueue $storage_url = (object)$this->getObject('storage_url', true); - if(!Storage::exists($new_document->url) && is_string($storage_url)){ - + if (!Storage::exists($new_document->url) && is_string($storage_url)) { $url = $storage_url . $new_document->url; $file = @file_get_contents($url); - if($file) - { - try{ + if ($file) { + try { Storage::disk(config('filesystems.default'))->put($new_document->url, $file); $new_document->disk = config('filesystems.default'); $new_document->save(); - - } - catch(\Exception $e) - { + } catch(\Exception $e) { nlog($e->getMessage()); nlog("I could not upload {$new_document->url}"); $new_document->forceDelete(); } } - } - } return $this; @@ -1183,14 +1159,15 @@ class CompanyImport implements ShouldQueue private function import_webhooks() { - - $this->genericImport(Webhook::class, - ['company_id', 'user_id'], + $this->genericImport( + Webhook::class, + ['company_id', 'user_id'], [ ['users' => 'user_id'], - ], + ], 'webhooks', - 'created_at'); + 'created_at' + ); return $this; } @@ -1206,11 +1183,10 @@ class CompanyImport implements ShouldQueue User::unguard(); //foreach ($this->backup_file->users as $user) - foreach((object)$this->getObject("users") as $user) - { - - if(User::withTrashed()->where('email', $user->email)->where('account_id', '!=', $this->account->id)->exists()) + foreach ((object)$this->getObject("users") as $user) { + if (User::withTrashed()->where('email', $user->email)->where('account_id', '!=', $this->account->id)->exists()) { throw new ImportCompanyFailed("{$user->email} is already in the system attached to a different account"); + } $user_array = (array)$user; unset($user_array['laravel_through_key']); @@ -1228,11 +1204,9 @@ class CompanyImport implements ShouldQueue $new_user->save(['timestamps' => false]); $this->ids['users']["{$user->hashed_id}"] = $new_user->id; - } User::reguard(); - } private function import_company_users() @@ -1240,8 +1214,7 @@ class CompanyImport implements ShouldQueue CompanyUser::unguard(); // foreach($this->backup_file->company_users as $cu) - foreach((object)$this->getObject("company_users") as $cu) - { + foreach ((object)$this->getObject("company_users") as $cu) { $user_id = $this->transformId('users', $cu->user_id); $cu_array = (array)$cu; @@ -1262,11 +1235,9 @@ class CompanyImport implements ShouldQueue $new_cu->account_id = $this->account->id; $new_cu->save(['timestamps' => false]); - } CompanyUser::reguard(); - } private function transformDocumentId($id, $type) @@ -1318,14 +1289,9 @@ class CompanyImport implements ShouldQueue private function paymentablesImport() { - // foreach($this->backup_file->payments as $payment) - foreach((object)$this->getObject("payments") as $payment) - { - - foreach($payment->paymentables as $paymentable_obj) - { - + foreach ((object)$this->getObject("payments") as $payment) { + foreach ($payment->paymentables as $paymentable_obj) { $paymentable = new Paymentable(); $paymentable->payment_id = $this->transformId('payments', $paymentable_obj->payment_id); $paymentable->paymentable_type = $paymentable_obj->paymentable_type; @@ -1351,9 +1317,9 @@ class CompanyImport implements ShouldQueue break; case Credit::class: return $this->transformId('credits', $id); - break; + break; case Payment::class: - return $this->transformId('payments', $id); + return $this->transformId('payments', $id); default: # code... break; @@ -1363,66 +1329,57 @@ class CompanyImport implements ShouldQueue private function genericNewClassImport($class, $unset, $transforms, $object_property) { - $class::unguard(); - foreach((object)$this->getObject($object_property) as $obj) - { + foreach ((object)$this->getObject($object_property) as $obj) { /* Remove unwanted keys*/ $obj_array = (array)$obj; - foreach($unset as $un){ + foreach ($unset as $un) { unset($obj_array[$un]); } - if($class instanceof CompanyGateway){ - - if(Ninja::isHosted() && $obj_array['gateway_key'] == 'd14dd26a37cecc30fdd65700bfb55b23'){ + if ($class instanceof CompanyGateway) { + if (Ninja::isHosted() && $obj_array['gateway_key'] == 'd14dd26a37cecc30fdd65700bfb55b23') { $obj_array['gateway_key'] = 'd14dd26a47cecc30fdd65700bfb67b34'; } - if(Ninja::isSelfHost() && $obj_array['gateway_key'] == 'd14dd26a47cecc30fdd65700bfb67b34'){ + if (Ninja::isSelfHost() && $obj_array['gateway_key'] == 'd14dd26a47cecc30fdd65700bfb67b34') { $obj_array['gateway_key'] = 'd14dd26a37cecc30fdd65700bfb55b23'; - } - + } } - if(array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1){ + if (array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1) { $obj_array['deleted_at'] = now(); } $activity_invitation_key = false; - if($class == 'App\Models\Activity'){ - - if(isset($obj->invitation_id)){ - - if(isset($obj->invoice_id)) + if ($class == 'App\Models\Activity') { + if (isset($obj->invitation_id)) { + if (isset($obj->invoice_id)) { $activity_invitation_key = 'invoice_invitations'; - elseif(isset($obj->quote_id)) + } elseif (isset($obj->quote_id)) { $activity_invitation_key = 'quote_invitations'; - elseif(isset($obj->credit_id)) + } elseif (isset($obj->credit_id)) { $activity_invitation_key = 'credit_invitations'; - + } } $obj_array['account_id'] = $this->account->id; - } /* Transform old keys to new keys */ - foreach($transforms as $transform) - { - foreach($transform as $key => $value) - { - if($class == 'App\Models\Activity' && $activity_invitation_key && $key == 'invitations'){ + foreach ($transforms as $transform) { + foreach ($transform as $key => $value) { + if ($class == 'App\Models\Activity' && $activity_invitation_key && $key == 'invitations') { $key = $activity_invitation_key; } $obj_array["{$value}"] = $this->transformId($key, $obj->{$value}); - } + } } - if($class == 'App\Models\CompanyGateway') { + if ($class == 'App\Models\CompanyGateway') { $obj_array['config'] = encrypt($obj_array['config']); } @@ -1433,105 +1390,90 @@ class CompanyImport implements ShouldQueue $new_obj->save(['timestamps' => false]); $this->ids["{$object_property}"]["{$obj->hashed_id}"] = $new_obj->id; - } $class::reguard(); - - } private function genericImportWithoutCompany($class, $unset, $transforms, $object_property, $match_key) { - $class::unguard(); //foreach($this->backup_file->{$object_property} as $obj) - foreach((object)$this->getObject($object_property) as $obj) - { - - if(is_null($obj)) + foreach ((object)$this->getObject($object_property) as $obj) { + if (is_null($obj)) { continue; + } /* Remove unwanted keys*/ $obj_array = (array)$obj; - foreach($unset as $un){ + foreach ($unset as $un) { unset($obj_array[$un]); } /* Transform old keys to new keys */ - foreach($transforms as $transform) - { - foreach($transform as $key => $value) - { + foreach ($transforms as $transform) { + foreach ($transform as $key => $value) { $obj_array["{$value}"] = $this->transformId($key, $obj->{$value}); - } + } } - if(array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1){ + if (array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1) { $obj_array['deleted_at'] = now(); } /* New to convert product ids from old hashes to new hashes*/ - 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']); + 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']); } $new_obj = $class::firstOrNew( - [$match_key => $obj->{$match_key}], - $obj_array, - ); + [$match_key => $obj->{$match_key}], + $obj_array, + ); $new_obj->save(['timestamps' => false]); - if($new_obj instanceof CompanyLedger){ - - } - else + if ($new_obj instanceof CompanyLedger) { + } else { $this->ids["{$object_property}"]["{$obj->hashed_id}"] = $new_obj->id; - + } } $class::reguard(); - } /* Ensure if no number is set, we don't overwrite a record with an existing number */ private function genericImport($class, $unset, $transforms, $object_property, $match_key) { - $class::unguard(); $x = 0; - foreach((object)$this->getObject($object_property) as $obj) - { - + foreach ((object)$this->getObject($object_property) as $obj) { /* Remove unwanted keys*/ $obj_array = (array)$obj; - foreach($unset as $un){ + foreach ($unset as $un) { unset($obj_array[$un]); } /* Transform old keys to new keys */ - foreach($transforms as $transform) - { - foreach($transform as $key => $value) - { + foreach ($transforms as $transform) { + foreach ($transform as $key => $value) { $obj_array["{$value}"] = $this->transformId($key, $obj->{$value}); - } + } } - if(array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1){ + if (array_key_exists('deleted_at', $obj_array) && $obj_array['deleted_at'] > 1) { $obj_array['deleted_at'] = now(); } /* New to convert product ids from old hashes to new hashes*/ - if($class == 'App\Models\Subscription'){ - - if(array_key_exists('company', $obj_array)) + if ($class == 'App\Models\Subscription') { + if (array_key_exists('company', $obj_array)) { unset($obj_array['company']); + } $obj_array['webhook_configuration'] = (array)$obj_array['webhook_configuration']; $obj_array['recurring_product_ids'] = ''; @@ -1539,147 +1481,128 @@ class CompanyImport implements ShouldQueue } /* Expenses that don't have a number will not be inserted - so need to override here*/ - if($class == 'App\Models\Expense' && is_null($obj->{$match_key})){ + if ($class == 'App\Models\Expense' && is_null($obj->{$match_key})) { $new_obj = new Expense(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); $new_obj->number = $this->getNextExpenseNumber($new_obj); - - } - elseif($class == 'App\Models\Invoice' && is_null($obj->{$match_key})){ + } elseif ($class == 'App\Models\Invoice' && is_null($obj->{$match_key})) { $new_obj = new Invoice(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); - $new_obj->number = $this->getNextInvoiceNumber($client = Client::withTrashed()->find($obj_array['client_id']),$new_obj); - } - elseif($class == 'App\Models\PurchaseOrder' && is_null($obj->{$match_key})){ + $new_obj->number = $this->getNextInvoiceNumber($client = Client::withTrashed()->find($obj_array['client_id']), $new_obj); + } elseif ($class == 'App\Models\PurchaseOrder' && is_null($obj->{$match_key})) { $new_obj = new PurchaseOrder(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); $new_obj->number = $this->getNextPurchaseOrderNumber($new_obj); - } - elseif($class == 'App\Models\Payment' && is_null($obj->{$match_key})){ + } elseif ($class == 'App\Models\Payment' && is_null($obj->{$match_key})) { $new_obj = new Payment(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); $new_obj->number = $this->getNextPaymentNumber($client = Client::withTrashed()->find($obj_array['client_id']), $new_obj); - } - elseif($class == 'App\Models\Quote' && is_null($obj->{$match_key})){ + } elseif ($class == 'App\Models\Quote' && is_null($obj->{$match_key})) { $new_obj = new Quote(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); $new_obj->number = $this->getNextQuoteNumber($client = Client::withTrashed()->find($obj_array['client_id']), $new_obj); - } - elseif($class == 'App\Models\ClientContact'){ + } elseif ($class == 'App\Models\ClientContact') { $new_obj = new ClientContact(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); - } - elseif($class == 'App\Models\VendorContact'){ + } elseif ($class == 'App\Models\VendorContact') { $new_obj = new VendorContact(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); - } - elseif($class == 'App\Models\RecurringExpense' && is_null($obj->{$match_key})){ + } elseif ($class == 'App\Models\RecurringExpense' && is_null($obj->{$match_key})) { $new_obj = new RecurringExpense(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); - $new_obj->number = $this->getNextRecurringExpenseNumber($new_obj); - } - elseif($class == 'App\Models\Project' && is_null($obj->{$match_key})){ + $new_obj->number = $this->getNextRecurringExpenseNumber($new_obj); + } elseif ($class == 'App\Models\Project' && is_null($obj->{$match_key})) { $new_obj = new Project(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); - $new_obj->number = $this->getNextProjectNumber($new_obj); - } - elseif($class == 'App\Models\Task' && is_null($obj->{$match_key})){ + $new_obj->number = $this->getNextProjectNumber($new_obj); + } elseif ($class == 'App\Models\Task' && is_null($obj->{$match_key})) { $new_obj = new Task(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); - $new_obj->number = $this->getNextTaskNumber($new_obj); - } - elseif($class == 'App\Models\Vendor' && is_null($obj->{$match_key})){ + $new_obj->number = $this->getNextTaskNumber($new_obj); + } elseif ($class == 'App\Models\Vendor' && is_null($obj->{$match_key})) { $new_obj = new Vendor(); $new_obj->company_id = $this->company->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); - $new_obj->number = $this->getNextVendorNumber($new_obj); - } - elseif($class == 'App\Models\CompanyLedger'){ + $new_obj->number = $this->getNextVendorNumber($new_obj); + } elseif ($class == 'App\Models\CompanyLedger') { $new_obj = $class::firstOrNew( - [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id], - $obj_array, - ); - } - elseif($class == 'App\Models\BankIntegration'){ + [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id], + $obj_array, + ); + } elseif ($class == 'App\Models\BankIntegration') { $new_obj = new BankIntegration(); $new_obj->company_id = $this->company->id; $new_obj->account_id = $this->account->id; $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); - } - elseif($class == 'App\Models\BankTransaction'){ - + } elseif ($class == 'App\Models\BankTransaction') { $new_obj = new BankTransaction(); $new_obj->company_id = $this->company->id; - $obj_array['invoice_ids'] = collect(explode(",",$obj_array['invoice_ids']))->map(function ($id) { - return $this->transformId('invoices', $id); - })->map(function ($encodeable){ + $obj_array['invoice_ids'] = collect(explode(",", $obj_array['invoice_ids']))->map(function ($id) { + return $this->transformId('invoices', $id); + })->map(function ($encodeable) { return $this->encodePrimaryKey($encodeable); })->implode(","); $new_obj->fill($obj_array); $new_obj->save(['timestamps' => false]); - } - else{ + } else { $new_obj = $class::withTrashed()->firstOrNew( - [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id], - $obj_array, - ); - } + [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id], + $obj_array, + ); + } $new_obj->save(['timestamps' => false]); - if($new_obj instanceof CompanyLedger){ - } - else + if ($new_obj instanceof CompanyLedger) { + } else { $this->ids["{$object_property}"]["{$obj->hashed_id}"] = $new_obj->id; - + } } $class::reguard(); - } private function recordProductIds($ids) { - $id_array = explode(",", $ids); $tmp_arr = []; - foreach($id_array as $id) { - - if(!$id) + foreach ($id_array as $id) { + if (!$id) { continue; + } $id = $this->decodePrimaryKey($id); nlog($id); $tmp_arr[] = $this->encodePrimaryKey($this->transformId('products', $id)); - } + } return implode(",", $tmp_arr); } @@ -1689,19 +1612,19 @@ class CompanyImport implements ShouldQueue * In the case of users - we need to check if the system * is attempting to migrate resources above their quota, * - * ie. > 50 clients or more than 1 user + * ie. > 50 clients or more than 1 user */ private function transformId(string $resource, ?string $old): ?int { - if(empty($old)) + if (empty($old)) { return null; + } - if ($resource == 'users' && $this->force_user_coalesce){ + if ($resource == 'users' && $this->force_user_coalesce) { return $this->company_owner->id; } if (! array_key_exists($resource, $this->ids)) { - $this->sendImportMail("The Import failed due to missing data in the import file. Resource {$resource} not available."); throw new \Exception("Resource {$resource} not available."); @@ -1713,8 +1636,9 @@ class CompanyImport implements ShouldQueue nlog("If we are missing a user - default to the company owner"); - if($resource == 'users') + if ($resource == 'users') { return $this->company_owner->id; + } $this->sendImportMail("The Import failed due to missing data in the import file. Resource {$resource} not available."); @@ -1727,8 +1651,8 @@ class CompanyImport implements ShouldQueue } - private function sendImportMail($message){ - + private function sendImportMail($message) + { App::forgetInstance('translator'); $t = app('translator'); $t->replace(Ninja::transformTranslations($this->company->settings)); @@ -1741,6 +1665,5 @@ class CompanyImport implements ShouldQueue $nmo->settings = $this->company->settings; $nmo->to_user = $this->company->owner(); NinjaMailerJob::dispatch($nmo); - } -} \ No newline at end of file +} diff --git a/app/Jobs/Company/CreateCompany.php b/app/Jobs/Company/CreateCompany.php index 1d6a7cb1efba..78dcff40618b 100644 --- a/app/Jobs/Company/CreateCompany.php +++ b/app/Jobs/Company/CreateCompany.php @@ -18,7 +18,6 @@ use App\Models\Company; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Bus\Dispatchable; -use Illuminate\Http\Request; class CreateCompany { diff --git a/app/Jobs/Credit/ApplyCreditPayment.php b/app/Jobs/Credit/ApplyCreditPayment.php index 398e5a7eae8d..77e875ccf832 100644 --- a/app/Jobs/Credit/ApplyCreditPayment.php +++ b/app/Jobs/Credit/ApplyCreditPayment.php @@ -51,7 +51,6 @@ class ApplyCreditPayment implements ShouldQueue */ public function handle() { - /* Update Pivot Record amount */ $this->payment->credits->each(function ($cred) { if ($cred->id == $this->credit->id) { @@ -66,7 +65,6 @@ class ApplyCreditPayment implements ShouldQueue $credit_balance = $this->credit->balance; if ($this->amount == $credit_balance) { //total credit applied. - $this->credit ->service() ->markSent() @@ -75,7 +73,6 @@ class ApplyCreditPayment implements ShouldQueue ->updatePaidToDate($this->amount) ->save(); } elseif ($this->amount < $credit_balance) { //compare number appropriately - $this->credit ->service() ->markSent() diff --git a/app/Jobs/Credit/ZipCredits.php b/app/Jobs/Credit/ZipCredits.php index 1b56f7ff5a6e..b649d6f7ee85 100644 --- a/app/Jobs/Credit/ZipCredits.php +++ b/app/Jobs/Credit/ZipCredits.php @@ -19,15 +19,12 @@ use App\Libraries\MultiDB; use App\Mail\DownloadCredits; use App\Models\Company; use App\Models\User; -use App\Utils\TempFile; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Storage; -use ZipArchive; class ZipCredits implements ShouldQueue { diff --git a/app/Jobs/Cron/AutoBill.php b/app/Jobs/Cron/AutoBill.php index 58d7435bd737..60f0c2572d76 100644 --- a/app/Jobs/Cron/AutoBill.php +++ b/app/Jobs/Cron/AutoBill.php @@ -13,9 +13,9 @@ namespace App\Jobs\Cron; use App\Libraries\MultiDB; use App\Models\Invoice; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; diff --git a/app/Jobs/Cron/AutoBillCron.php b/app/Jobs/Cron/AutoBillCron.php index 242bb0050278..8879c6930776 100644 --- a/app/Jobs/Cron/AutoBillCron.php +++ b/app/Jobs/Cron/AutoBillCron.php @@ -11,11 +11,8 @@ namespace App\Jobs\Cron; -use App\Jobs\Cron\AutoBill; -use App\Jobs\RecurringInvoice\SendRecurring; use App\Libraries\MultiDB; use App\Models\Invoice; -use App\Models\RecurringInvoice; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Support\Carbon; @@ -63,14 +60,11 @@ class AutoBillCron nlog($auto_bill_partial_invoices->count().' partial invoices to auto bill'); $auto_bill_partial_invoices->chunk(400, function ($invoices) { - - foreach($invoices as $invoice) - { + foreach ($invoices as $invoice) { AutoBill::dispatch($invoice->id, false); } sleep(2); - }); $auto_bill_invoices = Invoice::whereDate('due_date', '<=', now()) @@ -87,14 +81,11 @@ class AutoBillCron nlog($auto_bill_invoices->count().' full invoices to auto bill'); $auto_bill_invoices->chunk(400, function ($invoices) { - - foreach($invoices as $invoice) - { + foreach ($invoices as $invoice) { AutoBill::dispatch($invoice->id, false); } sleep(2); - }); } else { //multiDB environment, need to @@ -114,10 +105,8 @@ class AutoBillCron nlog($auto_bill_partial_invoices->count()." partial invoices to auto bill db = {$db}"); - $auto_bill_partial_invoices->chunk(400, function ($invoices) use($db){ - - foreach($invoices as $invoice) - { + $auto_bill_partial_invoices->chunk(400, function ($invoices) use ($db) { + foreach ($invoices as $invoice) { AutoBill::dispatch($invoice->id, $db); } @@ -137,15 +126,12 @@ class AutoBillCron nlog($auto_bill_invoices->count()." full invoices to auto bill db = {$db}"); - $auto_bill_invoices->chunk(400, function ($invoices) use($db){ - - foreach($invoices as $invoice) - { + $auto_bill_invoices->chunk(400, function ($invoices) use ($db) { + foreach ($invoices as $invoice) { AutoBill::dispatch($invoice->id, $db); } sleep(2); - }); } diff --git a/app/Jobs/Cron/CompanyRecurringCron.php b/app/Jobs/Cron/CompanyRecurringCron.php index a50663daebb5..a46d84e5af44 100644 --- a/app/Jobs/Cron/CompanyRecurringCron.php +++ b/app/Jobs/Cron/CompanyRecurringCron.php @@ -11,12 +11,10 @@ namespace App\Jobs\Cron; -use App\Jobs\RecurringInvoice\SendRecurring; use App\Libraries\MultiDB; use App\Models\Company; use App\Models\RecurringInvoice; use Illuminate\Foundation\Bus\Dispatchable; -use Illuminate\Support\Carbon; /*@not used*/ @@ -44,27 +42,24 @@ class CompanyRecurringCron { //multiDB environment, need to foreach (MultiDB::$dbs as $db) { - MultiDB::setDB($db); Company::where('is_disabled', 0) - ->whereHas('recurring_invoices', function ($query){ - $query->where('next_send_date', '<=', now()->toDateTimeString()) - ->whereNotNull('next_send_date') - ->whereNull('deleted_at') - ->where('is_deleted', false) - ->where('status_id', RecurringInvoice::STATUS_ACTIVE) - ->where('remaining_cycles', '!=', '0') - ->whereHas('client', function ($query) { + ->whereHas('recurring_invoices', function ($query) { + $query->where('next_send_date', '<=', now()->toDateTimeString()) + ->whereNotNull('next_send_date') + ->whereNull('deleted_at') + ->where('is_deleted', false) + ->where('status_id', RecurringInvoice::STATUS_ACTIVE) + ->where('remaining_cycles', '!=', '0') + ->whereHas('client', function ($query) { $query->where('is_deleted', 0) ->where('deleted_at', null); - }); - }) - ->cursor()->each(function ($company){ - - SendCompanyRecurring::dispatch($company->id, $company->db); - - }); + }); + }) + ->cursor()->each(function ($company) { + SendCompanyRecurring::dispatch($company->id, $company->db); + }); } } } diff --git a/app/Jobs/Cron/RecurringExpensesCron.php b/app/Jobs/Cron/RecurringExpensesCron.php index c6733f64757d..773a97e26ebe 100644 --- a/app/Jobs/Cron/RecurringExpensesCron.php +++ b/app/Jobs/Cron/RecurringExpensesCron.php @@ -46,7 +46,6 @@ class RecurringExpensesCron nlog('Sending recurring expenses '.Carbon::now()->format('Y-m-d h:i:s')); if (! config('ninja.db.multi_db_enabled')) { - $recurring_expenses = RecurringExpense::where('next_send_date', '<=', now()->toDateTimeString()) ->whereNotNull('next_send_date') ->whereNull('deleted_at') @@ -67,34 +66,31 @@ class RecurringExpensesCron $this->generateExpense($recurring_expense); } }); - } else { //multiDB environment, need to foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); - $recurring_expenses = RecurringExpense::where('next_send_date', '<=', now()->toDateTimeString()) - ->whereNotNull('next_send_date') - ->whereNull('deleted_at') - ->where('status_id', RecurringInvoice::STATUS_ACTIVE) - ->where('remaining_cycles', '!=', '0') - ->whereHas('company', function ($query) { - $query->where('is_disabled', 0); - }) - ->with('company') - ->cursor(); + $recurring_expenses = RecurringExpense::where('next_send_date', '<=', now()->toDateTimeString()) + ->whereNotNull('next_send_date') + ->whereNull('deleted_at') + ->where('status_id', RecurringInvoice::STATUS_ACTIVE) + ->where('remaining_cycles', '!=', '0') + ->whereHas('company', function ($query) { + $query->where('is_disabled', 0); + }) + ->with('company') + ->cursor(); - nlog(now()->format('Y-m-d').' Generating Recurring Expenses. Count = '.$recurring_expenses->count()); - - $recurring_expenses->each(function ($recurring_expense, $key) { - nlog('Current date = '.now()->format('Y-m-d').' Recurring date = '.$recurring_expense->next_send_date); - - if (! $recurring_expense->company->is_disabled) { - $this->generateExpense($recurring_expense); - } - }); + nlog(now()->format('Y-m-d').' Generating Recurring Expenses. Count = '.$recurring_expenses->count()); + $recurring_expenses->each(function ($recurring_expense, $key) { + nlog('Current date = '.now()->format('Y-m-d').' Recurring date = '.$recurring_expense->next_send_date); + if (! $recurring_expense->company->is_disabled) { + $this->generateExpense($recurring_expense); + } + }); } } } diff --git a/app/Jobs/Cron/RecurringInvoicesCron.php b/app/Jobs/Cron/RecurringInvoicesCron.php index 48dd442d402f..69bf17a41fb4 100644 --- a/app/Jobs/Cron/RecurringInvoicesCron.php +++ b/app/Jobs/Cron/RecurringInvoicesCron.php @@ -104,7 +104,6 @@ class RecurringInvoicesCron nlog(now()->format('Y-m-d').' Sending Recurring Invoices. Count = '.$recurring_invoices->count()); $recurring_invoices->each(function ($recurring_invoice, $key) { - nlog("Trying to send {$recurring_invoice->number}"); if ($recurring_invoice->company->stop_on_unpaid_recurring) { @@ -123,6 +122,5 @@ class RecurringInvoicesCron } nlog("Recurring invoice send duration " . $start . " - " . Carbon::now()->format('Y-m-d h:i:s')); - } } diff --git a/app/Jobs/Cron/SendCompanyRecurring.php b/app/Jobs/Cron/SendCompanyRecurring.php index 14c9c063ddd1..6b1d31e7dae4 100644 --- a/app/Jobs/Cron/SendCompanyRecurring.php +++ b/app/Jobs/Cron/SendCompanyRecurring.php @@ -16,7 +16,6 @@ use App\Libraries\MultiDB; use App\Models\Company; use App\Models\RecurringInvoice; use Illuminate\Foundation\Bus\Dispatchable; -use Illuminate\Support\Carbon; /*@not used*/ @@ -38,11 +37,9 @@ class SendCompanyRecurring public function __construct($company_id, $db) { - $this->company_id = $company_id; $this->db = $db; - } /** @@ -52,40 +49,36 @@ class SendCompanyRecurring */ public function handle() : void { - MultiDB::setDB($this->db); $recurring_invoices = Company::where('id', $this->company_id) ->where('is_disabled', 0) - ->whereHas('recurring_invoices', function ($query){ - $query->where('next_send_date', '<=', now()->toDateTimeString()) - ->whereNotNull('next_send_date') - ->whereNull('deleted_at') - ->where('is_deleted', false) - ->where('status_id', RecurringInvoice::STATUS_ACTIVE) - ->where('remaining_cycles', '!=', '0') - ->whereHas('client', function ($query) { - $query->where('is_deleted', 0) - ->where('deleted_at', null); - }); - }) - ->cursor()->each(function ($recurring_invoice){ + ->whereHas('recurring_invoices', function ($query) { + $query->where('next_send_date', '<=', now()->toDateTimeString()) + ->whereNotNull('next_send_date') + ->whereNull('deleted_at') + ->where('is_deleted', false) + ->where('status_id', RecurringInvoice::STATUS_ACTIVE) + ->where('remaining_cycles', '!=', '0') + ->whereHas('client', function ($query) { + $query->where('is_deleted', 0) + ->where('deleted_at', null); + }); + }) + ->cursor()->each(function ($recurring_invoice) { + nlog("Trying to send {$recurring_invoice->number}"); - nlog("Trying to send {$recurring_invoice->number}"); + if ($recurring_invoice->company->stop_on_unpaid_recurring) { + if ($recurring_invoice->invoices()->whereIn('status_id', [2, 3])->where('is_deleted', 0)->where('balance', '>', 0)->exists()) { + return; + } + } - if ($recurring_invoice->company->stop_on_unpaid_recurring) { - if ($recurring_invoice->invoices()->whereIn('status_id', [2, 3])->where('is_deleted', 0)->where('balance', '>', 0)->exists()) { - return; - } - } - - try { - (new SendRecurring($recurring_invoice, $recurring_invoice->company->db))->handle(); - } catch (\Exception $e) { - nlog("Unable to sending recurring invoice {$recurring_invoice->id} ".$e->getMessage()); - } - - }); - + try { + (new SendRecurring($recurring_invoice, $recurring_invoice->company->db))->handle(); + } catch (\Exception $e) { + nlog("Unable to sending recurring invoice {$recurring_invoice->id} ".$e->getMessage()); + } + }); } } diff --git a/app/Jobs/Cron/SubscriptionCron.php b/app/Jobs/Cron/SubscriptionCron.php index 186a05722c99..8fc2412bf630 100644 --- a/app/Jobs/Cron/SubscriptionCron.php +++ b/app/Jobs/Cron/SubscriptionCron.php @@ -15,7 +15,6 @@ use App\Libraries\MultiDB; use App\Models\Invoice; use App\Utils\Traits\SubscriptionHooker; use Illuminate\Foundation\Bus\Dispatchable; -use Illuminate\Support\Carbon; class SubscriptionCron { @@ -41,11 +40,10 @@ class SubscriptionCron nlog('Subscription Cron'); if (! config('ninja.db.multi_db_enabled')) { - $invoices = Invoice::where('is_deleted', 0) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('balance', '>', 0) - ->where('is_proforma',0) + ->where('is_proforma', 0) ->whereDate('due_date', '<=', now()->addDay()->startOfDay()) ->whereNull('deleted_at') ->whereNotNull('subscription_id') @@ -65,8 +63,6 @@ class SubscriptionCron //This will send the notification daily. //We'll need to handle this by performing some action on the invoice to either archive it or delete it? }); - - } else { //multiDB environment, need to foreach (MultiDB::$dbs as $db) { @@ -75,7 +71,7 @@ class SubscriptionCron $invoices = Invoice::where('is_deleted', 0) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('balance', '>', 0) - ->where('is_proforma',0) + ->where('is_proforma', 0) ->whereDate('due_date', '<=', now()->addDay()->startOfDay()) ->whereNull('deleted_at') ->whereNotNull('subscription_id') @@ -95,10 +91,7 @@ class SubscriptionCron //This will send the notification daily. //We'll need to handle this by performing some action on the invoice to either archive it or delete it? }); - - } } } - } diff --git a/app/Jobs/Document/ZipDocuments.php b/app/Jobs/Document/ZipDocuments.php index 4ee54338890f..c713e778e599 100644 --- a/app/Jobs/Document/ZipDocuments.php +++ b/app/Jobs/Document/ZipDocuments.php @@ -11,18 +11,15 @@ namespace App\Jobs\Document; -use App\Jobs\Entity\CreateEntityPdf; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\Util\UnlinkFile; use App\Libraries\MultiDB; use App\Mail\DownloadDocuments; -use App\Mail\DownloadInvoices; use App\Models\Company; use App\Models\Document; use App\Models\User; use App\Utils\Ninja; -use App\Utils\TempFile; use App\Utils\Traits\MakesDates; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -31,9 +28,7 @@ use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Storage; -use ZipArchive; class ZipDocuments implements ShouldQueue { @@ -128,7 +123,7 @@ class ZipDocuments implements ShouldQueue $entity = ctrans('texts.document'); - if(isset($document->documentable)){ + if (isset($document->documentable)) { $entity = $document->documentable->translate_entity(); } diff --git a/app/Jobs/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php index 6c12b1c1ec8b..b59e3529fdb4 100644 --- a/app/Jobs/Entity/CreateEntityPdf.php +++ b/app/Jobs/Entity/CreateEntityPdf.php @@ -34,7 +34,6 @@ use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesInvoiceHtml; use App\Utils\Traits\NumberFormatter; use App\Utils\Traits\Pdf\PageNumbering; -use App\Utils\Traits\Pdf\PDF; use App\Utils\Traits\Pdf\PdfMaker; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -42,9 +41,7 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\Storage; -use setasign\Fpdi\PdfParser\StreamReader; class CreateEntityPdf implements ShouldQueue { diff --git a/app/Jobs/Entity/CreateRawPdf.php b/app/Jobs/Entity/CreateRawPdf.php index 178ab18f97ad..ebd2704c894f 100644 --- a/app/Jobs/Entity/CreateRawPdf.php +++ b/app/Jobs/Entity/CreateRawPdf.php @@ -13,7 +13,6 @@ namespace App\Jobs\Entity; use App\Exceptions\FilePermissionsFailure; use App\Libraries\MultiDB; -use App\Models\Account; use App\Models\Credit; use App\Models\CreditInvitation; use App\Models\Design; @@ -41,8 +40,6 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; -use Illuminate\Support\Facades\Storage; class CreateRawPdf implements ShouldQueue { @@ -90,7 +87,6 @@ class CreateRawPdf implements ShouldQueue public function handle() { - /* Forget the singleton*/ App::forgetInstance('translator'); diff --git a/app/Jobs/Entity/EmailEntity.php b/app/Jobs/Entity/EmailEntity.php index dda2c0711fab..cdf5235dbd6f 100644 --- a/app/Jobs/Entity/EmailEntity.php +++ b/app/Jobs/Entity/EmailEntity.php @@ -83,7 +83,6 @@ class EmailEntity implements ShouldQueue $this->html_engine = new HtmlEngine($invitation); $this->template_data = $template_data; - } /** diff --git a/app/Jobs/Import/CSVIngest.php b/app/Jobs/Import/CSVIngest.php index 879470d1bf75..cdeaab860c28 100644 --- a/app/Jobs/Import/CSVIngest.php +++ b/app/Jobs/Import/CSVIngest.php @@ -81,7 +81,6 @@ class CSVIngest implements ShouldQueue $engine->finalizeImport(); $this->checkContacts(); - } private function checkContacts() @@ -106,23 +105,17 @@ class CSVIngest implements ShouldQueue $new_contact->save(); } - Client::with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($client){ - - $contact = $client->contacts()->first(); - $contact->is_primary = true; - $contact->save(); - + Client::with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($client) { + $contact = $client->contacts()->first(); + $contact->is_primary = true; + $contact->save(); }); - Vendor::with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($vendor){ - - $contact = $vendor->contacts()->first(); - $contact->is_primary = true; - $contact->save(); - + Vendor::with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($vendor) { + $contact = $vendor->contacts()->first(); + $contact->is_primary = true; + $contact->save(); }); - - } private function bootEngine() diff --git a/app/Jobs/Inventory/AdjustProductInventory.php b/app/Jobs/Inventory/AdjustProductInventory.php index 95ba7cc9150c..f4772ca9010f 100644 --- a/app/Jobs/Inventory/AdjustProductInventory.php +++ b/app/Jobs/Inventory/AdjustProductInventory.php @@ -20,7 +20,6 @@ use App\Models\Company; use App\Models\Invoice; use App\Models\Product; use App\Utils\Traits\Notifications\UserNotifies; -use App\Utils\Traits\NumberFormatter; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; @@ -64,11 +63,9 @@ class AdjustProductInventory implements ShouldQueue public function handleDeletedInvoice() { + MultiDB::setDb($this->company->db); - MultiDB::setDb($this->company->db); - - foreach ($this->invoice->line_items as $item) { - + foreach ($this->invoice->line_items as $item) { $p = Product::where('product_key', $item->product_key)->where('company_id', $this->company->id)->first(); if (! $p) { @@ -79,15 +76,13 @@ class AdjustProductInventory implements ShouldQueue $p->saveQuietly(); } - } public function handleRestoredInvoice() { + MultiDB::setDb($this->company->db); - MultiDB::setDb($this->company->db); - - foreach ($this->invoice->line_items as $item) { + foreach ($this->invoice->line_items as $item) { $p = Product::where('product_key', $item->product_key)->where('company_id', $this->company->id)->first(); if (! $p) { @@ -97,7 +92,6 @@ class AdjustProductInventory implements ShouldQueue $p->in_stock_quantity -= $item->quantity; $p->saveQuietly(); } - } public function middleware() @@ -148,17 +142,11 @@ class AdjustProductInventory implements ShouldQueue $nmo->company = $this->company; $nmo->settings = $this->company->settings; - $this->company->company_users->each(function ($cu) use($product, $nmo){ - - if($this->checkNotificationExists($cu, $product, ['inventory_all', 'inventory_user'])) - { - + $this->company->company_users->each(function ($cu) use ($product, $nmo) { + if ($this->checkNotificationExists($cu, $product, ['inventory_all', 'inventory_user'])) { $nmo->to_user = $cu->user; NinjaMailerJob::dispatch($nmo); - } - }); - } } diff --git a/app/Jobs/Invoice/BulkInvoiceJob.php b/app/Jobs/Invoice/BulkInvoiceJob.php index 787663c63519..dfbdb18a7905 100644 --- a/app/Jobs/Invoice/BulkInvoiceJob.php +++ b/app/Jobs/Invoice/BulkInvoiceJob.php @@ -13,20 +13,6 @@ namespace App\Jobs\Invoice; use App\Jobs\Entity\EmailEntity; use App\Models\Invoice; -use CleverIt\UBL\Invoice\Address; -use CleverIt\UBL\Invoice\Contact; -use CleverIt\UBL\Invoice\Country; -use CleverIt\UBL\Invoice\Generator; -use CleverIt\UBL\Invoice\Invoice as UBLInvoice; -use CleverIt\UBL\Invoice\InvoiceLine; -use CleverIt\UBL\Invoice\Item; -use CleverIt\UBL\Invoice\LegalMonetaryTotal; -use CleverIt\UBL\Invoice\Party; -use CleverIt\UBL\Invoice\TaxCategory; -use CleverIt\UBL\Invoice\TaxScheme; -use CleverIt\UBL\Invoice\TaxSubTotal; -use CleverIt\UBL\Invoice\TaxTotal; -use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; diff --git a/app/Jobs/Invoice/CheckGatewayFee.php b/app/Jobs/Invoice/CheckGatewayFee.php index 9fc58042e12a..e888f38489aa 100644 --- a/app/Jobs/Invoice/CheckGatewayFee.php +++ b/app/Jobs/Invoice/CheckGatewayFee.php @@ -29,7 +29,9 @@ class CheckGatewayFee implements ShouldQueue * @param $invoice_id * @param string $db */ - public function __construct(public int $invoice_id, public string $db){} + public function __construct(public int $invoice_id, public string $db) + { + } /** * Execute the job. @@ -42,13 +44,12 @@ class CheckGatewayFee implements ShouldQueue $i = Invoice::withTrashed()->find($this->invoice_id); - if(!$i) + if (!$i) { return; - - if($i->status_id == Invoice::STATUS_SENT) - { - $i->service()->removeUnpaidGatewayFees(); } + if ($i->status_id == Invoice::STATUS_SENT) { + $i->service()->removeUnpaidGatewayFees(); + } } } diff --git a/app/Jobs/Invoice/InvoiceCheckLateWebhook.php b/app/Jobs/Invoice/InvoiceCheckLateWebhook.php index bb045cbd2544..0c99407d11b2 100644 --- a/app/Jobs/Invoice/InvoiceCheckLateWebhook.php +++ b/app/Jobs/Invoice/InvoiceCheckLateWebhook.php @@ -29,7 +29,9 @@ class InvoiceCheckLateWebhook implements ShouldQueue /** * Create a new job instance. */ - public function __construct() {} + public function __construct() + { + } /** * Execute the job. @@ -40,8 +42,7 @@ class InvoiceCheckLateWebhook implements ShouldQueue { nlog("sending overdue webhooks for invoices"); - if (! config('ninja.db.multi_db_enabled')){ - + if (! config('ninja.db.multi_db_enabled')) { $company_ids = Webhook::where('event_id', Webhook::EVENT_LATE_INVOICE) ->where('is_deleted', 0) ->pluck('company_id'); @@ -54,26 +55,19 @@ class InvoiceCheckLateWebhook implements ShouldQueue ->where('balance', '>', 0) ->whereIn('company_id', $company_ids) ->whereHas('client', function ($query) { - $query->where('is_deleted', 0) - ->where('deleted_at', null); - }) - ->whereHas('company', function ($query){ + $query->where('is_deleted', 0) + ->where('deleted_at', null); + }) + ->whereHas('company', function ($query) { $query->where('is_disabled', 0); }) ->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()]) ->cursor() - ->each(function ($invoice){ - - WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client')->delay(now()->addSeconds(2)); - + ->each(function ($invoice) { + WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client')->delay(now()->addSeconds(2)); }); - - } - else { - - foreach (MultiDB::$dbs as $db) - { - + } else { + foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); $company_ids = Webhook::where('event_id', Webhook::EVENT_LATE_INVOICE) @@ -88,24 +82,18 @@ class InvoiceCheckLateWebhook implements ShouldQueue ->where('balance', '>', 0) ->whereIn('company_id', $company_ids) ->whereHas('client', function ($query) { - $query->where('is_deleted', 0) - ->where('deleted_at', null); - }) - ->whereHas('company', function ($query){ + $query->where('is_deleted', 0) + ->where('deleted_at', null); + }) + ->whereHas('company', function ($query) { $query->where('is_disabled', 0); }) ->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()]) ->cursor() - ->each(function ($invoice){ - - WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client')->delay(now()->addSeconds(2)); - + ->each(function ($invoice) { + WebhookHandler::dispatch(Webhook::EVENT_LATE_INVOICE, $invoice, $invoice->company, 'client')->delay(now()->addSeconds(2)); }); - - } } - } - } diff --git a/app/Jobs/Invoice/ZipInvoices.php b/app/Jobs/Invoice/ZipInvoices.php index 51d5989954f1..9a0d4752c3a8 100644 --- a/app/Jobs/Invoice/ZipInvoices.php +++ b/app/Jobs/Invoice/ZipInvoices.php @@ -19,15 +19,12 @@ use App\Libraries\MultiDB; use App\Mail\DownloadInvoices; use App\Models\Company; use App\Models\User; -use App\Utils\TempFile; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Storage; -use ZipArchive; class ZipInvoices implements ShouldQueue { diff --git a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php index b63fc65623db..731ec0872a77 100644 --- a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php +++ b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php @@ -52,11 +52,7 @@ 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) { - - if ($company_ledger->balance == 0) - { - - + if ($company_ledger->balance == 0) { $last_record = CompanyLedger::where('client_id', $company_ledger->client_id) ->where('company_id', $company_ledger->company_id) ->where('balance', '!=', 0) @@ -69,13 +65,10 @@ class ClientLedgerBalanceUpdate implements ShouldQueue ->orderBy('id', 'DESC') ->first(); } - } - $company_ledger->balance = $last_record->balance + $company_ledger->adjustment; - $company_ledger->save(); - + $company_ledger->balance = $last_record->balance + $company_ledger->adjustment; + $company_ledger->save(); }); - } } diff --git a/app/Jobs/Ledger/LedgerBalanceUpdate.php b/app/Jobs/Ledger/LedgerBalanceUpdate.php index 5fc6ffabefdf..72a6a274ce7b 100644 --- a/app/Jobs/Ledger/LedgerBalanceUpdate.php +++ b/app/Jobs/Ledger/LedgerBalanceUpdate.php @@ -12,7 +12,6 @@ namespace App\Jobs\Ledger; use App\Libraries\MultiDB; -use App\Models\Company; use App\Models\CompanyLedger; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php index ecaf942e9e37..48844a200b28 100644 --- a/app/Jobs/Mail/NinjaMailerJob.php +++ b/app/Jobs/Mail/NinjaMailerJob.php @@ -15,7 +15,6 @@ use App\DataMapper\Analytics\EmailFailure; use App\DataMapper\Analytics\EmailSuccess; use App\Events\Invoice\InvoiceWasEmailedAndFailed; use App\Events\Payment\PaymentWasEmailedAndFailed; -use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\Util\SystemLogger; use App\Libraries\Google\Google; use App\Libraries\MultiDB; @@ -34,9 +33,9 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Mail; use Turbo124\Beacon\Facades\LightLogs; -use Illuminate\Support\Facades\Cache; /*Multi Mailer implemented*/ @@ -66,11 +65,9 @@ class NinjaMailerJob implements ShouldQueue public function __construct(NinjaMailerObject $nmo, bool $override = false) { - $this->nmo = $nmo; $this->override = $override; - } public function backoff() @@ -87,24 +84,23 @@ class NinjaMailerJob implements ShouldQueue $this->company = Company::where('company_key', $this->nmo->company->company_key)->first(); /* If any pre conditions fail, we return early here */ - if(!$this->company || $this->preFlightChecksFail()) + if (!$this->company || $this->preFlightChecksFail()) { return; + } /* Set the email driver */ $this->setMailDriver(); /* Run time we set Reply To Email*/ if (strlen($this->nmo->settings->reply_to_email) > 1) { - - if(property_exists($this->nmo->settings, 'reply_to_name')) + if (property_exists($this->nmo->settings, 'reply_to_name')) { $reply_to_name = strlen($this->nmo->settings->reply_to_name) > 3 ? $this->nmo->settings->reply_to_name : $this->nmo->settings->reply_to_email; - else + } else { $reply_to_name = $this->nmo->settings->reply_to_email; + } $this->nmo->mailable->replyTo($this->nmo->settings->reply_to_email, $reply_to_name); - - } - else { + } else { $this->nmo->mailable->replyTo($this->company->owner()->email, $this->company->owner()->present()->name()); } @@ -112,15 +108,12 @@ class NinjaMailerJob implements ShouldQueue $this->nmo->mailable->tag($this->company->company_key); /* If we have an invitation present, we pass the invitation key into the email headers*/ - if($this->nmo->invitation) - { - + if ($this->nmo->invitation) { $this->nmo ->mailable ->withSymfonyMessage(function ($message) { - $message->getHeaders()->addTextHeader('x-invitation', $this->nmo->invitation->key); + $message->getHeaders()->addTextHeader('x-invitation', $this->nmo->invitation->key); }); - } //send email @@ -130,11 +123,11 @@ class NinjaMailerJob implements ShouldQueue $mailer = Mail::mailer($this->mailer); - if($this->client_postmark_secret){ + if ($this->client_postmark_secret) { $mailer->postmark_config($this->client_postmark_secret); } - if($this->client_mailgun_secret){ + if ($this->client_mailgun_secret) { $mailer->mailgun_config($this->client_mailgun_secret, $this->client_mailgun_domain); } @@ -150,24 +143,19 @@ class NinjaMailerJob implements ShouldQueue $this->nmo = null; $this->company = null; - - } - catch(\Symfony\Component\Mime\Exception\RfcComplianceException $e) { - nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); - $this->fail(); - $this->cleanUpMailers(); - $this->logMailError($e->getMessage(), $this->company->clients()->first()); - return; - } - catch(\Symfony\Component\Mime\Exception\LogicException $e){ - nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); - $this->fail(); - $this->cleanUpMailers(); - $this->logMailError($e->getMessage(), $this->company->clients()->first()); - return; - } - catch (\Exception | \Google\Service\Exception $e) { - + } catch(\Symfony\Component\Mime\Exception\RfcComplianceException $e) { + nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); + $this->fail(); + $this->cleanUpMailers(); + $this->logMailError($e->getMessage(), $this->company->clients()->first()); + return; + } catch(\Symfony\Component\Mime\Exception\LogicException $e) { + nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); + $this->fail(); + $this->cleanUpMailers(); + $this->logMailError($e->getMessage(), $this->company->clients()->first()); + return; + } catch (\Exception | \Google\Service\Exception $e) { nlog("Mailer failed with {$e->getMessage()}"); $message = $e->getMessage(); @@ -176,9 +164,7 @@ class NinjaMailerJob implements ShouldQueue * this merges a text string with a json object * need to harvest the ->Message property using the following */ - if(stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) - { - + if (stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) { $message = "Either Attachment too large, or recipient has been suppressed."; $this->fail(); @@ -186,36 +172,32 @@ class NinjaMailerJob implements ShouldQueue $this->cleanUpMailers(); return; - } //only report once, not on all tries - if($this->attempts() == $this->tries) - { - + if ($this->attempts() == $this->tries) { /* If the is an entity attached to the message send a failure mailer */ - if($this->nmo->entity) + if ($this->nmo->entity) { $this->entityEmailFailed($message); + } /* Don't send postmark failures to Sentry */ - if(Ninja::isHosted() && (!$e instanceof ClientException)) + if (Ninja::isHosted() && (!$e instanceof ClientException)) { app('sentry')->captureException($e); - + } } /* Releasing immediately does not add in the backoff */ $this->release($this->backoff()[$this->attempts()-1]); - } - /*Clean up mailers*/ + /*Clean up mailers*/ $this->cleanUpMailers(); - } /** * Entity notification when an email fails to send - * + * * @param string $message * @return void */ @@ -235,9 +217,9 @@ class NinjaMailerJob implements ShouldQueue break; } - if ($this->nmo->to_user instanceof ClientContact) + if ($this->nmo->to_user instanceof ClientContact) { $this->logMailError($message, $this->nmo->to_user->client); - + } } /** @@ -275,9 +257,9 @@ class NinjaMailerJob implements ShouldQueue break; } - if(Ninja::isSelfHost()) + if (Ninja::isSelfHost()) { $this->setSelfHostMultiMailer(); - + } } /** @@ -286,10 +268,7 @@ class NinjaMailerJob implements ShouldQueue */ private function setSelfHostMultiMailer(): void { - - if (env($this->company->id . '_MAIL_HOST')) - { - + if (env($this->company->id . '_MAIL_HOST')) { config([ 'mail.mailers.smtp' => [ 'transport' => 'smtp', @@ -300,20 +279,17 @@ class NinjaMailerJob implements ShouldQueue ], ]); - if(env($this->company->id . '_MAIL_FROM_ADDRESS')) - { - $this->nmo - ->mailable - ->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME'))); - } - + if (env($this->company->id . '_MAIL_FROM_ADDRESS')) { + $this->nmo + ->mailable + ->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME'))); + } } - } /** * Ensure we discard any data that is not required - * + * * @return void */ private function cleanUpMailers(): void @@ -324,21 +300,20 @@ class NinjaMailerJob implements ShouldQueue $this->client_mailgun_domain = false; - //always dump the drivers to prevent reuse + //always dump the drivers to prevent reuse app('mail.manager')->forgetMailers(); } - /** + /** * Check to ensure no cross account * emails can be sent. - * + * * @param User $user */ private function checkValidSendingUser($user) { /* Always ensure the user is set on the correct account */ - if($user->account_id != $this->company->account_id){ - + if ($user->account_id != $this->company->account_id) { $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); } @@ -348,17 +323,18 @@ class NinjaMailerJob implements ShouldQueue * Resolves the sending user * when configuring the Mailer * on behalf of the client - * + * * @return User $user */ private function resolveSendingUser(): ?User { $sending_user = $this->nmo->settings->gmail_sending_user_id; - if($sending_user == "0") + if ($sending_user == "0") { $user = $this->company->owner(); - else + } else { $user = User::find($this->decodePrimaryKey($sending_user)); + } return $user; } @@ -369,11 +345,10 @@ class NinjaMailerJob implements ShouldQueue */ private function setMailgunMailer() { - if(strlen($this->nmo->settings->mailgun_secret) > 2 && strlen($this->nmo->settings->mailgun_domain) > 2){ + if (strlen($this->nmo->settings->mailgun_secret) > 2 && strlen($this->nmo->settings->mailgun_domain) > 2) { $this->client_mailgun_secret = $this->nmo->settings->mailgun_secret; $this->client_mailgun_domain = $this->nmo->settings->mailgun_domain; - } - else{ + } else { $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); } @@ -383,9 +358,9 @@ class NinjaMailerJob implements ShouldQueue $sending_email = (isset($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; $sending_user = (isset($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); - $this->nmo - ->mailable - ->from($sending_email, $sending_user); + $this->nmo + ->mailable + ->from($sending_email, $sending_user); } /** @@ -394,10 +369,9 @@ class NinjaMailerJob implements ShouldQueue */ private function setPostmarkMailer() { - if(strlen($this->nmo->settings->postmark_secret) > 2){ + if (strlen($this->nmo->settings->postmark_secret) > 2) { $this->client_postmark_secret = $this->nmo->settings->postmark_secret; - } - else{ + } else { $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); } @@ -407,9 +381,9 @@ class NinjaMailerJob implements ShouldQueue $sending_email = (isset($this->nmo->settings->custom_sending_email) && stripos($this->nmo->settings->custom_sending_email, "@")) ? $this->nmo->settings->custom_sending_email : $user->email; $sending_user = (isset($this->nmo->settings->email_from_name) && strlen($this->nmo->settings->email_from_name) > 2) ? $this->nmo->settings->email_from_name : $user->name(); - $this->nmo - ->mailable - ->from($sending_email, $sending_user); + $this->nmo + ->mailable + ->from($sending_email, $sending_user); } /** @@ -426,26 +400,20 @@ class NinjaMailerJob implements ShouldQueue $token = $this->refreshOfficeToken($user); - if($token) - { + if ($token) { $user->oauth_user_token = $token; $user->save(); - - } - else { - + } else { $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); - } $this->nmo ->mailable ->from($user->email, $user->name()) - ->withSymfonyMessage(function ($message) use($token) { - $message->getHeaders()->addTextHeader('gmailtoken', $token); + ->withSymfonyMessage(function ($message) use ($token) { + $message->getHeaders()->addTextHeader('gmailtoken', $token); }); - } /** @@ -454,7 +422,6 @@ class NinjaMailerJob implements ShouldQueue */ private function setGmailMailer() { - $user = $this->resolveSendingUser(); $this->checkValidSendingUser($user); @@ -463,17 +430,14 @@ class NinjaMailerJob implements ShouldQueue $google = (new Google())->init(); - try{ - + try { if ($google->getClient()->isAccessTokenExpired()) { $google->refreshToken($user); $user = $user->fresh(); } $google->getClient()->setAccessToken(json_encode($user->oauth_user_token)); - - } - catch(\Exception $e) { + } catch(\Exception $e) { $this->logMailError('Gmail Token Invalid', $this->company->clients()->first()); $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -483,7 +447,7 @@ class NinjaMailerJob implements ShouldQueue * If the user doesn't have a valid token, notify them */ - if(!$user->oauth_user_token) { + if (!$user->oauth_user_token) { $this->company->account->gmailCredentialNotification(); $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -497,7 +461,7 @@ class NinjaMailerJob implements ShouldQueue $token = $user->oauth_user_token->access_token; - if(!$token) { + if (!$token) { $this->company->account->gmailCredentialNotification(); $this->nmo->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -506,45 +470,47 @@ class NinjaMailerJob implements ShouldQueue $this->nmo ->mailable ->from($user->email, $user->name()) - ->withSymfonyMessage(function ($message) use($token) { - $message->getHeaders()->addTextHeader('gmailtoken', $token); + ->withSymfonyMessage(function ($message) use ($token) { + $message->getHeaders()->addTextHeader('gmailtoken', $token); }); - } /** - * On the hosted platform we scan all outbound email for + * On the hosted platform we scan all outbound email for * spam. This sequence processes the filters we use on all * emails. - * + * * @return bool */ private function preFlightChecksFail(): bool { - /* If we are migrating data we don't want to fire any emails */ - if($this->company->is_disabled && !$this->override) + if ($this->company->is_disabled && !$this->override) { return true; + } /* To handle spam users we drop all emails from flagged accounts */ - if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) + if (Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) { return true; + } /* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */ - if(Ninja::isHosted() && $this->nmo->to_user && strpos($this->nmo->to_user->email, '@example.com') !== false) + if (Ninja::isHosted() && $this->nmo->to_user && strpos($this->nmo->to_user->email, '@example.com') !== false) { return true; + } /* GMail users are uncapped */ - if(Ninja::isHosted() && ($this->nmo->settings->email_sending_method == 'gmail' || $this->nmo->settings->email_sending_method == 'office365')) + if (Ninja::isHosted() && ($this->nmo->settings->email_sending_method == 'gmail' || $this->nmo->settings->email_sending_method == 'office365')) { return false; + } /* On the hosted platform, if the user is over the email quotas, we do not send the email. */ - if(Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded()) + if (Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded()) { return true; + } /* If the account is verified, we allow emails to flow */ - if(Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) { - + if (Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) { //11-01-2022 /* Continue to analyse verified accounts in case they later start sending poor quality emails*/ @@ -555,35 +521,36 @@ class NinjaMailerJob implements ShouldQueue } /* Ensure the user has a valid email address */ - if(!str_contains($this->nmo->to_user->email, "@")) + if (!str_contains($this->nmo->to_user->email, "@")) { return true; + } /* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */ - if(Ninja::isHosted() && $this->company->account && !$this->company->account->account_sms_verified){ - - if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) + if (Ninja::isHosted() && $this->company->account && !$this->company->account->account_sms_verified) { + if (class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) { return (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run(); + } return true; } /* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */ - if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) + if (class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class)) { return (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run(); + } return false; } /** * Logs any errors to the SystemLog - * + * * @param string $errors * @param App\Models\User | App\Models\Client $recipient_object * @return void */ private function logMailError($errors, $recipient_object) :void { - (new SystemLogger( $errors, SystemLog::CATEGORY_MAIL, @@ -601,12 +568,11 @@ class NinjaMailerJob implements ShouldQueue ->send(); $job_failure = null; - } /** * Attempts to refresh the Microsoft refreshToken - * + * * @param App\Models\User * @return string | boool */ @@ -614,10 +580,9 @@ class NinjaMailerJob implements ShouldQueue { $expiry = $user->oauth_user_token_expiry ?: now()->subDay(); - if($expiry->lt(now())) - { - $guzzle = new \GuzzleHttp\Client(); - $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'; + if ($expiry->lt(now())) { + $guzzle = new \GuzzleHttp\Client(); + $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'; $token = json_decode($guzzle->post($url, [ 'form_params' => [ @@ -629,8 +594,7 @@ class NinjaMailerJob implements ShouldQueue ], ])->getBody()->getContents()); - if($token){ - + if ($token) { $user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token; $user->oauth_user_token = $token->access_token; $user->oauth_user_token_expiry = now()->addSeconds($token->expires_in); @@ -643,14 +607,10 @@ class NinjaMailerJob implements ShouldQueue } return $user->oauth_user_token; - } public function failed($exception = null) { - config(['queue.failed.driver' => null]); - } - -} \ No newline at end of file +} diff --git a/app/Jobs/Mail/PaymentFailedMailer.php b/app/Jobs/Mail/PaymentFailedMailer.php index d79f4bb64388..c5fa3c14dbcc 100644 --- a/app/Jobs/Mail/PaymentFailedMailer.php +++ b/app/Jobs/Mail/PaymentFailedMailer.php @@ -11,18 +11,13 @@ namespace App\Jobs\Mail; -use App\Jobs\Mail\NinjaMailer; -use App\Jobs\Mail\NinjaMailerJob; -use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; use App\Mail\Admin\ClientPaymentFailureObject; -use App\Mail\Admin\EntityNotificationMailer; use App\Mail\Admin\PaymentFailureObject; use App\Models\Client; use App\Models\Company; use App\Models\Invoice; use App\Models\PaymentHash; -use App\Models\User; use App\Utils\Traits\MakesHash; use App\Utils\Traits\Notifications\UserNotifies; use Illuminate\Bus\Queueable; @@ -70,7 +65,7 @@ class PaymentFailedMailer implements ShouldQueue */ public function handle() { - if(!is_string($this->error)){ + if (!is_string($this->error)) { $this->error = "Payment failed, no reason given."; } diff --git a/app/Jobs/Mail/PaymentFailureMailer.php b/app/Jobs/Mail/PaymentFailureMailer.php index 75c546609169..336c8009c101 100644 --- a/app/Jobs/Mail/PaymentFailureMailer.php +++ b/app/Jobs/Mail/PaymentFailureMailer.php @@ -11,11 +11,7 @@ namespace App\Jobs\Mail; -use App\Jobs\Mail\NinjaMailer; -use App\Jobs\Mail\NinjaMailerJob; -use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; -use App\Mail\Admin\EntityNotificationMailer; use App\Mail\Admin\PaymentFailureObject; use App\Models\User; use App\Utils\Traits\Notifications\UserNotifies; @@ -72,13 +68,11 @@ class PaymentFailureMailer implements ShouldQueue */ public function handle() { - //Set DB MultiDB::setDb($this->company->db); //iterate through company_users $this->company->company_users->each(function ($company_user) { - //determine if this user has the right permissions $methods = $this->findCompanyUserNotificationType($company_user, ['payment_failure_all', 'payment_failure', 'payment_failure_user', 'all_notifications']); diff --git a/app/Jobs/Ninja/AdjustEmailQuota.php b/app/Jobs/Ninja/AdjustEmailQuota.php index 909ed72843f7..7e0a1cddab35 100644 --- a/app/Jobs/Ninja/AdjustEmailQuota.php +++ b/app/Jobs/Ninja/AdjustEmailQuota.php @@ -63,19 +63,16 @@ class AdjustEmailQuota implements ShouldQueue $email_count = Cache::get($account->key); - if($email_count > 0){ - - try{ + if ($email_count > 0) { + try { LightLogs::create(new EmailCount($email_count, $account->key))->send(); - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog($e->getMessage()); } } Cache::forget($account->key); Cache::forget("throttle_notified:{$account->key}"); - }); } } diff --git a/app/Jobs/Ninja/BankTransactionSync.php b/app/Jobs/Ninja/BankTransactionSync.php index 370fef9e7b86..ae7dc4d7b33a 100644 --- a/app/Jobs/Ninja/BankTransactionSync.php +++ b/app/Jobs/Ninja/BankTransactionSync.php @@ -20,7 +20,6 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Cache; class BankTransactionSync implements ShouldQueue { @@ -44,31 +43,21 @@ class BankTransactionSync implements ShouldQueue */ public function handle() { - //multiDB environment, need to - foreach (MultiDB::$dbs as $db) - { + foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); nlog("syncing transactions"); - $a = Account::with('bank_integrations')->whereNotNull('bank_integration_account_id')->cursor()->each(function ($account){ + $a = Account::with('bank_integrations')->whereNotNull('bank_integration_account_id')->cursor()->each(function ($account) { + // $queue = Ninja::isHosted() ? 'bank' : 'default'; - // $queue = Ninja::isHosted() ? 'bank' : 'default'; - - if($account->isPaid() && $account->plan == 'enterprise') - { - - $account->bank_integrations()->where('auto_sync', true)->cursor()->each(function ($bank_integration) use ($account){ - - (new ProcessBankTransactions($account->bank_integration_account_id, $bank_integration))->handle(); - - }); - - } - - }); + if ($account->isPaid() && $account->plan == 'enterprise') { + $account->bank_integrations()->where('auto_sync', true)->cursor()->each(function ($bank_integration) use ($account) { + (new ProcessBankTransactions($account->bank_integration_account_id, $bank_integration))->handle(); + }); + } + }); } } - } diff --git a/app/Jobs/Ninja/CheckCompanyData.php b/app/Jobs/Ninja/CheckCompanyData.php index 2478f611cb90..bd4d95504e96 100644 --- a/app/Jobs/Ninja/CheckCompanyData.php +++ b/app/Jobs/Ninja/CheckCompanyData.php @@ -25,7 +25,6 @@ use Illuminate\Queue\Middleware\RateLimited; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; -use Turbo124\Beacon\Jobs\Database\MySQL\DbStatus; class CheckCompanyData implements ShouldQueue { @@ -124,8 +123,8 @@ class CheckCompanyData implements ShouldQueue $this->company->clients->where('is_deleted', 0)->each(function ($client) use ($wrong_balances) { $client->invoices->where('is_deleted', false)->whereIn('status_id', '!=', Invoice::STATUS_DRAFT)->each(function ($invoice) use ($wrong_balances, $client) { - $total_amount = $invoice->payments->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.amount'); - $total_refund = $invoice->payments->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.refunded'); + $total_amount = $invoice->payments->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.amount'); + $total_refund = $invoice->payments->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED])->sum('pivot.refunded'); $total_credit = $invoice->credits->sum('amount'); $total_paid = $total_amount - $total_refund; @@ -153,8 +152,8 @@ class CheckCompanyData implements ShouldQueue $total_invoice_payments = 0; foreach ($client->invoices->where('is_deleted', false)->where('status_id', '>', 1) as $invoice) { - $total_amount = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->sum('pivot.amount'); - $total_refund = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->sum('pivot.refunded'); + $total_amount = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->sum('pivot.amount'); + $total_refund = $invoice->payments->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->sum('pivot.refunded'); $total_invoice_payments += ($total_amount - $total_refund); } diff --git a/app/Jobs/Ninja/CompanySizeCheck.php b/app/Jobs/Ninja/CompanySizeCheck.php index 89c07bdcdc11..2eeb238a2ea6 100644 --- a/app/Jobs/Ninja/CompanySizeCheck.php +++ b/app/Jobs/Ninja/CompanySizeCheck.php @@ -43,7 +43,6 @@ class CompanySizeCheck implements ShouldQueue public function handle() { if (! config('ninja.db.multi_db_enabled')) { - Company::where('is_large', false)->withCount(['invoices', 'clients', 'products', 'quotes'])->cursor()->each(function ($company) { if ($company->invoices_count > 500 || $company->products_count > 500 || $company->clients_count > 500) { nlog("Marking company {$company->id} as large"); @@ -56,29 +55,21 @@ class CompanySizeCheck implements ShouldQueue Client::where('updated_at', '>', now()->subDay()) ->cursor() - ->each(function ($client){ - - $client->credit_balance = $client->service()->getCreditBalance(); - $client->save(); - + ->each(function ($client) { + $client->credit_balance = $client->service()->getCreditBalance(); + $client->save(); }); /* Ensures lower permissioned users return the correct dataset and refresh responses */ - Account::whereHas('companies', function ($query){ - $query->where('is_large',0); + Account::whereHas('companies', function ($query) { + $query->where('is_large', 0); + }) + ->whereHas('company_users', function ($query) { + $query->where('is_admin', 0); }) - ->whereHas('company_users', function ($query){ - - $query->where('is_admin', 0); - - }) - ->cursor()->each(function ($account){ - - $account->companies()->update(['is_large' => true]); - + ->cursor()->each(function ($account) { + $account->companies()->update(['is_large' => true]); }); - - } else { //multiDB environment, need to foreach (MultiDB::$dbs as $db) { @@ -98,31 +89,23 @@ class CompanySizeCheck implements ShouldQueue Client::where('updated_at', '>', now()->subDay()) ->cursor() - ->each(function ($client){ - - $client->credit_balance = $client->service()->getCreditBalance(); - $client->save(); - + ->each(function ($client) { + $client->credit_balance = $client->service()->getCreditBalance(); + $client->save(); }); Account::where('plan', 'enterprise') ->whereDate('plan_expires', '>', now()) - ->whereHas('companies', function ($query){ - $query->where('is_large',0); + ->whereHas('companies', function ($query) { + $query->where('is_large', 0); }) - ->whereHas('company_users', function ($query){ - - $query->where('is_admin', 0); - - }) - ->cursor()->each(function ($account){ - - $account->companies()->update(['is_large' => true]); - + ->whereHas('company_users', function ($query) { + $query->where('is_admin', 0); + }) + ->cursor()->each(function ($account) { + $account->companies()->update(['is_large' => true]); }); - } } } - } diff --git a/app/Jobs/Ninja/QueueSize.php b/app/Jobs/Ninja/QueueSize.php index c1282edb581a..96850337b988 100644 --- a/app/Jobs/Ninja/QueueSize.php +++ b/app/Jobs/Ninja/QueueSize.php @@ -19,7 +19,6 @@ use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Queue; use Turbo124\Beacon\Facades\LightLogs; -use Turbo124\Beacon\Jobs\Database\MySQL\DbStatus; class QueueSize implements ShouldQueue { diff --git a/app/Jobs/Ninja/SendReminders.php b/app/Jobs/Ninja/SendReminders.php index 7587ec6004f2..33a0cdc9f1b1 100644 --- a/app/Jobs/Ninja/SendReminders.php +++ b/app/Jobs/Ninja/SendReminders.php @@ -209,7 +209,6 @@ class SendReminders implements ShouldQueue $invoice = $this->calcLateFee($invoice, $template); $invoice->invitations->each(function ($invitation) use ($template, $invoice) { - //only send if enable_reminder setting is toggled to yes if ($this->checkSendSetting($invoice, $template) && $invoice->company->account->hasFeature(Account::FEATURE_EMAIL_TEMPLATES_REMINDERS)) { nlog('firing email'); diff --git a/app/Jobs/Ninja/SystemMaintenance.php b/app/Jobs/Ninja/SystemMaintenance.php index 2ace08884189..e036a291be62 100644 --- a/app/Jobs/Ninja/SystemMaintenance.php +++ b/app/Jobs/Ninja/SystemMaintenance.php @@ -15,14 +15,11 @@ use App\Models\Backup; use App\Models\Credit; use App\Models\Invoice; use App\Models\Quote; -use App\Utils\Ninja; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Queue; -use Illuminate\Support\Facades\Storage; class SystemMaintenance implements ShouldQueue { diff --git a/app/Jobs/Ninja/TaskScheduler.php b/app/Jobs/Ninja/TaskScheduler.php index 4ee399603b12..46a3fb27b04b 100644 --- a/app/Jobs/Ninja/TaskScheduler.php +++ b/app/Jobs/Ninja/TaskScheduler.php @@ -11,10 +11,8 @@ namespace App\Jobs\Ninja; -use App\Jobs\Report\SendToAdmin; use App\Libraries\MultiDB; use App\Models\Scheduler; -use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; @@ -44,9 +42,7 @@ class TaskScheduler implements ShouldQueue */ public function handle() { - if (! config('ninja.db.multi_db_enabled')) { - Scheduler::with('company') ->where('is_paused', false) ->where('is_deleted', false) @@ -82,12 +78,8 @@ class TaskScheduler implements ShouldQueue try { $scheduler->service()->runTask(); - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog($e->getMessage()); - } } - - } diff --git a/app/Jobs/Payment/EmailPayment.php b/app/Jobs/Payment/EmailPayment.php index c05f3172c64d..fab34abbc7b7 100644 --- a/app/Jobs/Payment/EmailPayment.php +++ b/app/Jobs/Payment/EmailPayment.php @@ -12,7 +12,6 @@ namespace App\Jobs\Payment; use App\Events\Payment\PaymentWasEmailed; -use App\Events\Payment\PaymentWasEmailedAndFailed; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; @@ -27,7 +26,6 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Mail; class EmailPayment implements ShouldQueue { diff --git a/app/Jobs/Payment/EmailRefundPayment.php b/app/Jobs/Payment/EmailRefundPayment.php index c386882936ae..a3ef64cdbb41 100644 --- a/app/Jobs/Payment/EmailRefundPayment.php +++ b/app/Jobs/Payment/EmailRefundPayment.php @@ -12,7 +12,6 @@ namespace App\Jobs\Payment; use App\Events\Payment\PaymentWasEmailed; -use App\Events\Payment\PaymentWasEmailedAndFailed; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; @@ -28,7 +27,6 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Mail; class EmailRefundPayment implements ShouldQueue { diff --git a/app/Jobs/Payment/PaymentNotification.php b/app/Jobs/Payment/PaymentNotification.php index cd0c92b00562..eabde8021278 100644 --- a/app/Jobs/Payment/PaymentNotification.php +++ b/app/Jobs/Payment/PaymentNotification.php @@ -48,7 +48,6 @@ class PaymentNotification implements ShouldQueue */ public function handle() { - //notification for the payment. // //could mean a email, sms, slack, push diff --git a/app/Jobs/PostMark/ProcessPostmarkWebhook.php b/app/Jobs/PostMark/ProcessPostmarkWebhook.php index 82ae0969828c..c2497a3b5677 100644 --- a/app/Jobs/PostMark/ProcessPostmarkWebhook.php +++ b/app/Jobs/PostMark/ProcessPostmarkWebhook.php @@ -13,15 +13,8 @@ namespace App\Jobs\PostMark; use App\DataMapper\Analytics\Mail\EmailBounce; use App\DataMapper\Analytics\Mail\EmailSpam; -use App\Events\Payment\PaymentWasEmailed; -use App\Events\Payment\PaymentWasEmailedAndFailed; -use App\Jobs\Mail\NinjaMailerJob; -use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\Util\SystemLogger; use App\Libraries\MultiDB; -use App\Mail\Engine\PaymentEmailEngine; -use App\Mail\TemplateEmail; -use App\Models\ClientContact; use App\Models\Company; use App\Models\CreditInvitation; use App\Models\InvoiceInvitation; @@ -38,7 +31,6 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Mail; use Turbo124\Beacon\Facades\LightLogs; class ProcessPostmarkWebhook implements ShouldQueue @@ -71,19 +63,19 @@ class ProcessPostmarkWebhook implements ShouldQueue */ public function handle() { - MultiDB::findAndSetDbByCompanyKey($this->request['Tag']); $this->invitation = $this->discoverInvitation($this->request['MessageID']); - if(!$this->invitation) + if (!$this->invitation) { return; + } - if(array_key_exists('Details', $this->request)) + if (array_key_exists('Details', $this->request)) { $this->invitation->email_error = $this->request['Details']; + } - switch ($this->request['RecordType']) - { + switch ($this->request['RecordType']) { case 'Delivery': return $this->processDelivery(); case 'Bounce': @@ -96,7 +88,6 @@ class ProcessPostmarkWebhook implements ShouldQueue # code... break; } - } // { @@ -134,22 +125,21 @@ class ProcessPostmarkWebhook implements ShouldQueue // "ReceivedAt": "2022-02-06T06:37:48Z", // "Tag": "welcome-email", // "Recipient": "john@example.com" -// } +// } private function processOpen() { - $this->invitation->opened_date = now(); $this->invitation->save(); - (new SystemLogger($this->request, - SystemLog::CATEGORY_MAIL, - SystemLog::EVENT_MAIL_OPENED, - SystemLog::TYPE_WEBHOOK_RESPONSE, + (new SystemLogger( + $this->request, + SystemLog::CATEGORY_MAIL, + SystemLog::EVENT_MAIL_OPENED, + SystemLog::TYPE_WEBHOOK_RESPONSE, $this->invitation->contact->client, $this->invitation->company ))->handle(); - } // { @@ -171,10 +161,11 @@ class ProcessPostmarkWebhook implements ShouldQueue $this->invitation->email_status = 'delivered'; $this->invitation->save(); - (new SystemLogger($this->request, - SystemLog::CATEGORY_MAIL, - SystemLog::EVENT_MAIL_DELIVERY, - SystemLog::TYPE_WEBHOOK_RESPONSE, + (new SystemLogger( + $this->request, + SystemLog::CATEGORY_MAIL, + SystemLog::EVENT_MAIL_DELIVERY, + SystemLog::TYPE_WEBHOOK_RESPONSE, $this->invitation->contact->client, $this->invitation->company ))->handle(); @@ -222,8 +213,7 @@ class ProcessPostmarkWebhook implements ShouldQueue (new SystemLogger($this->request, SystemLog::CATEGORY_MAIL, SystemLog::EVENT_MAIL_BOUNCED, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->invitation->contact->client, $this->invitation->company))->handle(); // if(config('ninja.notification.slack')) - // $this->invitation->company->notification(new EmailBounceNotification($this->invitation->company->account))->ninja(); - + // $this->invitation->company->notification(new EmailBounceNotification($this->invitation->company->account))->ninja(); } // { @@ -253,7 +243,6 @@ class ProcessPostmarkWebhook implements ShouldQueue // } private function processSpamComplaint() { - $this->invitation->email_status = 'spam'; $this->invitation->save(); @@ -267,26 +256,27 @@ class ProcessPostmarkWebhook implements ShouldQueue (new SystemLogger($this->request, SystemLog::CATEGORY_MAIL, SystemLog::EVENT_MAIL_SPAM_COMPLAINT, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->invitation->contact->client, $this->invitation->company))->handle(); - if(config('ninja.notification.slack')) + if (config('ninja.notification.slack')) { $this->invitation->company->notification(new EmailSpamNotification($this->invitation->company->account))->ninja(); - + } } private function discoverInvitation($message_id) { $invitation = false; - if($invitation = InvoiceInvitation::where('message_id', $message_id)->first()) + if ($invitation = InvoiceInvitation::where('message_id', $message_id)->first()) { return $invitation; - elseif($invitation = QuoteInvitation::where('message_id', $message_id)->first()) + } elseif ($invitation = QuoteInvitation::where('message_id', $message_id)->first()) { return $invitation; - elseif($invitation = RecurringInvoiceInvitation::where('message_id', $message_id)->first()) + } elseif ($invitation = RecurringInvoiceInvitation::where('message_id', $message_id)->first()) { return $invitation; - elseif($invitation = CreditInvitation::where('message_id', $message_id)->first()) + } elseif ($invitation = CreditInvitation::where('message_id', $message_id)->first()) { return $invitation; - elseif($invitation = PurchaseOrderInvitation::where('message_id', $message_id)->first()) + } elseif ($invitation = PurchaseOrderInvitation::where('message_id', $message_id)->first()) { return $invitation; - else + } else { return $invitation; + } } -} \ No newline at end of file +} diff --git a/app/Jobs/Product/UpdateOrCreateProduct.php b/app/Jobs/Product/UpdateOrCreateProduct.php index 02a6d7e6b5bb..dd3ad2ab5633 100644 --- a/app/Jobs/Product/UpdateOrCreateProduct.php +++ b/app/Jobs/Product/UpdateOrCreateProduct.php @@ -85,20 +85,18 @@ class UpdateOrCreateProduct implements ShouldQueue $product = Product::withTrashed()->firstOrNew(['product_key' => $item->product_key, 'company_id' => $this->invoice->company->id]); - /* If a user is using placeholders in their descriptions, do not update the products */ - $string_hit = false; + /* If a user is using placeholders in their descriptions, do not update the products */ + $string_hit = false; - foreach ( [':MONTH',':YEAR',':QUARTER',':WEEK'] as $string ) - { - - if(stripos($product->notes, $string) !== FALSE) { - $string_hit = true; - } - + foreach ([':MONTH',':YEAR',':QUARTER',':WEEK'] as $string) { + if (stripos($product->notes, $string) !== false) { + $string_hit = true; } + } - if($string_hit) - continue; + if ($string_hit) { + continue; + } $product->product_key = $item->product_key; $product->notes = isset($item->notes) ? $item->notes : ''; @@ -115,17 +113,21 @@ class UpdateOrCreateProduct implements ShouldQueue $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) + if (isset($item->custom_value1) && strlen($item->custom_value1) >=1) { $product->custom_value1 = $item->custom_value1; + } - if(isset($item->custom_value2) && strlen($item->custom_value1) >=1) + if (isset($item->custom_value2) && strlen($item->custom_value1) >=1) { $product->custom_value2 = $item->custom_value2; + } - if(isset($item->custom_value3) && strlen($item->custom_value1) >=1) + if (isset($item->custom_value3) && strlen($item->custom_value1) >=1) { $product->custom_value3 = $item->custom_value3; + } - if(isset($item->custom_value4) && strlen($item->custom_value1) >=1) + if (isset($item->custom_value4) && strlen($item->custom_value1) >=1) { $product->custom_value4 = $item->custom_value4; + } $product->user_id = $this->invoice->user_id; $product->company_id = $this->invoice->company_id; diff --git a/app/Jobs/PurchaseOrder/PurchaseOrderEmail.php b/app/Jobs/PurchaseOrder/PurchaseOrderEmail.php index f210e9337dc3..ace474991c4e 100644 --- a/app/Jobs/PurchaseOrder/PurchaseOrderEmail.php +++ b/app/Jobs/PurchaseOrder/PurchaseOrderEmail.php @@ -20,7 +20,6 @@ use App\Mail\VendorTemplateEmail; use App\Models\Company; use App\Models\PurchaseOrder; use App\Utils\Ninja; -use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; @@ -60,8 +59,7 @@ class PurchaseOrderEmail implements ShouldQueue $this->purchase_order->last_sent_date = now(); $this->purchase_order->invitations->load('contact.vendor.country', 'purchase_order.vendor.country', 'purchase_order.company')->each(function ($invitation) { - - /* Don't fire emails if the company is disabled */ + /* Don't fire emails if the company is disabled */ if ($this->company->is_disabled) { return true; } @@ -77,10 +75,11 @@ class PurchaseOrderEmail implements ShouldQueue /* Mark entity sent */ $invitation->purchase_order->service()->markSent()->save(); - if(is_array($this->template_data) && array_key_exists('template', $this->template_data)) + if (is_array($this->template_data) && array_key_exists('template', $this->template_data)) { $template = $this->template_data['template']; - else + } else { $template = 'purchase_order'; + } $email_builder = (new PurchaseOrderEmailEngine($invitation, $template, $this->template_data))->build(); diff --git a/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php b/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php index bc8da551e975..07d37172b28d 100644 --- a/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php +++ b/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php @@ -11,25 +11,20 @@ namespace App\Jobs\PurchaseOrder; -use App\Jobs\Entity\CreateEntityPdf; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\Util\UnlinkFile; use App\Jobs\Vendor\CreatePurchaseOrderPdf; use App\Libraries\MultiDB; -use App\Mail\DownloadInvoices; use App\Mail\DownloadPurchaseOrders; use App\Models\Company; use App\Models\User; -use App\Utils\TempFile; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Storage; -use ZipArchive; class ZipPurchaseOrders implements ShouldQueue { diff --git a/app/Jobs/Quote/QuoteCheckExpired.php b/app/Jobs/Quote/QuoteCheckExpired.php index 5a4061d7bfdd..d1880458b779 100644 --- a/app/Jobs/Quote/QuoteCheckExpired.php +++ b/app/Jobs/Quote/QuoteCheckExpired.php @@ -18,7 +18,6 @@ use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; use App\Mail\Admin\QuoteExpiredObject; use App\Models\Quote; -use App\Repositories\BaseRepository; use App\Utils\Traits\Notifications\UserNotifies; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -33,7 +32,9 @@ class QuoteCheckExpired implements ShouldQueue /** * Create a new job instance. */ - public function __construct() {} + public function __construct() + { + } /** * Execute the job. @@ -42,61 +43,53 @@ class QuoteCheckExpired implements ShouldQueue */ public function handle() { - if (! config('ninja.db.multi_db_enabled')){ - + if (! config('ninja.db.multi_db_enabled')) { Quote::query() ->where('status_id', Quote::STATUS_SENT) ->where('is_deleted', false) ->whereNull('deleted_at') ->whereNotNull('due_date') ->whereHas('client', function ($query) { - $query->where('is_deleted', 0) - ->where('deleted_at', null); - }) + $query->where('is_deleted', 0) + ->where('deleted_at', null); + }) ->whereHas('company', function ($query) { $query->where('is_disabled', 0); }) // ->where('due_date', '<='. now()->toDateTimeString()) ->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()]) ->cursor() - ->each(function ($quote){ - $this->queueExpiredQuoteNotification($quote); + ->each(function ($quote) { + $this->queueExpiredQuoteNotification($quote); }); - - } - else { - - foreach (MultiDB::$dbs as $db) - { - + } else { + foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); - Quote::query() - ->where('status_id', Quote::STATUS_SENT) - ->where('is_deleted', false) - ->whereNull('deleted_at') - ->whereNotNull('due_date') - ->whereHas('client', function ($query) { - $query->where('is_deleted', 0) - ->where('deleted_at', null); - }) - ->whereHas('company', function ($query) { - $query->where('is_disabled', 0); - }) - // ->where('due_date', '<='. now()->toDateTimeString()) - ->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()]) - ->cursor() - ->each(function ($quote){ - $this->queueExpiredQuoteNotification($quote); - }); + Quote::query() + ->where('status_id', Quote::STATUS_SENT) + ->where('is_deleted', false) + ->whereNull('deleted_at') + ->whereNotNull('due_date') + ->whereHas('client', function ($query) { + $query->where('is_deleted', 0) + ->where('deleted_at', null); + }) + ->whereHas('company', function ($query) { + $query->where('is_disabled', 0); + }) + // ->where('due_date', '<='. now()->toDateTimeString()) + ->whereBetween('due_date', [now()->subDay()->startOfDay(), now()->startOfDay()->subSecond()]) + ->cursor() + ->each(function ($quote) { + $this->queueExpiredQuoteNotification($quote); + }); } } - } private function checkForExpiredQuotes() { - } private function queueExpiredQuoteNotification(Quote $quote) @@ -108,7 +101,6 @@ class QuoteCheckExpired implements ShouldQueue /* We loop through each user and determine whether they need to be notified */ foreach ($quote->company->company_users as $company_user) { - /* The User */ $user = $company_user->user; @@ -126,9 +118,7 @@ class QuoteCheckExpired implements ShouldQueue $nmo->to_user = $user; NinjaMailerJob::dispatch($nmo); - } } } - } diff --git a/app/Jobs/Quote/ZipQuotes.php b/app/Jobs/Quote/ZipQuotes.php index bd4e15ff977d..3dd1b7f8967b 100644 --- a/app/Jobs/Quote/ZipQuotes.php +++ b/app/Jobs/Quote/ZipQuotes.php @@ -19,15 +19,12 @@ use App\Libraries\MultiDB; use App\Mail\DownloadQuotes; use App\Models\Company; use App\Models\User; -use App\Utils\TempFile; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Storage; -use ZipArchive; class ZipQuotes implements ShouldQueue { @@ -80,11 +77,9 @@ class ZipQuotes implements ShouldQueue $path = $this->quotes->first()->client->quote_filepath($invitation); $this->quotes->each(function ($quote) { - $quote->service()->createInvitations(); (new CreateEntityPdf($quote->invitations()->first()))->handle(); - }); try { diff --git a/app/Jobs/RecurringInvoice/SendRecurring.php b/app/Jobs/RecurringInvoice/SendRecurring.php index 8833ebfd12b9..2b9269fd1a7a 100644 --- a/app/Jobs/RecurringInvoice/SendRecurring.php +++ b/app/Jobs/RecurringInvoice/SendRecurring.php @@ -12,17 +12,14 @@ namespace App\Jobs\RecurringInvoice; use App\DataMapper\Analytics\SendRecurringFailure; -use App\Events\Invoice\InvoiceWasEmailed; use App\Factory\InvoiceInvitationFactory; use App\Factory\RecurringInvoiceToInvoiceFactory; use App\Jobs\Cron\AutoBill; use App\Jobs\Entity\EmailEntity; use App\Models\Invoice; use App\Models\RecurringInvoice; -use App\Utils\Ninja; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; -use App\Utils\Traits\MakesInvoiceValues; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -62,7 +59,6 @@ class SendRecurring implements ShouldQueue */ public function handle() : void { - // Generate Standard Invoice $invoice = RecurringInvoiceToInvoiceFactory::create($this->recurring_invoice, $this->recurring_invoice->client); @@ -124,7 +120,7 @@ class SendRecurring implements ShouldQueue $invoice->invitations->each(function ($invitation) use ($invoice) { if ($invitation->contact && ! $invitation->contact->trashed() && strlen($invitation->contact->email) >= 1 && $invoice->client->getSetting('auto_email_invoice')) { try { - EmailEntity::dispatch($invitation, $invoice->company)->delay(rand(1,2)); + EmailEntity::dispatch($invitation, $invoice->company)->delay(rand(1, 2)); } catch (\Exception $e) { nlog($e->getMessage()); } @@ -137,12 +133,11 @@ class SendRecurring implements ShouldQueue //auto bill, BUT NOT DRAFTS!! if ($invoice->auto_bill_enabled && $invoice->client->getSetting('auto_bill_date') == 'on_send_date' && $invoice->client->getSetting('auto_email_invoice')) { nlog("attempting to autobill {$invoice->number}"); - AutoBill::dispatch($invoice->id, $this->db)->delay(rand(1,2)); - + AutoBill::dispatch($invoice->id, $this->db)->delay(rand(1, 2)); } elseif ($invoice->auto_bill_enabled && $invoice->client->getSetting('auto_bill_date') == 'on_due_date' && $invoice->client->getSetting('auto_email_invoice')) { if ($invoice->due_date && Carbon::parse($invoice->due_date)->startOfDay()->lte(now()->startOfDay())) { nlog("attempting to autobill {$invoice->number}"); - AutoBill::dispatch($invoice->id, $this->db)->delay(rand(1,2)); + AutoBill::dispatch($invoice->id, $this->db)->delay(rand(1, 2)); } } } @@ -154,8 +149,7 @@ class SendRecurring implements ShouldQueue */ private function createRecurringInvitations($invoice) :Invoice { - - if($this->recurring_invoice->invitations->count() == 0) { + if ($this->recurring_invoice->invitations->count() == 0) { $this->recurring_invoice = $this->recurring_invoice->service()->createInvitations()->save(); } @@ -187,14 +181,14 @@ class SendRecurring implements ShouldQueue /** - * + * * 1/8/2022 - * + * * Improvements here include moving the emailentity and autobilling into the queue. - * + * * Further improvements could using the CompanyRecurringCron.php stub which divides * the recurring invoices into companies and spins them off into their own queue to * improve parallel processing. - * + * * Need to be careful we do not overload redis and OOM. -*/ \ No newline at end of file +*/ diff --git a/app/Jobs/Report/SendToAdmin.php b/app/Jobs/Report/SendToAdmin.php index dce88638ceb3..29caccd7bbd6 100644 --- a/app/Jobs/Report/SendToAdmin.php +++ b/app/Jobs/Report/SendToAdmin.php @@ -11,7 +11,6 @@ namespace App\Jobs\Report; -use App\Http\Requests\Report\GenericReportRequest; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; diff --git a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php index c7d08602f45c..f58084239c4f 100644 --- a/app/Jobs/Subscription/CleanStaleInvoiceOrder.php +++ b/app/Jobs/Subscription/CleanStaleInvoiceOrder.php @@ -15,7 +15,6 @@ use App\Libraries\MultiDB; use App\Models\Invoice; use App\Repositories\InvoiceRepository; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; @@ -30,17 +29,17 @@ class CleanStaleInvoiceOrder implements ShouldQueue * @param int invoice_id * @param string $db */ - public function __construct(){} + public function __construct() + { + } /** - * @param InvoiceRepository $repo - * @return void + * @param InvoiceRepository $repo + * @return void */ public function handle(InvoiceRepository $repo) : void { - - if (! config('ninja.db.multi_db_enabled')) { - + if (! config('ninja.db.multi_db_enabled')) { Invoice::query() ->withTrashed() ->where('is_proforma', 1) @@ -52,12 +51,10 @@ class CleanStaleInvoiceOrder implements ShouldQueue }); return; - } + } - foreach (MultiDB::$dbs as $db) - { - + foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); Invoice::query() @@ -69,9 +66,7 @@ class CleanStaleInvoiceOrder implements ShouldQueue $invoice->is_proforma = false; $repo->delete($invoice); }); - } - } public function failed($exception = null) diff --git a/app/Jobs/User/CreateUser.php b/app/Jobs/User/CreateUser.php index 2835eed92fff..3e33c6f6c28c 100644 --- a/app/Jobs/User/CreateUser.php +++ b/app/Jobs/User/CreateUser.php @@ -12,13 +12,11 @@ namespace App\Jobs\User; use App\DataMapper\CompanySettings; -use App\DataMapper\DefaultSettings; use App\Events\User\UserWasCreated; use App\Models\User; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Bus\Dispatchable; -use Illuminate\Http\Request; class CreateUser { diff --git a/app/Jobs/User/UserEmailChanged.php b/app/Jobs/User/UserEmailChanged.php index 73a22028f58a..b400684f052b 100644 --- a/app/Jobs/User/UserEmailChanged.php +++ b/app/Jobs/User/UserEmailChanged.php @@ -24,7 +24,6 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Mail; use stdClass; class UserEmailChanged implements ShouldQueue diff --git a/app/Jobs/User/VerifyPhone.php b/app/Jobs/User/VerifyPhone.php index 521e5c64413a..e28c77afb420 100644 --- a/app/Jobs/User/VerifyPhone.php +++ b/app/Jobs/User/VerifyPhone.php @@ -11,17 +11,12 @@ namespace App\Jobs\User; -use App\DataMapper\CompanySettings; -use App\DataMapper\DefaultSettings; -use App\Events\User\UserWasCreated; use App\Libraries\MultiDB; use App\Models\User; -use App\Utils\Ninja; use App\Utils\Traits\MakesHash; -use Illuminate\Foundation\Bus\Dispatchable; -use Illuminate\Http\Request; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; @@ -35,7 +30,9 @@ class VerifyPhone implements ShouldQueue * * @param User $user */ - public function __construct(private User $user){} + public function __construct(private User $user) + { + } /** * Execute the job. @@ -44,41 +41,38 @@ class VerifyPhone implements ShouldQueue */ public function handle() : void { + MultiDB::checkUserEmailExists($this->user->email); - MultiDB::checkUserEmailExists($this->user->email); + $sid = config('ninja.twilio_account_sid'); + $token = config('ninja.twilio_auth_token'); - $sid = config('ninja.twilio_account_sid'); - $token = config('ninja.twilio_auth_token'); + if (!$sid) { + return; + } // no twilio api credentials provided, bail. - if(!$sid) - return; // no twilio api credentials provided, bail. + $twilio = new \Twilio\Rest\Client($sid, $token); - $twilio = new \Twilio\Rest\Client($sid, $token); + $country = $this->user->account?->companies()?->first()?->country(); - $country = $this->user->account?->companies()?->first()?->country(); + if (!$country || strlen($this->user->phone) < 2) { + return; + } - if(!$country || strlen($this->user->phone) < 2) - return; + $countryCode = $country->iso_3166_2; - $countryCode = $country->iso_3166_2; + try { + $phone_number = $twilio->lookups->v1->phoneNumbers($this->user->phone) + ->fetch(["countryCode" => $countryCode]); + } catch(\Exception $e) { + $this->user->verified_phone_number = false; + $this->user->save(); + return; + } - try{ - - $phone_number = $twilio->lookups->v1->phoneNumbers($this->user->phone) - ->fetch(["countryCode" => $countryCode]); - } - catch(\Exception $e) { - $this->user->verified_phone_number = false; - $this->user->save(); - return; - } - - if($phone_number && strlen($phone_number->phoneNumber) > 1) - { - $this->user->phone = $phone_number->phoneNumber; - $this->user->verified_phone_number = true; - $this->user->save(); - } - } - -} \ No newline at end of file + if ($phone_number && strlen($phone_number->phoneNumber) > 1) { + $this->user->phone = $phone_number->phoneNumber; + $this->user->verified_phone_number = true; + $this->user->save(); + } + } +} diff --git a/app/Jobs/Util/ApplePayDomain.php b/app/Jobs/Util/ApplePayDomain.php index 3e3c25b6fc83..b9e424e2e3ef 100644 --- a/app/Jobs/Util/ApplePayDomain.php +++ b/app/Jobs/Util/ApplePayDomain.php @@ -11,9 +11,7 @@ namespace App\Jobs\Util; -use App\Jobs\Util\UnlinkFile; use App\Libraries\MultiDB; -use App\Models\Account; use App\Models\CompanyGateway; use App\Utils\Ninja; use Illuminate\Bus\Queueable; @@ -21,7 +19,6 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Storage; class ApplePayDomain implements ShouldQueue { diff --git a/app/Jobs/Util/DiskCleanup.php b/app/Jobs/Util/DiskCleanup.php index 46c6acfa2d50..9764fc86d26b 100644 --- a/app/Jobs/Util/DiskCleanup.php +++ b/app/Jobs/Util/DiskCleanup.php @@ -11,9 +11,6 @@ namespace App\Jobs\Util; -use App\Jobs\Util\UnlinkFile; -use App\Models\Account; -use App\Utils\Ninja; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; diff --git a/app/Jobs/Util/Import.php b/app/Jobs/Util/Import.php index 20f33d21f733..ca6c8143650c 100644 --- a/app/Jobs/Util/Import.php +++ b/app/Jobs/Util/Import.php @@ -15,10 +15,7 @@ use App\DataMapper\Analytics\MigrationFailure; use App\DataMapper\CompanySettings; use App\Exceptions\ClientHostedMigrationException; use App\Exceptions\MigrationValidatorFailed; -use App\Exceptions\ProcessingMigrationArchiveFailed; use App\Exceptions\ResourceDependencyMissing; -use App\Exceptions\ResourceNotAvailableForMigration; -use App\Factory\ClientContactFactory; use App\Factory\ClientFactory; use App\Factory\CompanyLedgerFactory; use App\Factory\CreditFactory; @@ -31,19 +28,15 @@ use App\Factory\TaxRateFactory; use App\Factory\UserFactory; use App\Factory\VendorFactory; use App\Http\Requests\Company\UpdateCompanyRequest; -use App\Http\ValidationRules\User\AttachableUser; use App\Http\ValidationRules\ValidCompanyGatewayFeesAndLimitsRule; use App\Http\ValidationRules\ValidUserForCompany; -use App\Jobs\Company\CreateCompanyTaskStatuses; use App\Jobs\Company\CreateCompanyToken; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\Ninja\CheckCompanyData; -use App\Jobs\Ninja\CompanySizeCheck; -use App\Jobs\Util\VersionCheck; use App\Libraries\MultiDB; -use App\Mail\MigrationCompleted; use App\Mail\Migration\StripeConnectMigration; +use App\Mail\MigrationCompleted; use App\Models\Activity; use App\Models\Client; use App\Models\ClientContact; @@ -74,7 +67,6 @@ use App\Repositories\CreditRepository; use App\Repositories\Migration\InvoiceMigrationRepository; use App\Repositories\Migration\PaymentMigrationRepository; use App\Repositories\ProductRepository; -use App\Repositories\QuoteRepository; use App\Repositories\UserRepository; use App\Repositories\VendorContactRepository; use App\Repositories\VendorRepository; @@ -191,7 +183,7 @@ class Import implements ShouldQueue } public function middleware() - { + { return [(new WithoutOverlapping($this->user->account_id))]; } @@ -260,43 +252,40 @@ class Import implements ShouldQueue $this->processNinjaTokens($data['ninja_tokens']); // $this->fixData(); - try{ + try { App::forgetInstance('translator'); $t = app('translator'); $t->replace(Ninja::transformTranslations($this->company->settings)); Mail::to($this->user->email, $this->user->name()) - ->send(new MigrationCompleted($this->company->id, $this->company->db, implode("
",$check_data))); - } - catch(\Exception $e) { + ->send(new MigrationCompleted($this->company->id, $this->company->db, implode("
", $check_data))); + } catch(\Exception $e) { nlog($e->getMessage()); } /*After a migration first some basic jobs to ensure the system is up to date*/ - if(Ninja::isSelfHost()) + if (Ninja::isSelfHost()) { VersionCheck::dispatch(); + } info('Completed🚀🚀🚀🚀🚀 at '.now()); - try{ + try { unlink($this->file_path); - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog("problem unsetting file"); } } private function fixData() { - $this->company->clients()->withTrashed()->where('is_deleted', 0)->cursor()->each(function ($client) { $total_invoice_payments = 0; $credit_total_applied = 0; foreach ($client->invoices()->where('is_deleted', false)->where('status_id', '>', 1)->get() as $invoice) { - - $total_amount = $invoice->payments()->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->get()->sum('pivot.amount'); - $total_refund = $invoice->payments()->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment:: STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->get()->sum('pivot.refunded'); + $total_amount = $invoice->payments()->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->get()->sum('pivot.amount'); + $total_refund = $invoice->payments()->where('is_deleted', false)->whereIn('status_id', [Payment::STATUS_COMPLETED, Payment::STATUS_PENDING, Payment::STATUS_PARTIALLY_REFUNDED, Payment::STATUS_REFUNDED])->get()->sum('pivot.refunded'); $total_invoice_payments += ($total_amount - $total_refund); } @@ -308,23 +297,19 @@ class Import implements ShouldQueue if ($credit_total_applied < 0) { $total_invoice_payments += $credit_total_applied; - } + } if (round($total_invoice_payments, 2) != round($client->paid_to_date, 2)) { - $client->paid_to_date = $total_invoice_payments; $client->save(); - } }); - } private function setInitialCompanyLedgerBalances() { Client::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); @@ -339,13 +324,12 @@ class Import implements ShouldQueue $client->balance = $invoice_balances; $client->save(); - }); } private function processAccount(array $data) :void { - if(array_key_exists('token', $data)){ + if (array_key_exists('token', $data)) { $this->token = $data['token']; unset($data['token']); } @@ -353,29 +337,33 @@ class Import implements ShouldQueue $account = $this->company->account; /* If the user has upgraded their account, do not wipe their payment plan*/ - if($account->isPaid() || (isset($data['plan']) && $data['plan'] == 'white_label')) - { - if(isset($data['plan'])) + if ($account->isPaid() || (isset($data['plan']) && $data['plan'] == 'white_label')) { + if (isset($data['plan'])) { unset($data['plan']); + } - if(isset($data['plan_term'])) + if (isset($data['plan_term'])) { unset($data['plan_term']); + } - if(isset($data['plan_paid'])) + if (isset($data['plan_paid'])) { unset($data['plan_paid']); + } - if(isset($data['plan_started'])) + if (isset($data['plan_started'])) { unset($data['plan_started']); + } - if(isset($data['plan_expires'])) + if (isset($data['plan_expires'])) { unset($data['plan_expires']); + } } $account->fill($data); $account->save(); //Prevent hosted users being pushed into a trial - if(Ninja::isHosted() && $account->plan != ''){ + if (Ninja::isHosted() && $account->plan != '') { $account->trial_plan = ''; $account->save(); } @@ -395,32 +383,35 @@ class Import implements ShouldQueue ) { $data['settings']['invoice_design_id'] = 1; } - $data['settings']['email_sending_method'] = 'default'; + $data['settings']['email_sending_method'] = 'default'; $data = $this->transformCompanyData($data); - if(Ninja::isHosted()) { - - if(!MultiDB::checkDomainAvailable($data['subdomain'])) + if (Ninja::isHosted()) { + if (!MultiDB::checkDomainAvailable($data['subdomain'])) { $data['subdomain'] = MultiDB::randomSubdomainGenerator(); + } - if(strlen($data['subdomain']) == 0) + if (strlen($data['subdomain']) == 0) { $data['subdomain'] = MultiDB::randomSubdomainGenerator(); - + } } $rules = (new UpdateCompanyRequest())->rules(); $validator = Validator::make($data, $rules); - if ($validator->fails()) + if ($validator->fails()) { throw new MigrationValidatorFailed(json_encode($validator->errors())); + } - if (isset($data['account_id'])) + if (isset($data['account_id'])) { unset($data['account_id']); + } - if(isset($data['version'])) + if (isset($data['version'])) { unset($data['version']); + } if (isset($data['referral_code'])) { $account = $this->company->account; @@ -438,18 +429,15 @@ class Import implements ShouldQueue $company_repository->save($data, $this->company); if (isset($data['settings']->company_logo) && strlen($data['settings']->company_logo) > 0) { - try { $tempImage = tempnam(sys_get_temp_dir(), basename($data['settings']->company_logo)); copy($data['settings']->company_logo, $tempImage); $this->uploadLogo($tempImage, $this->company, $this->company); } catch (\Exception $e) { - $settings = $this->company->settings; $settings->company_logo = ''; $this->company->settings = $settings; $this->company->save(); - } } @@ -464,24 +452,29 @@ class Import implements ShouldQueue private function parseCustomFields($fields) :array { - - if(array_key_exists('account1', $fields)) + if (array_key_exists('account1', $fields)) { $fields['company1'] = $fields['account1']; + } - if(array_key_exists('account2', $fields)) + if (array_key_exists('account2', $fields)) { $fields['company2'] = $fields['account2']; + } - if(array_key_exists('invoice1', $fields)) + if (array_key_exists('invoice1', $fields)) { $fields['surcharge1'] = $fields['invoice1']; + } - if(array_key_exists('invoice2', $fields)) + if (array_key_exists('invoice2', $fields)) { $fields['surcharge2'] = $fields['invoice2']; + } - if(array_key_exists('invoice_text1', $fields)) + if (array_key_exists('invoice_text1', $fields)) { $fields['invoice1'] = $fields['invoice_text1']; + } - if(array_key_exists('invoice_text2', $fields)) + if (array_key_exists('invoice_text2', $fields)) { $fields['invoice2'] = $fields['invoice_text2']; + } foreach ($fields as &$value) { $value = (string) $value; @@ -492,7 +485,6 @@ class Import implements ShouldQueue private function transformCompanyData(array $data): array { - $company_settings = CompanySettings::defaults(); if (array_key_exists('settings', $data)) { @@ -500,9 +492,9 @@ class Import implements ShouldQueue if ($key == 'invoice_design_id' || $key == 'quote_design_id' || $key == 'credit_design_id') { $value = $this->encodePrimaryKey($value); - if(!$value) + if (!$value) { $value = $this->encodePrimaryKey(1); - + } } /* changes $key = '' to $value == '' and changed the return value from -1 to "0" 06/01/2022 */ @@ -512,17 +504,15 @@ class Import implements ShouldQueue $company_settings->{$key} = $value; - if($key == 'payment_terms'){ + if ($key == 'payment_terms') { settype($company_settings->payment_terms, 'string'); } - } - if(Ninja::isHosted()) - { - $data['portal_mode'] = 'subdomain'; - $data['portal_domain'] = ''; - } + if (Ninja::isHosted()) { + $data['portal_mode'] = 'subdomain'; + $data['portal_domain'] = ''; + } $data['settings'] = $company_settings; } @@ -572,7 +562,7 @@ class Import implements ShouldQueue TaxRate::reguard(); - if(TaxRate::count() > 0){ + if (TaxRate::count() > 0) { $this->company->enabled_tax_rates = 2; $this->company->save(); } @@ -585,9 +575,9 @@ class Import implements ShouldQueue private function testUserDbLocationSanity(array $data): bool { - - if(Ninja::isSelfHost()) + if (Ninja::isSelfHost()) { return true; + } $current_db = config('database.default'); @@ -596,11 +586,13 @@ class Import implements ShouldQueue MultiDB::setDb($current_db); - if($db2_count == 0 && $db1_count == 0) + if ($db2_count == 0 && $db1_count == 0) { return true; + } - if($db1_count >= 1 && $db2_count >= 1) + if ($db1_count >= 1 && $db2_count >= 1) { return false; + } return true; } @@ -611,8 +603,9 @@ class Import implements ShouldQueue */ private function processUsers(array $data): void { - if(!$this->testUserDbLocationSanity($data)) + if (!$this->testUserDbLocationSanity($data)) { throw new ClientHostedMigrationException('You have users that belong to different accounts registered in the system, please contact us to resolve.', 400); + } User::unguard(); @@ -642,8 +635,9 @@ class Import implements ShouldQueue $user->email_verified_at = now(); // $user->confirmation_code = ''; - if($modified['deleted_at']) + if ($modified['deleted_at']) { $user->deleted_at = now(); + } $user->password = $modified['password']; $user->save(); @@ -678,8 +672,9 @@ class Import implements ShouldQueue ->withTrashed() ->exists(); - if($model_query) + if ($model_query) { return $value . '_' . Str::random(5); + } return $value; } @@ -714,11 +709,13 @@ class Import implements ShouldQueue ) ); - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $client->created_at = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $client->updated_at = Carbon::parse($modified['updated_at']); + } $client->country_id = array_key_exists('country_id', $modified) ? $modified['country_id'] : $this->company->settings->country_id; $client->save(['timestamps' => false]); @@ -733,7 +730,7 @@ class Import implements ShouldQueue $modified_contacts[$key]['company_id'] = $this->company->id; $modified_contacts[$key]['user_id'] = $this->processUserId($resource); $modified_contacts[$key]['client_id'] = $client->id; - $modified_contacts[$key]['password'] = Str::random(8); + $modified_contacts[$key]['password'] = Str::random(8); unset($modified_contacts[$key]['id']); } @@ -744,7 +741,6 @@ class Import implements ShouldQueue //link contact ids foreach ($resource['contacts'] as $key => $old_contact) { - $contact_match = ClientContact::where('contact_key', $old_contact['contact_key']) ->where('company_id', $this->company->id) ->where('client_id', $client->id) @@ -752,12 +748,10 @@ class Import implements ShouldQueue ->first(); if ($contact_match) { - $this->ids['client_contacts']['client_contacts_'.$old_contact['id']] = [ 'old' => $old_contact['id'], 'new' => $contact_match->id, ]; - } } } @@ -774,12 +768,10 @@ class Import implements ShouldQueue Client::reguard(); - Client::withTrashed()->with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($client){ - - $contact = $client->contacts->sortByDesc('is_primary')->first(); - $contact->is_primary = true; - $contact->save(); - + Client::withTrashed()->with('contacts')->where('company_id', $this->company->id)->cursor()->each(function ($client) { + $contact = $client->contacts->sortByDesc('is_primary')->first(); + $contact->is_primary = true; + $contact->save(); }); @@ -809,11 +801,13 @@ class Import implements ShouldQueue unset($modified['id']); unset($modified['contacts']); - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $modified['created_at'] = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $modified['updated_at'] = Carbon::parse($modified['updated_at']); + } $vendor = $vendor_repository->save( $modified, @@ -882,11 +876,13 @@ class Import implements ShouldQueue $modified['company_id'] = $this->company->id; $modified['user_id'] = $this->processUserId($resource); - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $modified['created_at'] = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $modified['updated_at'] = Carbon::parse($modified['updated_at']); + } unset($modified['id']); @@ -942,11 +938,13 @@ class Import implements ShouldQueue $expense = RecurringExpense::create($modified); - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $expense->created_at = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $expense->updated_at = Carbon::parse($modified['updated_at']); + } $expense->save(['timestamps' => false]); @@ -958,7 +956,6 @@ class Import implements ShouldQueue 'old' => $resource['id'], 'new' => $expense->id, ]; - } @@ -996,14 +993,17 @@ class Import implements ShouldQueue $modified['company_id'] = $this->company->id; $modified['line_items'] = $this->cleanItems($modified['line_items']); - if(array_key_exists('next_send_date', $resource)) + if (array_key_exists('next_send_date', $resource)) { $modified['next_send_date_client'] = $resource['next_send_date']; + } - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $modified['created_at'] = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $modified['updated_at'] = Carbon::parse($modified['updated_at']); + } unset($modified['id']); @@ -1016,11 +1016,9 @@ class Import implements ShouldQueue unset($resource['invitations'][$key]['recurring_invoice_id']); unset($resource['invitations'][$key]['id']); - } $modified['invitations'] = $this->deDuplicateInvitations($resource['invitations']); - } $invoice = $invoice_repository->save( @@ -1028,7 +1026,7 @@ class Import implements ShouldQueue RecurringInvoiceFactory::create($this->company->id, $modified['user_id']) ); - if($invoice->status_id == 4 && $invoice->remaining_cycles == -1){ + if ($invoice->status_id == 4 && $invoice->remaining_cycles == -1) { $invoice->status_id =2; $invoice->save(); } @@ -1073,8 +1071,9 @@ class Import implements ShouldQueue $modified['client_id'] = $this->transformId('clients', $resource['client_id']); - if(array_key_exists('recurring_id', $resource) && !is_null($resource['recurring_id'])) + if (array_key_exists('recurring_id', $resource) && !is_null($resource['recurring_id'])) { $modified['recurring_id'] = $this->transformId('recurring_invoices', (string)$resource['recurring_id']); + } $modified['user_id'] = $this->processUserId($resource); $modified['company_id'] = $this->company->id; @@ -1093,7 +1092,6 @@ class Import implements ShouldQueue } $modified['invitations'] = $this->deDuplicateInvitations($resource['invitations']); - } $invoice = $invoice_repository->save( @@ -1119,7 +1117,7 @@ class Import implements ShouldQueue /* Prevent edge case where V4 has inserted multiple invitations for a resource for a client contact */ private function deDuplicateInvitations($invitations) - { + { return array_intersect_key($invitations, array_unique(array_column($invitations, 'client_contact_id'))); } @@ -1150,11 +1148,13 @@ class Import implements ShouldQueue $modified['user_id'] = $this->processUserId($resource); $modified['company_id'] = $this->company->id; - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $modified['created_at'] = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $modified['updated_at'] = Carbon::parse($modified['updated_at']); + } unset($modified['id']); @@ -1164,7 +1164,7 @@ class Import implements ShouldQueue ); //remove credit balance from ledger - if($credit->balance > 0 && $credit->client->balance > 0){ + if ($credit->balance > 0 && $credit->client->balance > 0) { $client = $credit->client; $client->balance -= $credit->balance; $client->save(); @@ -1184,7 +1184,6 @@ class Import implements ShouldQueue /*Improve memory handling by setting everything to null when we have finished*/ $data = null; $credit_repository = null; - } private function processQuotes(array $data): void @@ -1212,24 +1211,29 @@ class Import implements ShouldQueue $modified['client_id'] = $this->transformId('clients', $resource['client_id']); - if(array_key_exists('invoice_id', $resource) && isset($resource['invoice_id']) && $this->tryTransformingId('invoices', $resource['invoice_id'])) + if (array_key_exists('invoice_id', $resource) && isset($resource['invoice_id']) && $this->tryTransformingId('invoices', $resource['invoice_id'])) { $modified['invoice_id'] = $this->transformId('invoices', $resource['invoice_id']); + } $modified['user_id'] = $this->processUserId($resource); $modified['company_id'] = $this->company->id; - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $modified['created_at'] = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $modified['updated_at'] = Carbon::parse($modified['updated_at']); + } - if(array_key_exists('tax_rate1', $modified) && is_null($modified['tax_rate1'])) + if (array_key_exists('tax_rate1', $modified) && is_null($modified['tax_rate1'])) { $modified['tax_rate1'] = 0; + } - if(array_key_exists('tax_rate2', $modified) && is_null($modified['tax_rate2'])) + if (array_key_exists('tax_rate2', $modified) && is_null($modified['tax_rate2'])) { $modified['tax_rate2'] = 0; + } unset($modified['id']); @@ -1245,7 +1249,6 @@ class Import implements ShouldQueue } $modified['invitations'] = $this->deDuplicateInvitations($resource['invitations']); - } $quote = $quote_repository->save( @@ -1253,11 +1256,13 @@ class Import implements ShouldQueue QuoteFactory::create($this->company->id, $modified['user_id']) ); - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $quote->created_at = $modified['created_at']; + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $quote->updated_at = $modified['updated_at']; + } $quote->save(['timestamps' => false]); @@ -1313,9 +1318,9 @@ class Import implements ShouldQueue if ($this->tryTransformingId('invoices', $invoice['invoice_id'])) { $modified['invoices'][$key]['invoice_id'] = $this->transformId('invoices', $invoice['invoice_id']); } else { - nlog($modified['invoices']); - unset($modified['invoices']); - //if the transformation didn't work - you _must_ unset this data as it will be incorrect! + nlog($modified['invoices']); + unset($modified['invoices']); + //if the transformation didn't work - you _must_ unset this data as it will be incorrect! } } } @@ -1325,18 +1330,20 @@ class Import implements ShouldQueue PaymentFactory::create($this->company->id, $modified['user_id']) ); - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $payment->created_at = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $payment->updated_at = Carbon::parse($modified['updated_at']); + } $payment->save(['timestamps' => false]); if (array_key_exists('company_gateway_id', $resource) && isset($resource['company_gateway_id']) && $resource['company_gateway_id'] != 'NULL') { - - if($this->tryTransformingId('company_gateways', $resource['company_gateway_id'])) + if ($this->tryTransformingId('company_gateways', $resource['company_gateway_id'])) { $payment->company_gateway_id = $this->transformId('company_gateways', $resource['company_gateway_id']); + } $payment->save(); } @@ -1351,11 +1358,9 @@ class Import implements ShouldQueue ], ]; - if(in_array($payment->status_id, [Payment::STATUS_REFUNDED, Payment::STATUS_PARTIALLY_REFUNDED])) { + if (in_array($payment->status_id, [Payment::STATUS_REFUNDED, Payment::STATUS_PARTIALLY_REFUNDED])) { $this->processPaymentRefund($payment); } - - } Payment::reguard(); @@ -1369,17 +1374,14 @@ class Import implements ShouldQueue { $invoices = $payment->invoices()->get(); - $invoices->each(function ($invoice) use($payment) { - + $invoices->each(function ($invoice) use ($payment) { if ($payment->refunded > 0 && in_array($invoice->status_id, [Invoice::STATUS_SENT])) { - $invoice->service() ->updateBalance($payment->refunded) ->updatePaidToDate($payment->refunded*-1) ->updateStatus() ->save(); } - }); } @@ -1428,7 +1430,6 @@ class Import implements ShouldQueue /* No validators since data provided by database is already valid. */ foreach ($data as $resource) { - $modified = $resource; if (array_key_exists('invoice_id', $resource) && $resource['invoice_id'] && ! array_key_exists('invoices', $this->ids)) { @@ -1442,39 +1443,34 @@ class Import implements ShouldQueue } if (array_key_exists('invoice_id', $resource) && $resource['invoice_id'] && array_key_exists('invoices', $this->ids)) { - $try_quote = false; $exception = false; $entity = false; - try{ + try { $invoice_id = $this->transformId('invoices', $resource['invoice_id']); $entity = Invoice::where('id', $invoice_id)->withTrashed()->first(); - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog("i couldn't find the invoice document {$resource['invoice_id']}, perhaps it is a quote?"); nlog($e->getMessage()); $try_quote = true; } - if($try_quote && array_key_exists('quotes', $this->ids) ) { - - try{ + 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(); - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog("i couldn't find the quote document {$resource['invoice_id']}, perhaps it is a quote?"); nlog($e->getMessage()); } } - if(!$entity) + if (!$entity) { continue; + } // throw new Exception("Resource invoice/quote document not available."); - - } @@ -1493,24 +1489,19 @@ class Import implements ShouldQueue $file_info = $finfo->file($file_path); $uploaded_file = new UploadedFile( - $file_path, - $file_name, - $file_info, - filesize($file_path), - 0, - false - ); + $file_path, + $file_name, + $file_info, + filesize($file_path), + 0, + false + ); $this->saveDocument($uploaded_file, $entity, $is_public = true); - } - catch(\Exception $e) { - + } catch(\Exception $e) { //do nothing, gracefully :) - } - } - } private function processPaymentTerms(array $data) :void @@ -1564,12 +1555,12 @@ class Import implements ShouldQueue $modified['fees_and_limits'] = $this->cleanFeesAndLimits($modified['fees_and_limits']); } - if(!array_key_exists('accepted_credit_cards', $modified) || (array_key_exists('accepted_credit_cards', $modified) && empty($modified['accepted_credit_cards']))) + if (!array_key_exists('accepted_credit_cards', $modified) || (array_key_exists('accepted_credit_cards', $modified) && empty($modified['accepted_credit_cards']))) { $modified['accepted_credit_cards'] = 0; + } // /* On Hosted platform we need to advise Stripe users to connect with Stripe Connect */ - if(Ninja::isHosted() && $modified['gateway_key'] == 'd14dd26a37cecc30fdd65700bfb55b23'){ - + if (Ninja::isHosted() && $modified['gateway_key'] == 'd14dd26a37cecc30fdd65700bfb55b23') { $nmo = new NinjaMailerObject; $nmo->mailable = new StripeConnectMigration($this->company); $nmo->company = $this->company; @@ -1578,13 +1569,10 @@ class Import implements ShouldQueue NinjaMailerJob::dispatch($nmo, true); $modified['gateway_key'] = 'd14dd26a47cecc30fdd65700bfb67b34'; - } - if(Ninja::isSelfHost() && $modified['gateway_key'] == 'd14dd26a47cecc30fdd65700bfb67b34'){ - + if (Ninja::isSelfHost() && $modified['gateway_key'] == 'd14dd26a47cecc30fdd65700bfb67b34') { $modified['gateway_key'] = 'd14dd26a37cecc30fdd65700bfb55b23'; - } @@ -1686,7 +1674,6 @@ class Import implements ShouldQueue 'old' => $resource['id'], 'new' => $expense_category->id, ]; - } ExpenseCategory::reguard(); @@ -1724,11 +1711,13 @@ class Import implements ShouldQueue $task = Task::Create($modified); - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $task->created_at = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $task->updated_at = Carbon::parse($modified['updated_at']); + } @@ -1814,11 +1803,13 @@ class Import implements ShouldQueue $expense = Expense::Create($modified); - if(array_key_exists('created_at', $modified)) + if (array_key_exists('created_at', $modified)) { $expense->created_at = Carbon::parse($modified['created_at']); + } - if(array_key_exists('updated_at', $modified)) + if (array_key_exists('updated_at', $modified)) { $expense->updated_at = Carbon::parse($modified['updated_at']); + } @@ -1832,7 +1823,6 @@ class Import implements ShouldQueue 'old' => $resource['id'], 'new' => $expense->id, ]; - } Expense::reguard(); @@ -1873,7 +1863,6 @@ class Import implements ShouldQueue */ public function transformId($resource, string $old): int { - if (! array_key_exists($resource, $this->ids)) { info(print_r($resource, 1)); throw new Exception("Resource {$resource} not available."); @@ -1934,23 +1923,22 @@ class Import implements ShouldQueue info(print_r($exception->getMessage(), 1)); - if(Ninja::isHosted()) + if (Ninja::isHosted()) { app('sentry')->captureException($exception); + } } public function curlGet($url, $headers = false) { - return $this->exec('GET', $url, null); } public function exec($method, $url, $data) { - - $client = new \GuzzleHttp\Client(['headers' => - [ - 'X-Ninja-Token' => $this->token, + $client = new \GuzzleHttp\Client(['headers' => + [ + 'X-Ninja-Token' => $this->token, ] ]); @@ -1963,20 +1951,15 @@ class Import implements ShouldQueue private function processNinjaTokens(array $data) { - nlog("attempting to process Ninja Tokens"); - if(Ninja::isHosted()){ - - try{ + if (Ninja::isHosted()) { + try { \Modules\Admin\Jobs\Account\NinjaUser::dispatch($data, $this->company); - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog($e->getMessage()); } - } - } /* In V4 we use negative invoices (credits) and add then into the client balance. In V5, these sit off ledger and are applied later. diff --git a/app/Jobs/Util/RefreshPdfs.php b/app/Jobs/Util/RefreshPdfs.php index ab8fbadc3e85..cdc5a2c5ccdb 100644 --- a/app/Jobs/Util/RefreshPdfs.php +++ b/app/Jobs/Util/RefreshPdfs.php @@ -12,21 +12,16 @@ namespace App\Jobs\Util; use App\Jobs\Entity\CreateEntityPdf; -use App\Jobs\Util\UnlinkFile; use App\Libraries\MultiDB; -use App\Models\Account; use App\Models\Company; use App\Models\CreditInvitation; use App\Models\InvoiceInvitation; use App\Models\QuoteInvitation; -use App\Utils\Ninja; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Storage; class RefreshPdfs implements ShouldQueue { diff --git a/app/Jobs/Util/ReminderJob.php b/app/Jobs/Util/ReminderJob.php index 2e31aa95fa94..2aef984496d4 100644 --- a/app/Jobs/Util/ReminderJob.php +++ b/app/Jobs/Util/ReminderJob.php @@ -46,12 +46,9 @@ class ReminderJob implements ShouldQueue */ public function handle() :void { - set_time_limit(0); - if (! config('ninja.db.multi_db_enabled')) - { - + if (! config('ninja.db.multi_db_enabled')) { nlog("Sending invoice reminders on ".now()->format('Y-m-d h:i:s')); Invoice::query() @@ -68,23 +65,16 @@ class ReminderJob implements ShouldQueue $query->where('is_disabled', 0); }) ->with('invitations')->chunk(50, function ($invoices) { - - foreach($invoices as $invoice) - { - $this->sendReminderForInvoice($invoice); - } - - sleep(2); + foreach ($invoices as $invoice) { + $this->sendReminderForInvoice($invoice); + } + sleep(2); }); - - } else { //multiDB environment, need to - foreach (MultiDB::$dbs as $db) - { - + foreach (MultiDB::$dbs as $db) { MultiDB::setDB($db); nlog("Sending invoice reminders on db {$db} ".now()->format('Y-m-d h:i:s')); @@ -105,67 +95,58 @@ class ReminderJob implements ShouldQueue ->with('invitations')->chunk(50, function ($invoices) { // if ($invoice->refresh() && $invoice->isPayable()) { - foreach($invoices as $invoice) - { - $this->sendReminderForInvoice($invoice); - } + foreach ($invoices as $invoice) { + $this->sendReminderForInvoice($invoice); + } - sleep(2); - + sleep(2); }); - } - } } - private function sendReminderForInvoice($invoice) { - + private function sendReminderForInvoice($invoice) + { if ($invoice->isPayable()) { - //Attempts to prevent duplicates from sending - if($invoice->reminder_last_sent && Carbon::parse($invoice->reminder_last_sent)->startOfDay()->eq(now()->startOfDay())){ + if ($invoice->reminder_last_sent && Carbon::parse($invoice->reminder_last_sent)->startOfDay()->eq(now()->startOfDay())) { nlog("caught a duplicate reminder for invoice {$invoice->number}"); return; } - $reminder_template = $invoice->calculateTemplate('invoice'); - nlog("reminder template = {$reminder_template}"); - $invoice->service()->touchReminder($reminder_template)->save(); - $invoice = $this->calcLateFee($invoice, $reminder_template); + $reminder_template = $invoice->calculateTemplate('invoice'); + nlog("reminder template = {$reminder_template}"); + $invoice->service()->touchReminder($reminder_template)->save(); + $invoice = $this->calcLateFee($invoice, $reminder_template); - //20-04-2022 fixes for endless reminders - generic template naming was wrong - $enabled_reminder = 'enable_'.$reminder_template; - if ($reminder_template == 'endless_reminder') { - $enabled_reminder = 'enable_reminder_endless'; - } + //20-04-2022 fixes for endless reminders - generic template naming was wrong + $enabled_reminder = 'enable_'.$reminder_template; + if ($reminder_template == 'endless_reminder') { + $enabled_reminder = 'enable_reminder_endless'; + } - //check if this reminder needs to be emailed - //15-01-2022 - insert addition if block if send_reminders is definitely set - if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'reminder_endless', 'endless_reminder']) && + //check if this reminder needs to be emailed + //15-01-2022 - insert addition if block if send_reminders is definitely set + if (in_array($reminder_template, ['reminder1', 'reminder2', 'reminder3', 'reminder_endless', 'endless_reminder']) && $invoice->client->getSetting($enabled_reminder) && $invoice->client->getSetting('send_reminders') && (Ninja::isSelfHost() || $invoice->company->account->isPaidHostedClient())) { - - $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) { - - if($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email) { - EmailEntity::dispatch($invitation, $invitation->company, $reminder_template)->delay(now()->addSeconds(3)); - nlog("Firing reminder email for invoice {$invoice->number} - {$reminder_template}"); + $invoice->invitations->each(function ($invitation) use ($invoice, $reminder_template) { + if ($invitation->contact && !$invitation->contact->trashed() && $invitation->contact->email) { + EmailEntity::dispatch($invitation, $invitation->company, $reminder_template)->delay(now()->addSeconds(3)); + nlog("Firing reminder email for invoice {$invoice->number} - {$reminder_template}"); } + }); - }); - - if ($invoice->invitations->count() > 0) { - event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(), $reminder_template)); - } - } - $invoice->service()->setReminder()->save(); - } else { - $invoice->next_send_date = null; - $invoice->save(); - } - + if ($invoice->invitations->count() > 0) { + event(new InvoiceWasEmailed($invoice->invitations->first(), $invoice->company, Ninja::eventVars(), $reminder_template)); + } + } + $invoice->service()->setReminder()->save(); + } else { + $invoice->next_send_date = null; + $invoice->save(); + } } /** diff --git a/app/Jobs/Util/SchedulerCheck.php b/app/Jobs/Util/SchedulerCheck.php index c20508089ed5..6c45287fc384 100644 --- a/app/Jobs/Util/SchedulerCheck.php +++ b/app/Jobs/Util/SchedulerCheck.php @@ -11,7 +11,6 @@ namespace App\Jobs\Util; -use App\Models\Account; use App\Utils\Ninja; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -40,8 +39,9 @@ class SchedulerCheck implements ShouldQueue set_time_limit(0); - if(Ninja::isHosted()) + if (Ninja::isHosted()) { return; + } if (config('ninja.app_version') != base_path('VERSION.txt')) { try { diff --git a/app/Jobs/Util/UpdateExchangeRates.php b/app/Jobs/Util/UpdateExchangeRates.php index 8a4c0cb7f91d..b6437627f721 100644 --- a/app/Jobs/Util/UpdateExchangeRates.php +++ b/app/Jobs/Util/UpdateExchangeRates.php @@ -63,28 +63,23 @@ class UpdateExchangeRates implements ShouldQueue $currencies = Currency::orderBy('name')->get(); Cache::forever('currencies', $currencies); - - } } else { - - $client = new Client(); - $response = $client->get($cc_endpoint); + $client = new Client(); + $response = $client->get($cc_endpoint); - $currency_api = json_decode($response->getBody()); + $currency_api = json_decode($response->getBody()); - /* Update all currencies */ - Currency::all()->each(function ($currency) use ($currency_api) { - $currency->exchange_rate = $currency_api->rates->{$currency->code}; - $currency->save(); - }); + /* Update all currencies */ + Currency::all()->each(function ($currency) use ($currency_api) { + $currency->exchange_rate = $currency_api->rates->{$currency->code}; + $currency->save(); + }); - /* Rebuild the cache */ - $currencies = Currency::orderBy('name')->get(); - - Cache::forever('currencies', $currencies); + /* Rebuild the cache */ + $currencies = Currency::orderBy('name')->get(); + Cache::forever('currencies', $currencies); } } - } diff --git a/app/Jobs/Util/VersionCheck.php b/app/Jobs/Util/VersionCheck.php index 552a5d566665..c21fb1d4ac63 100644 --- a/app/Jobs/Util/VersionCheck.php +++ b/app/Jobs/Util/VersionCheck.php @@ -42,7 +42,6 @@ class VersionCheck implements ShouldQueue } if (Ninja::isSelfHost()) { - nlog("latest version = {$version_file}"); $account = Account::first(); diff --git a/app/Jobs/Util/WebhookHandler.php b/app/Jobs/Util/WebhookHandler.php index fae6d59d3a21..fd5f5d228fb7 100644 --- a/app/Jobs/Util/WebhookHandler.php +++ b/app/Jobs/Util/WebhookHandler.php @@ -11,7 +11,6 @@ namespace App\Jobs\Util; -use App\Jobs\Util\WebhookSingle; use App\Libraries\MultiDB; use App\Models\Company; use App\Models\Webhook; @@ -22,7 +21,6 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; - class WebhookHandler implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; @@ -38,7 +36,9 @@ class WebhookHandler implements ShouldQueue * @param $event_id * @param $entity */ - public function __construct(private int $event_id, private $entity, private Company $company, private string $includes = ''){} + public function __construct(private int $event_id, private $entity, private Company $company, private string $includes = '') + { + } /** * Execute the job. @@ -47,7 +47,6 @@ class WebhookHandler implements ShouldQueue */ public function handle() { - MultiDB::setDb($this->company->db); //If the company is disabled, or if on hosted, the user is not a paid hosted user return early @@ -59,15 +58,11 @@ class WebhookHandler implements ShouldQueue ->where('event_id', $this->event_id) ->cursor() ->each(function ($subscription) { - - WebhookSingle::dispatch($subscription->id, $this->entity, $this->company->db, $this->includes); - - }); - + WebhookSingle::dispatch($subscription->id, $this->entity, $this->company->db, $this->includes); + }); } public function failed($exception = null) { - } } diff --git a/app/Jobs/Util/WebhookSingle.php b/app/Jobs/Util/WebhookSingle.php index 6c76c56b68c3..b780fcd523aa 100644 --- a/app/Jobs/Util/WebhookSingle.php +++ b/app/Jobs/Util/WebhookSingle.php @@ -11,13 +11,9 @@ namespace App\Jobs\Util; -use App\Jobs\Util\SystemLogger; use App\Libraries\MultiDB; -use App\Models\Client as ClientModel; use App\Models\Company; -use App\Models\Product; use App\Models\SystemLog; -use App\Models\Vendor; use App\Models\Webhook; use App\Transformers\ArraySerializer; use GuzzleHttp\Client; @@ -76,15 +72,15 @@ class WebhookSingle implements ShouldQueue */ public function handle() { - MultiDB::setDb($this->db); $subscription = Webhook::with('company')->find($this->subscription_id); - if($subscription) + if ($subscription) { nlog("firing event ID {$subscription->event_id}"); + } - if(!$subscription){ + if (!$subscription) { $this->fail(); nlog("failed to fire event, could not find webhook ID {$this->subscription_id}"); @@ -133,10 +129,7 @@ class WebhookSingle implements ShouldQueue $this->resolveClient(), $this->company ); - - } - catch(\GuzzleHttp\Exception\ConnectException $e){ - + } catch(\GuzzleHttp\Exception\ConnectException $e) { nlog("connection problem"); nlog($e->getCode()); nlog($e->getMessage()); @@ -149,12 +142,8 @@ class WebhookSingle implements ShouldQueue $this->resolveClient(), $this->company ); - - } - catch (BadResponseException $e) { - - if ($e->getResponse()->getStatusCode() >= 400 && $e->getResponse()->getStatusCode() < 500){ - + } catch (BadResponseException $e) { + if ($e->getResponse()->getStatusCode() >= 400 && $e->getResponse()->getStatusCode() < 500) { $message = "Server encountered a problem when connecting to {$subscription->target_url} => status code ". $e->getResponse()->getStatusCode(). " scheduling retry."; nlog($message); @@ -169,10 +158,9 @@ class WebhookSingle implements ShouldQueue ); $this->release($this->backoff()[$this->attempts()-1]); - } - if($e->getResponse()->getStatusCode() >= 500){ + if ($e->getResponse()->getStatusCode() >= 500) { nlog("endpoint returned a 500, failing"); $message = "Server encountered a problem when connecting to {$subscription->target_url} => status code ". $e->getResponse()->getStatusCode(). " no retry attempted."; @@ -189,11 +177,7 @@ class WebhookSingle implements ShouldQueue $this->fail(); return; } - - - } - catch (ServerException $e) { - + } catch (ServerException $e) { nlog("Server exception"); $error = json_decode($e->getResponse()->getBody()->getContents()); @@ -205,10 +189,7 @@ class WebhookSingle implements ShouldQueue $this->resolveClient(), $this->company ); - - } - catch (ClientException $e) { - + } catch (ClientException $e) { nlog("Client exception"); $error = json_decode($e->getResponse()->getBody()->getContents()); @@ -220,11 +201,7 @@ class WebhookSingle implements ShouldQueue $this->resolveClient(), $this->company ); - - - } - catch (\Exception $e) { - + } catch (\Exception $e) { nlog("Exception handler => " . $e->getMessage()); nlog($e->getCode()); @@ -238,22 +215,20 @@ class WebhookSingle implements ShouldQueue ); $this->release($this->backoff()[$this->attempts()-1]); - } } private function resolveClient() - { nlog(get_class($this->entity)); + { + nlog(get_class($this->entity)); //make sure it isn't an instance of the Client Model - if (!$this->entity instanceof \App\Models\Client && - !$this->entity instanceof \App\Models\Vendor && - !$this->entity instanceof \App\Models\Product && + if (!$this->entity instanceof \App\Models\Client && + !$this->entity instanceof \App\Models\Vendor && + !$this->entity instanceof \App\Models\Product && !$this->entity instanceof \App\Models\PurchaseOrder && $this->entity->client()->exists()) { - return $this->entity->client; - } @@ -262,8 +237,6 @@ class WebhookSingle implements ShouldQueue public function failed($exception = null) { - config(['queue.failed.driver' => null]); - } } diff --git a/app/Jobs/Vendor/CreatePurchaseOrderPdf.php b/app/Jobs/Vendor/CreatePurchaseOrderPdf.php index 718d96825c0e..83d62ebd7a49 100644 --- a/app/Jobs/Vendor/CreatePurchaseOrderPdf.php +++ b/app/Jobs/Vendor/CreatePurchaseOrderPdf.php @@ -13,27 +13,16 @@ namespace App\Jobs\Vendor; use App\Exceptions\FilePermissionsFailure; use App\Libraries\MultiDB; -use App\Models\Account; -use App\Models\Credit; -use App\Models\CreditInvitation; use App\Models\Design; -use App\Models\Invoice; -use App\Models\InvoiceInvitation; -use App\Models\Quote; -use App\Models\QuoteInvitation; -use App\Models\RecurringInvoice; -use App\Models\RecurringInvoiceInvitation; use App\Services\PdfMaker\Design as PdfDesignModel; use App\Services\PdfMaker\Design as PdfMakerDesign; use App\Services\PdfMaker\PdfMaker as PdfMakerService; use App\Utils\HostedPDF\NinjaPdf; -use App\Utils\HtmlEngine; use App\Utils\Ninja; use App\Utils\PhantomJS\Phantom; use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesInvoiceHtml; use App\Utils\Traits\NumberFormatter; -use App\Utils\Traits\Pdf\PDF; use App\Utils\Traits\Pdf\PageNumbering; use App\Utils\Traits\Pdf\PdfMaker; use App\Utils\VendorHtmlEngine; @@ -43,9 +32,7 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\Storage; -use setasign\Fpdi\PdfParser\StreamReader; class CreatePurchaseOrderPdf implements ShouldQueue { @@ -88,21 +75,16 @@ class CreatePurchaseOrderPdf implements ShouldQueue $this->vendor->load('company'); $this->disk = $disk ?? config('filesystems.default'); - } public function handle() { - $pdf = $this->rawPdf(); if ($pdf) { - - try{ + try { Storage::disk($this->disk)->put($this->file_path, $pdf); - } - catch(\Exception $e) - { + } catch(\Exception $e) { throw new FilePermissionsFailure($e->getMessage()); } } @@ -112,7 +94,6 @@ class CreatePurchaseOrderPdf implements ShouldQueue public function rawPdf() { - MultiDB::setDb($this->company->db); /* Forget the singleton*/ @@ -142,8 +123,9 @@ class CreatePurchaseOrderPdf implements ShouldQueue $design = Design::find($entity_design_id); /* Catch all in case migration doesn't pass back a valid design */ - if(!$design) + if (!$design) { $design = Design::find(2); + } $html = new VendorHtmlEngine($this->invitation); @@ -184,27 +166,23 @@ class CreatePurchaseOrderPdf implements ShouldQueue $pdf = null; try { - - if(config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja'){ + if (config('ninja.invoiceninja_hosted_pdf_generation') || config('ninja.pdf_generator') == 'hosted_ninja') { $pdf = (new NinjaPdf())->build($maker->getCompiledHTML(true)); $numbered_pdf = $this->pageNumbering($pdf, $this->company); - if($numbered_pdf) + if ($numbered_pdf) { $pdf = $numbered_pdf; - - } - else { - + } + } else { $pdf = $this->makePdf(null, null, $maker->getCompiledHTML(true)); $numbered_pdf = $this->pageNumbering($pdf, $this->company); - if($numbered_pdf) + if ($numbered_pdf) { $pdf = $numbered_pdf; - + } } - } catch (\Exception $e) { nlog(print_r($e->getMessage(), 1)); } @@ -217,13 +195,9 @@ class CreatePurchaseOrderPdf implements ShouldQueue $state = null; return $pdf; - } public function failed($e) { - } - - } diff --git a/app/Libraries/MultiDB.php b/app/Libraries/MultiDB.php index cfca4b64c675..98d78cd71688 100644 --- a/app/Libraries/MultiDB.php +++ b/app/Libraries/MultiDB.php @@ -461,19 +461,18 @@ class MultiDB */ public static function hasPhoneNumber(string $phone) : bool { - if (! config('ninja.db.multi_db_enabled')) + if (! config('ninja.db.multi_db_enabled')) { return Account::where('account_sms_verification_number', $phone)->where('account_sms_verified', true)->exists(); + } - $current_db = config('database.default'); + $current_db = config('database.default'); foreach (self::$dbs as $db) { - self::setDB($db); if ($exists = Account::where('account_sms_verification_number', $phone)->where('account_sms_verified', true)->exists()) { self::setDb($current_db); return true; } - } self::setDb($current_db); diff --git a/app/Listeners/Activity/RestoreClientActivity.php b/app/Listeners/Activity/RestoreClientActivity.php index 7f739585ac1c..709ff0f7d1d3 100644 --- a/app/Listeners/Activity/RestoreClientActivity.php +++ b/app/Listeners/Activity/RestoreClientActivity.php @@ -51,6 +51,5 @@ class RestoreClientActivity implements ShouldQueue $fields->activity_type_id = Activity::RESTORE_CLIENT; $this->activity_repo->save($fields, $event->client, $event->event_vars); - } } diff --git a/app/Listeners/Credit/CreditCreatedNotification.php b/app/Listeners/Credit/CreditCreatedNotification.php index ca8b569afd40..79dfa23d5358 100644 --- a/app/Listeners/Credit/CreditCreatedNotification.php +++ b/app/Listeners/Credit/CreditCreatedNotification.php @@ -49,7 +49,6 @@ class CreditCreatedNotification implements ShouldQueue /* We loop through each user and determine whether they need to be notified */ foreach ($event->company->company_users as $company_user) { - /* The User */ $user = $company_user->user; diff --git a/app/Listeners/Invoice/CreateInvoicePdf.php b/app/Listeners/Invoice/CreateInvoicePdf.php index 6921f0d93c7a..a50c13ef46a3 100644 --- a/app/Listeners/Invoice/CreateInvoicePdf.php +++ b/app/Listeners/Invoice/CreateInvoicePdf.php @@ -51,7 +51,6 @@ class CreateInvoicePdf implements ShouldQueue if (isset($event->credit)) { $event->credit->invitations->each(function ($invitation) { (new CreateEntityPdf($invitation->load('credit', 'contact.client.company')))->handle(); - }); } } diff --git a/app/Listeners/Invoice/InvoiceCreatedNotification.php b/app/Listeners/Invoice/InvoiceCreatedNotification.php index 1436c1b8d809..92f507490168 100644 --- a/app/Listeners/Invoice/InvoiceCreatedNotification.php +++ b/app/Listeners/Invoice/InvoiceCreatedNotification.php @@ -51,7 +51,6 @@ class InvoiceCreatedNotification implements ShouldQueue /* We loop through each user and determine whether they need to be notified */ foreach ($event->company->company_users as $company_user) { - /* The User */ $user = $company_user->user; diff --git a/app/Listeners/Invoice/InvoiceEmailFailedActivity.php b/app/Listeners/Invoice/InvoiceEmailFailedActivity.php index 1a80be2a01d3..ff6ed1106d50 100644 --- a/app/Listeners/Invoice/InvoiceEmailFailedActivity.php +++ b/app/Listeners/Invoice/InvoiceEmailFailedActivity.php @@ -19,7 +19,6 @@ use stdClass; class InvoiceEmailFailedActivity implements ShouldQueue { - // public $delay = 10; protected $activity_repo; diff --git a/app/Listeners/Invoice/InvoiceEmailedNotification.php b/app/Listeners/Invoice/InvoiceEmailedNotification.php index ffde68b795b1..66cb02145cf2 100644 --- a/app/Listeners/Invoice/InvoiceEmailedNotification.php +++ b/app/Listeners/Invoice/InvoiceEmailedNotification.php @@ -53,7 +53,6 @@ class InvoiceEmailedNotification implements ShouldQueue /* We loop through each user and determine whether they need to be notified */ foreach ($event->invitation->company->company_users as $company_user) { - /* The User */ $user = $company_user->user; diff --git a/app/Listeners/Invoice/InvoiceFailedEmailNotification.php b/app/Listeners/Invoice/InvoiceFailedEmailNotification.php index c0264f4ebc57..09d28f1870dc 100644 --- a/app/Listeners/Invoice/InvoiceFailedEmailNotification.php +++ b/app/Listeners/Invoice/InvoiceFailedEmailNotification.php @@ -16,17 +16,14 @@ use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; use App\Mail\Admin\EntityFailedSendObject; -use App\Notifications\Admin\EntitySentNotification; use App\Utils\Traits\Notifications\UserNotifies; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class InvoiceFailedEmailNotification { - use UserNotifies, Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct() diff --git a/app/Listeners/Invoice/InvoicePaidActivity.php b/app/Listeners/Invoice/InvoicePaidActivity.php index 1c7152c01ca4..998783e4c200 100644 --- a/app/Listeners/Invoice/InvoicePaidActivity.php +++ b/app/Listeners/Invoice/InvoicePaidActivity.php @@ -39,7 +39,6 @@ class InvoicePaidActivity implements ShouldQueue */ public function handle($event) { - MultiDB::setDb($event->company->db); $fields = new stdClass; @@ -54,8 +53,7 @@ class InvoicePaidActivity implements ShouldQueue $this->activity_repo->save($fields, $event->invoice, $event->event_vars); - if($event->invoice->subscription()->exists()) - { + if ($event->invoice->subscription()->exists()) { $event->invoice->subscription->service()->planPaid($event->invoice); } diff --git a/app/Listeners/Mail/MailSentListener.php b/app/Listeners/Mail/MailSentListener.php index 7eab2a2f813e..9978f076068b 100644 --- a/app/Listeners/Mail/MailSentListener.php +++ b/app/Listeners/Mail/MailSentListener.php @@ -20,7 +20,6 @@ use App\Models\RecurringInvoiceInvitation; use App\Utils\Ninja; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Events\MessageSent; -use Illuminate\Support\Facades\Notification; use Symfony\Component\Mime\MessageConverter; class MailSentListener implements ShouldQueue @@ -42,55 +41,50 @@ class MailSentListener implements ShouldQueue */ public function handle(MessageSent $event) { - if(!Ninja::isHosted()) + if (!Ninja::isHosted()) { return; + } $message_id = $event->sent->getMessageId(); $message = MessageConverter::toEmail($event->sent->getOriginalMessage()); - if(!$message->getHeaders()->get('x-invitation')) + if (!$message->getHeaders()->get('x-invitation')) { return; + } $invitation_key = $message->getHeaders()->get('x-invitation')->getValue(); - if($message_id && $invitation_key) - { - + if ($message_id && $invitation_key) { $invitation = $this->discoverInvitation($invitation_key); - if(!$invitation) + if (!$invitation) { return; + } $invitation->message_id = $message_id; - $invitation->save(); + $invitation->save(); } - } private function discoverInvitation($key) { - $invitation = false; - foreach (MultiDB::$dbs as $db) - { - - if($invitation = InvoiceInvitation::on($db)->where('key', $key)->first()) + foreach (MultiDB::$dbs as $db) { + if ($invitation = InvoiceInvitation::on($db)->where('key', $key)->first()) { return $invitation; - elseif($invitation = QuoteInvitation::on($db)->where('key', $key)->first()) + } elseif ($invitation = QuoteInvitation::on($db)->where('key', $key)->first()) { return $invitation; - elseif($invitation = RecurringInvoiceInvitation::on($db)->where('key', $key)->first()) + } elseif ($invitation = RecurringInvoiceInvitation::on($db)->where('key', $key)->first()) { return $invitation; - elseif($invitation = CreditInvitation::on($db)->where('key', $key)->first()) + } elseif ($invitation = CreditInvitation::on($db)->where('key', $key)->first()) { return $invitation; - elseif($invitation = PurchaseOrderInvitation::on($db)->where('key', $key)->first()) + } elseif ($invitation = PurchaseOrderInvitation::on($db)->where('key', $key)->first()) { return $invitation; - + } } return $invitation; - } - } diff --git a/app/Listeners/Misc/InvitationViewedListener.php b/app/Listeners/Misc/InvitationViewedListener.php index 7003a464d827..fb8d28afee29 100644 --- a/app/Listeners/Misc/InvitationViewedListener.php +++ b/app/Listeners/Misc/InvitationViewedListener.php @@ -16,12 +16,10 @@ use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; use App\Mail\Admin\EntityViewedObject; -use App\Notifications\Admin\EntityViewedNotification; use App\Utils\Ninja; use App\Utils\Traits\Notifications\UserNotifies; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Notification; class InvitationViewedListener implements ShouldQueue { diff --git a/app/Listeners/Payment/PaymentNotification.php b/app/Listeners/Payment/PaymentNotification.php index 40d4071250c5..1899c9ed35f1 100644 --- a/app/Listeners/Payment/PaymentNotification.php +++ b/app/Listeners/Payment/PaymentNotification.php @@ -16,11 +16,9 @@ use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; use App\Mail\Admin\EntityPaidObject; -use App\Notifications\Admin\NewPaymentNotification; use App\Utils\Ninja; use App\Utils\Traits\Notifications\UserNotifies; use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Support\Facades\Notification; class PaymentNotification implements ShouldQueue { @@ -62,7 +60,10 @@ class PaymentNotification implements ShouldQueue foreach ($payment->company->company_users as $company_user) { $user = $company_user->user; - $methods = $this->findUserEntityNotificationType($payment, $company_user, [ + $methods = $this->findUserEntityNotificationType( + $payment, + $company_user, + [ 'payment_success', 'payment_success_all', 'payment_success_user', diff --git a/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php b/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php index 802a82582530..d83b7223d573 100644 --- a/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php +++ b/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php @@ -15,9 +15,7 @@ use App\Jobs\Mail\NinjaMailer; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; -use App\Mail\Admin\EntityCreatedObject; use App\Mail\Admin\PurchaseOrderAcceptedObject; -use App\Notifications\Admin\EntitySentNotification; use App\Utils\Traits\Notifications\UserNotifies; use Illuminate\Contracts\Queue\ShouldQueue; @@ -50,7 +48,6 @@ class PurchaseOrderAcceptedListener implements ShouldQueue /* We loop through each user and determine whether they need to be notified */ foreach ($event->company->company_users as $company_user) { - /* The User */ $user = $company_user->user; diff --git a/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php b/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php index 3d22d4fb056e..6b7e146defed 100644 --- a/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php +++ b/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php @@ -37,7 +37,6 @@ class PurchaseOrderCreatedListener implements ShouldQueue */ public function handle(PurchaseOrderWasCreated $event) { - MultiDB::setDb($event->company->db); $first_notification_sent = true; @@ -51,7 +50,6 @@ class PurchaseOrderCreatedListener implements ShouldQueue /* We loop through each user and determine whether they need to be notified */ foreach ($event->company->company_users as $company_user) { - /* The User */ $user = $company_user->user; diff --git a/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php b/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php index 9def7f062112..22541380768c 100644 --- a/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php +++ b/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php @@ -53,7 +53,6 @@ class PurchaseOrderEmailedNotification implements ShouldQueue /* We loop through each user and determine whether they need to be notified */ foreach ($event->invitation->company->company_users as $company_user) { - /* The User */ $user = $company_user->user; diff --git a/app/Listeners/Quote/QuoteApprovedNotification.php b/app/Listeners/Quote/QuoteApprovedNotification.php index 47bb68867fc0..eae4d21e417a 100644 --- a/app/Listeners/Quote/QuoteApprovedNotification.php +++ b/app/Listeners/Quote/QuoteApprovedNotification.php @@ -15,9 +15,7 @@ use App\Jobs\Mail\NinjaMailer; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; -use App\Mail\Admin\EntityCreatedObject; use App\Mail\Admin\QuoteApprovedObject; -use App\Notifications\Admin\EntitySentNotification; use App\Utils\Traits\Notifications\UserNotifies; use Illuminate\Contracts\Queue\ShouldQueue; @@ -52,7 +50,6 @@ class QuoteApprovedNotification implements ShouldQueue /* We loop through each user and determine whether they need to be notified */ foreach ($event->company->company_users as $company_user) { - /* The User */ $user = $company_user->user; diff --git a/app/Listeners/Quote/QuoteCreatedNotification.php b/app/Listeners/Quote/QuoteCreatedNotification.php index dfecf70cd2bb..6c636605f127 100644 --- a/app/Listeners/Quote/QuoteCreatedNotification.php +++ b/app/Listeners/Quote/QuoteCreatedNotification.php @@ -51,7 +51,6 @@ class QuoteCreatedNotification implements ShouldQueue /* We loop through each user and determine whether they need to be notified */ foreach ($event->company->company_users as $company_user) { - /* The User */ $user = $company_user->user; diff --git a/app/Listeners/SendVerificationNotification.php b/app/Listeners/SendVerificationNotification.php index f6d722c5e1d2..d4c40f613d5f 100644 --- a/app/Listeners/SendVerificationNotification.php +++ b/app/Listeners/SendVerificationNotification.php @@ -11,14 +11,11 @@ namespace App\Listeners; -use App\Jobs\Mail\NinjaMailer; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; -use App\Mail\Admin\VerifyUserObject; use App\Mail\User\UserAdded; use App\Utils\Ninja; -use Exception; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Events\Dispatchable; diff --git a/app/Listeners/Subscription/AppStoreRenewSubscription.php b/app/Listeners/Subscription/AppStoreRenewSubscription.php index 958fd62929de..26c2b41df179 100644 --- a/app/Listeners/Subscription/AppStoreRenewSubscription.php +++ b/app/Listeners/Subscription/AppStoreRenewSubscription.php @@ -37,7 +37,6 @@ class AppStoreRenewSubscription implements ShouldQueue */ public function handle(DidRenew $event) { - $inapp_transaction_id = $event->getSubscriptionId(); //$subscription_id nlog("inapp upgrade processing for = {$inapp_transaction_id}"); @@ -46,23 +45,22 @@ class AppStoreRenewSubscription implements ShouldQueue $account = Account::where('inapp_transaction_id', $inapp_transaction_id)->first(); - if(!$account) { + if (!$account) { $ninja_company = Company::on('db-ninja-01')->find(config('ninja.ninja_default_company_id')); $ninja_company->notification(new RenewalFailureNotification("{$inapp_transaction_id}"))->ninja(); return; } - if($account->plan_term == 'month') + if ($account->plan_term == 'month') { $account->plan_expires = now()->addMonth(); - elseif($account->plan_term == 'year') + } elseif ($account->plan_term == 'year') { $account->plan_expires = now()->addYear(); + } $account->save(); // $server_notification = $event->getServerNotification(); // $subscription = $event->getSubscription(); // $subscription_identifier = $event->getSubscriptionIdentifier(); - } - -} \ No newline at end of file +} diff --git a/app/Listeners/User/UpdateUserLastLogin.php b/app/Listeners/User/UpdateUserLastLogin.php index 015375e4c8bb..4882cfa26554 100644 --- a/app/Listeners/User/UpdateUserLastLogin.php +++ b/app/Listeners/User/UpdateUserLastLogin.php @@ -16,7 +16,6 @@ use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\Util\SystemLogger; use App\Libraries\MultiDB; use App\Mail\User\UserLoggedIn; -use App\Models\Client; use App\Models\SystemLog; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Queue\ShouldQueue; diff --git a/app/Mail/Admin/AutoBillingFailureObject.php b/app/Mail/Admin/AutoBillingFailureObject.php index b40d6d964159..d56642b419ee 100644 --- a/app/Mail/Admin/AutoBillingFailureObject.php +++ b/app/Mail/Admin/AutoBillingFailureObject.php @@ -14,7 +14,6 @@ namespace App\Mail\Admin; use App\Models\Invoice; use App\Utils\HtmlEngine; use App\Utils\Ninja; -use App\Utils\Number; use App\Utils\Traits\MakesHash; use Illuminate\Support\Facades\App; use stdClass; diff --git a/app/Mail/Admin/EntityCreatedObject.php b/app/Mail/Admin/EntityCreatedObject.php index 918fc13ba8c0..c75c3ec73316 100644 --- a/app/Mail/Admin/EntityCreatedObject.php +++ b/app/Mail/Admin/EntityCreatedObject.php @@ -40,8 +40,8 @@ class EntityCreatedObject } /** - * @return stdClass - * @throws BindingResolutionException + * @return stdClass + * @throws BindingResolutionException */ public function build() :stdClass { @@ -55,32 +55,32 @@ class EntityCreatedObject $this->setTemplate(); $this->company = $this->entity->company; - if($this->entity_type == 'purchase_order') - { - + if ($this->entity_type == 'purchase_order') { $this->entity->load('vendor.company'); $mail_obj = new stdClass; $mail_obj->amount = Number::formatMoney($this->entity->amount, $this->entity->vendor); - $mail_obj->subject = ctrans($this->template_subject, - [ - 'vendor' => $this->entity->vendor->present()->name(), - 'purchase_order' => $this->entity->number, - ] - ); + $mail_obj->subject = ctrans( + $this->template_subject, + [ + 'vendor' => $this->entity->vendor->present()->name(), + 'purchase_order' => $this->entity->number, + ] + ); $mail_obj->markdown = 'email.admin.generic'; $mail_obj->tag = $this->company->company_key; $mail_obj->data = [ 'title' => $mail_obj->subject, - 'message' => ctrans($this->template_body, - [ - 'amount' => $mail_obj->amount, - 'vendor' => $this->entity->vendor->present()->name(), - 'purchase_order' => $this->entity->number, - ] - ), + 'message' => ctrans( + $this->template_body, + [ + 'amount' => $mail_obj->amount, + 'vendor' => $this->entity->vendor->present()->name(), + 'purchase_order' => $this->entity->number, + ] + ), 'url' => $this->entity->invitations()->first()->getAdminLink(), 'button' => ctrans("texts.view_{$this->entity_type}"), 'signature' => $this->company->settings->email_signature, @@ -88,11 +88,7 @@ class EntityCreatedObject 'settings' => $this->company->settings, 'whitelabel' => $this->company->account->isPaid() ? true : false, ]; - - - } - else { - + } else { $this->entity->load('client.country', 'client.company'); $this->client = $this->entity->client; @@ -102,7 +98,6 @@ class EntityCreatedObject $mail_obj->data = $this->getData(); $mail_obj->markdown = 'email.admin.generic'; $mail_obj->tag = $this->entity->company->company_key; - } return $mail_obj; @@ -110,7 +105,6 @@ class EntityCreatedObject private function setTemplate() { - switch ($this->entity_type) { case 'invoice': $this->template_subject = 'texts.notification_invoice_created_subject'; @@ -135,7 +129,7 @@ class EntityCreatedObject } } - private function getAmount() + private function getAmount() { return Number::formatMoney($this->entity->amount, $this->entity->client); } @@ -155,13 +149,13 @@ class EntityCreatedObject private function getMessage() { return ctrans( - $this->template_body, - [ - 'amount' => $this->getAmount(), - 'client' => $this->client->present()->name(), - 'invoice' => $this->entity->number, - ] - ); + $this->template_body, + [ + 'amount' => $this->getAmount(), + 'client' => $this->client->present()->name(), + 'invoice' => $this->entity->number, + ] + ); } private function getData() diff --git a/app/Mail/Admin/EntityFailedSendObject.php b/app/Mail/Admin/EntityFailedSendObject.php index dad2846c4d6c..e51413e42b79 100644 --- a/app/Mail/Admin/EntityFailedSendObject.php +++ b/app/Mail/Admin/EntityFailedSendObject.php @@ -15,7 +15,7 @@ use App\Utils\HtmlEngine; use App\Utils\Ninja; use App\Utils\Number; use Illuminate\Support\Facades\App; - use stdClass; +use stdClass; class EntityFailedSendObject { diff --git a/app/Mail/Admin/EntitySentObject.php b/app/Mail/Admin/EntitySentObject.php index 9eb7717bd102..c3bc4eaa503e 100644 --- a/app/Mail/Admin/EntitySentObject.php +++ b/app/Mail/Admin/EntitySentObject.php @@ -58,12 +58,11 @@ class EntitySentObject $this->setTemplate(); - if($this->template == 'purchase_order') - { - + if ($this->template == 'purchase_order') { $mail_obj = new stdClass; $mail_obj->amount = Number::formatMoney($this->entity->amount, $this->entity->vendor); - $mail_obj->subject = ctrans($this->template_subject, + $mail_obj->subject = ctrans( + $this->template_subject, [ 'vendor' => $this->contact->vendor->present()->name(), 'purchase_order' => $this->entity->number, @@ -71,13 +70,14 @@ class EntitySentObject ); $mail_obj->data = [ 'title' => $mail_obj->subject, - 'message' => ctrans($this->template_body, - [ - 'amount' => $mail_obj->amount, - 'vendor' => $this->contact->vendor->present()->name(), - 'purchase_order' => $this->entity->number, - ] - ), + 'message' => ctrans( + $this->template_body, + [ + 'amount' => $mail_obj->amount, + 'vendor' => $this->contact->vendor->present()->name(), + 'purchase_order' => $this->entity->number, + ] + ), 'url' => $this->invitation->getAdminLink(), 'button' => ctrans("texts.view_{$this->entity_type}"), 'signature' => $this->company->settings->email_signature, @@ -87,17 +87,13 @@ class EntitySentObject ]; $mail_obj->markdown = 'email.admin.generic'; $mail_obj->tag = $this->company->company_key; - - } - else { - + } else { $mail_obj = new stdClass; $mail_obj->amount = $this->getAmount(); $mail_obj->subject = $this->getSubject(); $mail_obj->data = $this->getData(); $mail_obj->markdown = 'email.admin.generic'; $mail_obj->tag = $this->company->company_key; - } return $mail_obj; @@ -167,13 +163,13 @@ class EntitySentObject private function getMessage() { return ctrans( - $this->template_body, - [ - 'amount' => $this->getAmount(), - 'client' => $this->contact->client->present()->name(), - 'invoice' => $this->entity->number, - ] - ); + $this->template_body, + [ + 'amount' => $this->getAmount(), + 'client' => $this->contact->client->present()->name(), + 'invoice' => $this->entity->number, + ] + ); } private function getData() diff --git a/app/Mail/Admin/InventoryNotificationObject.php b/app/Mail/Admin/InventoryNotificationObject.php index bc74e85a2200..3a414c8dacdb 100644 --- a/app/Mail/Admin/InventoryNotificationObject.php +++ b/app/Mail/Admin/InventoryNotificationObject.php @@ -12,11 +12,9 @@ namespace App\Mail\Admin; -use App\Mail\Engine\PaymentEmailEngine; use App\Models\Company; use App\Models\Product; use App\Utils\Ninja; -use App\Utils\Number; use Illuminate\Support\Facades\App; use stdClass; diff --git a/app/Mail/Admin/PaymentFailureObject.php b/app/Mail/Admin/PaymentFailureObject.php index 5c2c2e6b2dc2..8b484be26ee8 100644 --- a/app/Mail/Admin/PaymentFailureObject.php +++ b/app/Mail/Admin/PaymentFailureObject.php @@ -13,7 +13,6 @@ namespace App\Mail\Admin; use App\Models\Client; use App\Models\Company; -use App\Models\Invoice; use App\Models\PaymentHash; use App\Utils\Ninja; use App\Utils\Number; @@ -110,7 +109,8 @@ class PaymentFailureObject 'client' => $this->client->present()->name(), 'invoice' => $this->getDescription(), 'amount' => Number::formatMoney($this->amount, $this->client), - ]), + ] + ), 'signature' => $signature, 'logo' => $this->company->present()->logo(), 'settings' => $this->client->getMergedSettings(), diff --git a/app/Mail/BouncedEmail.php b/app/Mail/BouncedEmail.php index 71a837c5ff59..891e353ccdb8 100644 --- a/app/Mail/BouncedEmail.php +++ b/app/Mail/BouncedEmail.php @@ -11,11 +11,7 @@ namespace App\Mail; -use App\Models\User; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; -use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; class BouncedEmail extends Mailable diff --git a/app/Mail/Client/ClientStatement.php b/app/Mail/Client/ClientStatement.php index 80ea6d52788e..ec34f05d77c0 100644 --- a/app/Mail/Client/ClientStatement.php +++ b/app/Mail/Client/ClientStatement.php @@ -11,23 +11,21 @@ namespace App\Mail\Client; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Attachment; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; -use Illuminate\Queue\SerializesModels; class ClientStatement extends Mailable { - /** * Create a new message instance. * * @return void */ - public function __construct(public array $data){} + public function __construct(public array $data) + { + } /** * Get the message envelope. @@ -79,16 +77,12 @@ class ClientStatement extends Mailable { $array_of_attachments = []; - foreach($this->data['attachments'] as $attachment) - { - - $array_of_attachments[] = + foreach ($this->data['attachments'] as $attachment) { + $array_of_attachments[] = Attachment::fromData(fn () => base64_decode($attachment['file']), $attachment['name']) ->withMime('application/pdf'); - } return $array_of_attachments; - } } diff --git a/app/Mail/ContactPasswordlessLogin.php b/app/Mail/ContactPasswordlessLogin.php index 4bcf5278a098..f7779d874c31 100644 --- a/app/Mail/ContactPasswordlessLogin.php +++ b/app/Mail/ContactPasswordlessLogin.php @@ -14,10 +14,7 @@ namespace App\Mail; use App\Models\Company; use App\Utils\ClientPortal\MagicLink; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; -use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; class ContactPasswordlessLogin extends Mailable diff --git a/app/Mail/DownloadBackup.php b/app/Mail/DownloadBackup.php index a28f118002ca..ffc89d21d000 100644 --- a/app/Mail/DownloadBackup.php +++ b/app/Mail/DownloadBackup.php @@ -13,9 +13,7 @@ namespace App\Mail; use App\Models\Company; -use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; -use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; class DownloadBackup extends Mailable diff --git a/app/Mail/DownloadReport.php b/app/Mail/DownloadReport.php index 9a713809bef2..f2c53725d777 100644 --- a/app/Mail/DownloadReport.php +++ b/app/Mail/DownloadReport.php @@ -13,7 +13,6 @@ namespace App\Mail; use App\Models\Company; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; diff --git a/app/Mail/Engine/CreditEmailEngine.php b/app/Mail/Engine/CreditEmailEngine.php index 19989905bb18..2bf98f78410d 100644 --- a/app/Mail/Engine/CreditEmailEngine.php +++ b/app/Mail/Engine/CreditEmailEngine.php @@ -17,7 +17,6 @@ use App\Utils\HtmlEngine; use App\Utils\Ninja; use App\Utils\Number; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\URL; class CreditEmailEngine extends BaseEmailEngine @@ -96,16 +95,15 @@ class CreditEmailEngine extends BaseEmailEngine } $text_body = trans( - 'texts.credit_message', - [ - 'credit' => $this->credit->number, - 'company' => $this->credit->company->present()->name(), - 'amount' => Number::formatMoney($this->credit->balance, $this->client), - ], - null, - $this->client->locale() - - )."\n\n".$this->invitation->getLink(); + 'texts.credit_message', + [ + 'credit' => $this->credit->number, + 'company' => $this->credit->company->present()->name(), + 'amount' => Number::formatMoney($this->credit->balance, $this->client), + ], + null, + $this->client->locale() + )."\n\n".$this->invitation->getLink(); $this->setTemplate($this->client->getSetting('email_style')) ->setContact($this->contact) @@ -125,31 +123,28 @@ class CreditEmailEngine extends BaseEmailEngine // $this->setAttachments([$this->credit->pdf_file_path($this->invitation)]); // } - $pdf = ((new CreateRawPdf($this->invitation, $this->invitation->company->db))->handle()); - - $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->credit->numberFormatter().'.pdf']]); - + $pdf = ((new CreateRawPdf($this->invitation, $this->invitation->company->db))->handle()); + $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->credit->numberFormatter().'.pdf']]); } //attach third party documents if ($this->client->getSetting('document_email_attachment') !== false && $this->credit->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - // Storage::url foreach ($this->credit->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, 'file' => base64_encode($document->getFile())]]); + } else { + $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, 'file' => base64_encode($document->getFile())]]); + } } foreach ($this->credit->company->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, 'file' => base64_encode($document->getFile())]]); + } else { + $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, 'file' => base64_encode($document->getFile())]]); + } } } diff --git a/app/Mail/Engine/InvoiceEmailEngine.php b/app/Mail/Engine/InvoiceEmailEngine.php index 598db7a00a3d..9ba08c127f86 100644 --- a/app/Mail/Engine/InvoiceEmailEngine.php +++ b/app/Mail/Engine/InvoiceEmailEngine.php @@ -12,7 +12,6 @@ namespace App\Mail\Engine; use App\DataMapper\EmailTemplateDefaults; -use App\Jobs\Entity\CreateEntityPdf; use App\Jobs\Entity\CreateRawPdf; use App\Models\Account; use App\Models\Expense; @@ -22,7 +21,6 @@ use App\Utils\Ninja; use App\Utils\Number; use App\Utils\Traits\MakesHash; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\URL; class InvoiceEmailEngine extends BaseEmailEngine @@ -86,15 +84,15 @@ class InvoiceEmailEngine extends BaseEmailEngine } $text_body = trans( - 'texts.invoice_message', - [ - 'invoice' => $this->invoice->number, - 'company' => $this->invoice->company->present()->name(), - 'amount' => Number::formatMoney($this->invoice->balance, $this->client), - ], - null, - $this->client->locale() - )."\n\n".$this->invitation->getLink(); + 'texts.invoice_message', + [ + 'invoice' => $this->invoice->number, + 'company' => $this->invoice->company->present()->name(), + 'amount' => Number::formatMoney($this->invoice->balance, $this->client), + ], + null, + $this->client->locale() + )."\n\n".$this->invitation->getLink(); if (is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) { $subject_template = $this->template_data['subject']; @@ -128,42 +126,38 @@ class InvoiceEmailEngine extends BaseEmailEngine ->setTextBody($text_body); if ($this->client->getSetting('pdf_email_attachment') !== false && $this->invoice->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { - $pdf = ((new CreateRawPdf($this->invitation, $this->invitation->company->db))->handle()); - $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->invoice->numberFormatter().'.pdf']]); + $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->invoice->numberFormatter().'.pdf']]); } //attach third party documents if ($this->client->getSetting('document_email_attachment') !== false && $this->invoice->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - - - if($this->invoice->recurring_invoice()->exists()) - { + if ($this->invoice->recurring_invoice()->exists()) { foreach ($this->invoice->recurring_invoice->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]); + } else { + $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]); + } } } // Storage::url foreach ($this->invoice->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]); + } else { + $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]); + } } foreach ($this->invoice->company->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]); + } else { + $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]); + } } $line_items = $this->invoice->line_items; @@ -181,12 +175,11 @@ class InvoiceEmailEngine extends BaseEmailEngine ->cursor() ->each(function ($expense) { foreach ($expense->documents as $document) { - - if($document->size > $this->max_attachment_size) - $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]); - + if ($document->size > $this->max_attachment_size) { + $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); + } else { + $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]); + } } }); } @@ -202,17 +195,15 @@ class InvoiceEmailEngine extends BaseEmailEngine ->cursor() ->each(function ($task) { foreach ($task->documents as $document) { - - if($document->size > $this->max_attachment_size) - $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]); - + if ($document->size > $this->max_attachment_size) { + $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); + } else { + $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]); + } } }); } } - } return $this; diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php index 8213215fbc9f..b32cfb4efe65 100644 --- a/app/Mail/Engine/PaymentEmailEngine.php +++ b/app/Mail/Engine/PaymentEmailEngine.php @@ -90,28 +90,22 @@ class PaymentEmailEngine extends BaseEmailEngine ->setViewText(''); if ($this->client->getSetting('pdf_email_attachment') !== false && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { - $this->payment->invoices->each(function ($invoice) { - $pdf = ((new CreateRawPdf($invoice->invitations->first(), $invoice->company->db))->handle()); - $this->setAttachments([['file' => base64_encode($pdf), 'name' => $invoice->numberFormatter().'.pdf']]); + $this->setAttachments([['file' => base64_encode($pdf), 'name' => $invoice->numberFormatter().'.pdf']]); //attach invoice documents also to payments - if ($this->client->getSetting('document_email_attachment') !== false) - { + if ($this->client->getSetting('document_email_attachment') !== false) { foreach ($invoice->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]); + } else { + $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]); + } } } - }); - - } return $this; @@ -268,11 +262,11 @@ class PaymentEmailEngine extends BaseEmailEngine $data['$invoices.po_number'] = ['value' => $this->formatInvoiceField('po_number'), 'label' => ctrans('texts.invoices')]; - if($this->payment->status_id == 4) { + if ($this->payment->status_id == 4) { $data['$status_logo'] = ['value' => '
' . ctrans('texts.paid') .'
', 'label' => '']; - } - else + } else { $data['$status_logo'] = ['value' => '', 'label' => '']; + } $arrKeysLength = array_map('strlen', array_keys($data)); @@ -286,21 +280,20 @@ class PaymentEmailEngine extends BaseEmailEngine $invoicex = ''; foreach ($this->payment->invoices as $invoice) { - $invoice_field = $invoice->{$field}; - if(in_array($field, ['amount', 'balance'])) + if (in_array($field, ['amount', 'balance'])) { $invoice_field = Number::formatMoney($invoice_field, $this->client); + } - if($field == 'due_date') + if ($field == 'due_date') { $invoice_field = $this->translateDate($invoice_field, $this->client->date_format(), $this->client->locale()); + } $invoicex .= ctrans('texts.invoice_number_short') . "{$invoice->number} {$invoice_field}"; - } return $invoicex; - } private function formatInvoice() @@ -341,15 +334,14 @@ class PaymentEmailEngine extends BaseEmailEngine $invoice_list = '

'; foreach ($this->payment->invoices as $invoice) { - - if(strlen($invoice->po_number) > 1) + if (strlen($invoice->po_number) > 1) { $invoice_list .= ctrans('texts.po_number')." {$invoice->po_number}
"; + } $invoice_list .= ctrans('texts.invoice_number_short')." {$invoice->number}
"; $invoice_list .= ctrans('texts.invoice_amount').' '.Number::formatMoney($invoice->pivot->amount, $this->client).'
'; $invoice_list .= ctrans('texts.invoice_balance').' '.Number::formatMoney($invoice->fresh()->balance, $this->client).'
'; $invoice_list .= '-----
'; - } return $invoice_list; @@ -406,5 +398,4 @@ class PaymentEmailEngine extends BaseEmailEngine
'; } - } diff --git a/app/Mail/Engine/PurchaseOrderEmailEngine.php b/app/Mail/Engine/PurchaseOrderEmailEngine.php index 4f4722381e02..4d104cc2d149 100644 --- a/app/Mail/Engine/PurchaseOrderEmailEngine.php +++ b/app/Mail/Engine/PurchaseOrderEmailEngine.php @@ -12,21 +12,16 @@ namespace App\Mail\Engine; use App\DataMapper\EmailTemplateDefaults; -use App\Jobs\Entity\CreateEntityPdf; use App\Jobs\Vendor\CreatePurchaseOrderPdf; use App\Models\Account; -use App\Models\Expense; use App\Models\PurchaseOrder; -use App\Models\Task; use App\Models\Vendor; -use App\Models\VendorContact; use App\Utils\HtmlEngine; use App\Utils\Ninja; use App\Utils\Number; use App\Utils\Traits\MakesHash; use App\Utils\VendorHtmlEngine; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\URL; class PurchaseOrderEmailEngine extends BaseEmailEngine @@ -85,15 +80,15 @@ class PurchaseOrderEmailEngine extends BaseEmailEngine $body_template .= '
$view_button
'; } $text_body = trans( - 'texts.purchase_order_message', - [ - 'purchase_order' => $this->purchase_order->number, - 'company' => $this->purchase_order->company->present()->name(), - 'amount' => Number::formatMoney($this->purchase_order->balance, $this->vendor), - ], - null, - $this->vendor->company->locale() - )."\n\n".$this->invitation->getLink(); + 'texts.purchase_order_message', + [ + 'purchase_order' => $this->purchase_order->number, + 'company' => $this->purchase_order->company->present()->name(), + 'amount' => Number::formatMoney($this->purchase_order->balance, $this->vendor), + ], + null, + $this->vendor->company->locale() + )."\n\n".$this->invitation->getLink(); if (is_array($this->template_data) && array_key_exists('subject', $this->template_data) && strlen($this->template_data['subject']) > 0) { $subject_template = $this->template_data['subject']; @@ -127,33 +122,29 @@ class PurchaseOrderEmailEngine extends BaseEmailEngine ->setTextBody($text_body); if ($this->vendor->getSetting('pdf_email_attachment') !== false && $this->purchase_order->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { - $pdf = (new CreatePurchaseOrderPdf($this->invitation))->rawPdf(); - $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->purchase_order->numberFormatter().'.pdf']]); - + $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->purchase_order->numberFormatter().'.pdf']]); } //attach third party documents if ($this->vendor->getSetting('document_email_attachment') !== false && $this->purchase_order->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - // Storage::url foreach ($this->purchase_order->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else + } else { $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); + } } foreach ($this->purchase_order->company->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else + } else { $this->setAttachments([['path' => $document->filePath(), 'name' => $document->name, 'mime' => null]]); + } } - } return $this; diff --git a/app/Mail/Engine/QuoteEmailEngine.php b/app/Mail/Engine/QuoteEmailEngine.php index 03a3be65f988..440624a3975f 100644 --- a/app/Mail/Engine/QuoteEmailEngine.php +++ b/app/Mail/Engine/QuoteEmailEngine.php @@ -17,7 +17,6 @@ use App\Utils\HtmlEngine; use App\Utils\Ninja; use App\Utils\Number; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; use Illuminate\Support\Facades\URL; class QuoteEmailEngine extends BaseEmailEngine @@ -95,16 +94,15 @@ class QuoteEmailEngine extends BaseEmailEngine } $text_body = trans( - 'texts.quote_message', - [ - 'quote' => $this->quote->number, - 'company' => $this->quote->company->present()->name(), - 'amount' => Number::formatMoney($this->quote->amount, $this->client), - ], - null, - $this->client->locale() - - )."\n\n".$this->invitation->getLink(); + 'texts.quote_message', + [ + 'quote' => $this->quote->number, + 'company' => $this->quote->company->present()->name(), + 'amount' => Number::formatMoney($this->quote->amount, $this->client), + ], + null, + $this->client->locale() + )."\n\n".$this->invitation->getLink(); $this->setTemplate($this->client->getSetting('email_style')) ->setContact($this->contact) @@ -118,30 +116,28 @@ class QuoteEmailEngine extends BaseEmailEngine ->setTextBody($text_body); if ($this->client->getSetting('pdf_email_attachment') !== false && $this->quote->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { - $pdf = ((new CreateRawPdf($this->invitation, $this->invitation->company->db))->handle()); - $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->quote->numberFormatter().'.pdf']]); + $this->setAttachments([['file' => base64_encode($pdf), 'name' => $this->quote->numberFormatter().'.pdf']]); } //attach third party documents if ($this->client->getSetting('document_email_attachment') !== false && $this->quote->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - // Storage::url foreach ($this->quote->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]); + } else { + $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]); + } } foreach ($this->quote->company->documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->setAttachmentLinks([" $document->hash]) ."'>". $document->name .""]); - else - $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => NULL, ]]); + } else { + $this->setAttachments([['file' => base64_encode($document->getFile()), 'path' => $document->filePath(), 'name' => $document->name, 'mime' => null, ]]); + } } } diff --git a/app/Mail/Import/CsvImportCompleted.php b/app/Mail/Import/CsvImportCompleted.php index 73944eef34e5..ac00b1a31c9e 100644 --- a/app/Mail/Import/CsvImportCompleted.php +++ b/app/Mail/Import/CsvImportCompleted.php @@ -34,7 +34,7 @@ class CsvImportCompleted extends Mailable * 'company' => Company $company, * 'entity_count' => (array) $entity_count * ]; - */ + */ public $data; /** diff --git a/app/Mail/MigrationCompleted.php b/app/Mail/MigrationCompleted.php index daddca816c82..43e2672789e0 100644 --- a/app/Mail/MigrationCompleted.php +++ b/app/Mail/MigrationCompleted.php @@ -40,7 +40,6 @@ class MigrationCompleted extends Mailable */ public function build() { - MultiDB::setDb($this->db); $this->company = Company::find($this->company_id); diff --git a/app/Mail/MigrationFailed.php b/app/Mail/MigrationFailed.php index 44be3af46b41..f235cdc1dd3b 100644 --- a/app/Mail/MigrationFailed.php +++ b/app/Mail/MigrationFailed.php @@ -51,8 +51,9 @@ class MigrationFailed extends Mailable $special_message = ''; - if($this->exception instanceof ClientHostedMigrationException) + if ($this->exception instanceof ClientHostedMigrationException) { $special_message = $this->content; + } return $this ->from(config('mail.from.address'), config('mail.from.name')) diff --git a/app/Mail/Ninja/EmailQuotaExceeded.php b/app/Mail/Ninja/EmailQuotaExceeded.php index 859ef0f11200..6746c3a1d2d6 100644 --- a/app/Mail/Ninja/EmailQuotaExceeded.php +++ b/app/Mail/Ninja/EmailQuotaExceeded.php @@ -11,9 +11,7 @@ namespace App\Mail\Ninja; -use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; -use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; class EmailQuotaExceeded extends Mailable diff --git a/app/Mail/Ninja/GmailTokenInvalid.php b/app/Mail/Ninja/GmailTokenInvalid.php index 116afca8663d..98e401506249 100644 --- a/app/Mail/Ninja/GmailTokenInvalid.php +++ b/app/Mail/Ninja/GmailTokenInvalid.php @@ -11,9 +11,7 @@ namespace App\Mail\Ninja; -use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; -use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; class GmailTokenInvalid extends Mailable diff --git a/app/Mail/RecurringInvoice/ClientContactRequestCancellationObject.php b/app/Mail/RecurringInvoice/ClientContactRequestCancellationObject.php index ed46041a30fb..0ae4682d1c70 100644 --- a/app/Mail/RecurringInvoice/ClientContactRequestCancellationObject.php +++ b/app/Mail/RecurringInvoice/ClientContactRequestCancellationObject.php @@ -18,8 +18,9 @@ use Illuminate\Support\Facades\App; class ClientContactRequestCancellationObject { - - public function __construct(public RecurringInvoice $recurring_invoice, public ClientContact $client_contact, private bool $gateway_refund_attempted){} + public function __construct(public RecurringInvoice $recurring_invoice, public ClientContact $client_contact, private bool $gateway_refund_attempted) + { + } public function build() { @@ -32,8 +33,9 @@ class ClientContactRequestCancellationObject $t->replace(Ninja::transformTranslations($this->company->settings)); $content = ctrans('texts.recurring_cancellation_request_body', ['contact' => $this->client_contact->present()->name(), 'client' => $this->client_contact->client->present()->name(), 'invoice' => $this->recurring_invoice->number]); - if($this->gateway_refund_attempted) + if ($this->gateway_refund_attempted) { $content .= "\n\n" . ctrans('texts.status') . " : " . ctrans('texts.payment_status_6'); + } $data = [ 'title' => ctrans('texts.recurring_cancellation_request', ['contact' => $this->client_contact->present()->name()]), diff --git a/app/Mail/SupportMessageSent.php b/app/Mail/SupportMessageSent.php index 7258aa19bf01..ea8f34f49373 100644 --- a/app/Mail/SupportMessageSent.php +++ b/app/Mail/SupportMessageSent.php @@ -6,9 +6,9 @@ use App\Utils\Ninja; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; +use Illuminate\Support\Carbon; use LimitIterator; use SplFileObject; -use Illuminate\Support\Carbon; class SupportMessageSent extends Mailable { @@ -73,8 +73,9 @@ class SupportMessageSent extends Mailable $plan_status = ''; - if($account->plan_expires && Carbon::parse($account->plan_expires)->lt(now())) + if ($account->plan_expires && Carbon::parse($account->plan_expires)->lt(now())) { $plan_status = 'Plan Expired :: '; + } if (Ninja::isHosted()) { $subject = "{$priority}Hosted-{$db}-{$is_large}{$platform}{$migrated}{$trial} :: {$plan} :: {$plan_status} ".date('M jS, g:ia'); diff --git a/app/Mail/TemplateEmail.php b/app/Mail/TemplateEmail.php index f3550899aee5..6d8dd1ffaac8 100644 --- a/app/Mail/TemplateEmail.php +++ b/app/Mail/TemplateEmail.php @@ -11,20 +11,13 @@ namespace App\Mail; -use App\Jobs\Entity\CreateEntityPdf; use App\Jobs\Invoice\CreateUbl; use App\Models\Account; -use App\Models\Client; use App\Models\ClientContact; -use App\Models\User; use App\Services\PdfMaker\Designs\Utilities\DesignHelpers; use App\Utils\HtmlEngine; use App\Utils\Ninja; -use App\Utils\TemplateEngine; -use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; -use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Storage; class TemplateEmail extends Mailable { @@ -52,34 +45,32 @@ class TemplateEmail extends Mailable } /** - * Supports inline attachments for large + * Supports inline attachments for large * attachments in custom designs - * + * * @return string */ private function buildLinksForCustomDesign(): string { $links = $this->build_email->getAttachmentLinks(); - if(count($links) == 0) + if (count($links) == 0) { return ''; + } $link_string = '
    '; - foreach($this->build_email->getAttachmentLinks() as $link) - { + foreach ($this->build_email->getAttachmentLinks() as $link) { $link_string .= "
  • {$link}
  • "; } $link_string .= '
'; return $link_string; - } public function build() { - $template_name = 'email.template.'.$this->build_email->getTemplate(); if ($this->build_email->getTemplate() == 'light' || $this->build_email->getTemplate() == 'dark') { @@ -119,7 +110,7 @@ class TemplateEmail extends Mailable if (Ninja::isHosted()) { $bccs = explode(',', str_replace(' ', '', $settings->bcc_email)); $this->bcc(array_slice($bccs, 0, 2)); - //$this->bcc(reset($bccs)); //remove whitespace if any has been inserted. + //$this->bcc(reset($bccs)); //remove whitespace if any has been inserted. } else { $this->bcc(explode(',', str_replace(' ', '', $settings->bcc_email))); }//remove whitespace if any has been inserted. @@ -147,10 +138,11 @@ class TemplateEmail extends Mailable ]); foreach ($this->build_email->getAttachments() as $file) { - if(array_key_exists('file', $file)) + if (array_key_exists('file', $file)) { $this->attachData(base64_decode($file['file']), $file['name']); - else + } else { $this->attach($file['path'], ['as' => $file['name'], 'mime' => null]); + } } if ($this->invitation && $this->invitation->invoice && $settings->ubl_email_attachment && $this->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { diff --git a/app/Mail/VendorTemplateEmail.php b/app/Mail/VendorTemplateEmail.php index 4ea8e8493b34..2ac0987b8045 100644 --- a/app/Mail/VendorTemplateEmail.php +++ b/app/Mail/VendorTemplateEmail.php @@ -11,21 +11,10 @@ namespace App\Mail; -use App\Jobs\Invoice\CreateUbl; -use App\Jobs\Vendor\CreatePurchaseOrderPdf; -use App\Models\Account; -use App\Models\Client; -use App\Models\User; use App\Models\VendorContact; use App\Services\PdfMaker\Designs\Utilities\DesignHelpers; -use App\Utils\HtmlEngine; -use App\Utils\Ninja; -use App\Utils\TemplateEngine; use App\Utils\VendorHtmlEngine; -use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; -use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Facades\Storage; class VendorTemplateEmail extends Mailable { @@ -53,29 +42,28 @@ class VendorTemplateEmail extends Mailable } /** - * Supports inline attachments for large + * Supports inline attachments for large * attachments in custom designs - * + * * @return string */ private function buildLinksForCustomDesign(): string { $links = $this->build_email->getAttachmentLinks(); - if(count($links) == 0) + if (count($links) == 0) { return ''; + } $link_string = '
    '; - foreach($this->build_email->getAttachmentLinks() as $link) - { + foreach ($this->build_email->getAttachmentLinks() as $link) { $link_string .= "
  • {$link}
  • "; } $link_string .= '
'; return $link_string; - } public function build() @@ -140,12 +128,11 @@ class VendorTemplateEmail extends Mailable foreach ($this->build_email->getAttachments() as $file) { - - if(array_key_exists('file', $file)) + if (array_key_exists('file', $file)) { $this->attachData(base64_decode($file['file']), $file['name']); - else + } else { $this->attach($file['path'], ['as' => $file['name'], 'mime' => null]); - + } } return $this; diff --git a/app/Models/Account.php b/app/Models/Account.php index a4ec1d5d568b..ff66c29599c4 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -157,8 +157,9 @@ class Account extends BaseModel public function getPlan() { - if(Carbon::parse($this->plan_expires)->lt(now())) + if (Carbon::parse($this->plan_expires)->lt(now())) { return ''; + } return $this->plan ?: ''; } @@ -169,7 +170,6 @@ class Account extends BaseModel $self_host = ! Ninja::isNinja(); switch ($feature) { - case self::FEATURE_TASKS: case self::FEATURE_EXPENSES: case self::FEATURE_QUOTES: @@ -190,11 +190,11 @@ class Account extends BaseModel case self::FEATURE_CUSTOM_URL: return $self_host || ! empty($plan_details); - // Pro; No trial allowed, unless they're trialing enterprise with an active pro plan + // Pro; No trial allowed, unless they're trialing enterprise with an active pro plan case self::FEATURE_MORE_CLIENTS: return $self_host || ! empty($plan_details) && (! $plan_details['trial'] || ! empty($this->getPlanDetails(false, false))); - // White Label + // White Label case self::FEATURE_WHITE_LABEL: if (! $self_host && $plan_details && ! $plan_details['expires']) { return false; @@ -213,7 +213,7 @@ class Account extends BaseModel return $self_host || ! empty($plan_details) && ($plan_details['plan'] == self::PLAN_ENTERPRISE); - // Enterprise; No Trial allowed + // Enterprise; No Trial allowed case self::FEATURE_DOCUMENTS: case self::FEATURE_USER_PERMISSIONS: return $self_host || ! empty($plan_details) && $plan_details['plan'] == self::PLAN_ENTERPRISE && ! $plan_details['trial']; @@ -234,8 +234,9 @@ class Account extends BaseModel return false; } - if($this->plan_expires && Carbon::parse($this->plan_expires)->lt(now())) + if ($this->plan_expires && Carbon::parse($this->plan_expires)->lt(now())) { return false; + } return $this->plan == 'pro' || $this->plan == 'enterprise'; } @@ -246,8 +247,9 @@ class Account extends BaseModel return false; } - if($this->plan_expires && Carbon::parse($this->plan_expires)->lt(now())) + if ($this->plan_expires && Carbon::parse($this->plan_expires)->lt(now())) { return true; + } return $this->plan == 'free' || is_null($this->plan) || empty($this->plan); } @@ -306,10 +308,9 @@ class Account extends BaseModel $trial_started = $this->trial_started; $trial_expires = Carbon::parse($this->trial_started)->addSeconds($duration); - if($trial_expires->greaterThan(now())){ + if ($trial_expires->greaterThan(now())) { $trial_active = true; - } - + } } $plan_active = false; @@ -386,20 +387,22 @@ class Account extends BaseModel public function getDailyEmailLimit() { - if($this->is_flagged) + if ($this->is_flagged) { return 0; + } - if(Carbon::createFromTimestamp($this->created_at)->diffInWeeks() == 0) + if (Carbon::createFromTimestamp($this->created_at)->diffInWeeks() == 0) { return 20; + } - if(Carbon::createFromTimestamp($this->created_at)->diffInWeeks() <= 2 && !$this->payment_id) + if (Carbon::createFromTimestamp($this->created_at)->diffInWeeks() <= 2 && !$this->payment_id) { return 20; + } - if($this->isPaid()){ + if ($this->isPaid()) { $limit = $this->paid_plan_email_quota; $limit += Carbon::createFromTimestamp($this->created_at)->diffInMonths() * 50; - } - else{ + } else { $limit = $this->free_plan_email_quota; $limit += Carbon::createFromTimestamp($this->created_at)->diffInMonths() * 10; } @@ -409,22 +412,22 @@ class Account extends BaseModel public function emailsSent() { - if(is_null(Cache::get($this->key))) + if (is_null(Cache::get($this->key))) { return 0; + } return Cache::get($this->key); - } + } public function emailQuotaExceeded() :bool { - if(is_null(Cache::get($this->key))) + if (is_null(Cache::get($this->key))) { return false; + } try { - if(Cache::get($this->key) > $this->getDailyEmailLimit()) { - - if(is_null(Cache::get("throttle_notified:{$this->key}"))) { - + if (Cache::get($this->key) > $this->getDailyEmailLimit()) { + if (is_null(Cache::get("throttle_notified:{$this->key}"))) { App::forgetInstance('translator'); $t = app('translator'); $t->replace(Ninja::transformTranslations($this->companies()->first()->settings)); @@ -438,14 +441,14 @@ class Account extends BaseModel Cache::put("throttle_notified:{$this->key}", true, 60 * 24); - if(config('ninja.notification.slack')) + if (config('ninja.notification.slack')) { $this->companies()->first()->notification(new EmailQuotaNotification($this))->ninja(); + } } return true; } - } - catch(\Exception $e){ + } catch(\Exception $e) { \Sentry\captureMessage("I encountered an error with email quotas for account {$this->key} - defaulting to SEND"); } @@ -456,15 +459,14 @@ class Account extends BaseModel { nlog("checking if gmail credential notification has already been sent"); - if(is_null(Cache::get($this->key))) + if (is_null(Cache::get($this->key))) { return false; + } nlog("Sending notification"); try { - - if(is_null(Cache::get("gmail_credentials_notified:{$this->key}"))) { - + if (is_null(Cache::get("gmail_credentials_notified:{$this->key}"))) { App::forgetInstance('translator'); $t = app('translator'); $t->replace(Ninja::transformTranslations($this->companies()->first()->settings)); @@ -478,20 +480,17 @@ class Account extends BaseModel Cache::put("gmail_credentials_notified:{$this->key}", true, 60 * 24); - if(config('ninja.notification.slack')) + if (config('ninja.notification.slack')) { $this->companies()->first()->notification(new GmailCredentialNotification($this))->ninja(); + } } return true; - - } - catch(\Exception $e){ + } catch(\Exception $e) { \Sentry\captureMessage("I encountered an error with sending with gmail for account {$this->key}"); } return false; - - } public function resolveRouteBinding($value, $field = null) @@ -507,22 +506,21 @@ class Account extends BaseModel public function getTrialDays() { - if($this->payment_id) + if ($this->payment_id) { return 0; + } $plan_expires = Carbon::parse($this->plan_expires); - if(!$this->payment_id && $plan_expires->gt(now())){ - + if (!$this->payment_id && $plan_expires->gt(now())) { $diff = $plan_expires->diffInDays(); - if($diff > 14); - return 0; + if ($diff > 14); + return 0; return $diff; } return 0; } - } diff --git a/app/Models/Activity.php b/app/Models/Activity.php index 5c2af53d3ab9..aa8107cfc4ad 100644 --- a/app/Models/Activity.php +++ b/app/Models/Activity.php @@ -12,7 +12,6 @@ namespace App\Models; use App\Utils\Traits\MakesHash; -use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; class Activity extends StaticModel { @@ -374,5 +373,4 @@ class Activity extends StaticModel { return $this->belongsTo(Company::class); } - -} \ No newline at end of file +} diff --git a/app/Models/Backup.php b/app/Models/Backup.php index bb3b890142ef..c4920e64adf5 100644 --- a/app/Models/Backup.php +++ b/app/Models/Backup.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Models\Client; use Illuminate\Support\Facades\Storage; class Backup extends BaseModel @@ -38,17 +37,17 @@ class Backup extends BaseModel Storage::disk(config('filesystems.default'))->put($file_path, $html); - $this->filename = $file_path; - $this->save(); - + $this->filename = $file_path; + $this->save(); } public function deleteFile() { nlog('deleting => '.$this->filename); - if(!$this->filename) + if (!$this->filename) { return; + } try { Storage::disk(config('filesystems.default'))->delete($this->filename); diff --git a/app/Models/BankIntegration.php b/app/Models/BankIntegration.php index c6455f2d8004..00d94d562b70 100644 --- a/app/Models/BankIntegration.php +++ b/app/Models/BankIntegration.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Models\Filterable; use App\Models\Traits\Excludable; use Illuminate\Database\Eloquent\SoftDeletes; @@ -60,5 +59,4 @@ class BankIntegration extends BaseModel { return $this->hasMany(BankTransaction::class)->withTrashed(); } - -} \ No newline at end of file +} diff --git a/app/Models/BankTransaction.php b/app/Models/BankTransaction.php index 0798492d6f3a..0cf098a6f866 100644 --- a/app/Models/BankTransaction.php +++ b/app/Models/BankTransaction.php @@ -11,9 +11,6 @@ namespace App\Models; -use App\Models\BankTransactionRule; -use App\Models\Filterable; -use App\Models\Invoice; use App\Services\Bank\BankService; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\SoftDeletes; @@ -51,15 +48,12 @@ class BankTransaction extends BaseModel $invoices = explode(",", $this->invoice_ids); - if(count($invoices) >= 1) - { - - foreach($invoices as $invoice){ - - if(is_string($invoice) && strlen($invoice) > 1) + if (count($invoices) >= 1) { + foreach ($invoices as $invoice) { + if (is_string($invoice) && strlen($invoice) > 1) { $collection->push($this->decodePrimaryKey($invoice)); + } } - } return $collection; @@ -104,5 +98,4 @@ class BankTransaction extends BaseModel { return new BankService($this); } - -} \ No newline at end of file +} diff --git a/app/Models/BankTransactionRule.php b/app/Models/BankTransactionRule.php index b7c879d722cd..817e4495cefd 100644 --- a/app/Models/BankTransactionRule.php +++ b/app/Models/BankTransactionRule.php @@ -11,8 +11,6 @@ namespace App\Models; -use App\Models\Filterable; -use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\SoftDeletes; class BankTransactionRule extends BaseModel @@ -167,6 +165,4 @@ class BankTransactionRule extends BaseModel // //search expenses // } // } - - -} \ No newline at end of file +} diff --git a/app/Models/BaseModel.php b/app/Models/BaseModel.php index 08ad4823838d..dbb56e5876c8 100644 --- a/app/Models/BaseModel.php +++ b/app/Models/BaseModel.php @@ -21,7 +21,6 @@ use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundExceptio use Illuminate\Support\Carbon; use Illuminate\Support\Str; - /** * Class BaseModel * @@ -139,7 +138,7 @@ class BaseModel extends Model $this->company->settings = $settings; $this->company->save(); break; - //todo check that saving any other entity (Invoice:: RecurringInvoice::) settings is valid using the default: + //todo check that saving any other entity (Invoice:: RecurringInvoice::) settings is valid using the default: default: $this->client->settings = $settings; $this->client->save(); @@ -168,7 +167,6 @@ class BaseModel extends Model */ public function resolveRouteBinding($value, $field = null) { - if (is_numeric($value)) { throw new ModelNotFoundException("Record with value {$value} not found"); } @@ -208,11 +206,11 @@ class BaseModel extends Model /** * Model helper to send events for webhooks - * - * @param int $event_id + * + * @param int $event_id * @param string $additional_data optional includes - * - * @return void + * + * @return void */ public function sendEvent(int $event_id, string $additional_data = ""): void { @@ -224,6 +222,4 @@ class BaseModel extends Model WebhookHandler::dispatch($event_id, $this, $this->company, $additional_data); } } - - } diff --git a/app/Models/Client.php b/app/Models/Client.php index 8895377e14f3..173bd945310f 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -14,14 +14,9 @@ namespace App\Models; use App\DataMapper\ClientSettings; use App\DataMapper\CompanySettings; use App\DataMapper\FeesAndLimits; -use App\Models\CompanyGateway; -use App\Models\Expense; use App\Models\Presenters\ClientPresenter; -use App\Models\Project; -use App\Models\Quote; -use App\Models\Task; -use App\Services\Client\ClientService; use App\Models\Traits\Excludable; +use App\Services\Client\ClientService; use App\Utils\Traits\AppSetup; use App\Utils\Traits\ClientGroupSettingsSaver; use App\Utils\Traits\GeneratesCounter; @@ -375,7 +370,6 @@ class Client extends BaseModel implements HasLocalePreference */ public function getSetting($setting) { - /*Client Settings*/ if ($this->settings && property_exists($this->settings, $setting) && isset($this->settings->{$setting})) { /*need to catch empty string here*/ diff --git a/app/Models/ClientContact.php b/app/Models/ClientContact.php index 229cf262fd0f..9c91224b4825 100644 --- a/app/Models/ClientContact.php +++ b/app/Models/ClientContact.php @@ -16,7 +16,6 @@ use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Mail\ClientContact\ClientContactResetPasswordObject; use App\Models\Presenters\ClientContactPresenter; -use App\Notifications\ClientContactResetPassword; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use Illuminate\Contracts\Translation\HasLocalePreference; @@ -208,7 +207,6 @@ class ClientContact extends Authenticatable implements HasLocalePreference $nmo->settings = $this->company->settings; NinjaMailerJob::dispatch($nmo); - } public function preferredLocale() @@ -289,7 +287,5 @@ class ClientContact extends Authenticatable implements HasLocalePreference return ''; break; } - - } } diff --git a/app/Models/ClientGatewayToken.php b/app/Models/ClientGatewayToken.php index 5efcea44ad83..8b41d65508a8 100644 --- a/app/Models/ClientGatewayToken.php +++ b/app/Models/ClientGatewayToken.php @@ -12,7 +12,6 @@ namespace App\Models; use App\Utils\Traits\MakesDates; -use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class ClientGatewayToken extends BaseModel @@ -69,5 +68,4 @@ class ClientGatewayToken extends BaseModel { return $this->belongsTo(User::class)->withTrashed(); } - } diff --git a/app/Models/Company.php b/app/Models/Company.php index 54a4b5f718a0..ccb8514a6592 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -12,12 +12,7 @@ namespace App\Models; use App\DataMapper\CompanySettings; -use App\Models\BankTransaction; -use App\Models\BankTransactionRule; -use App\Models\Language; use App\Models\Presenters\CompanyPresenter; -use App\Models\PurchaseOrder; -use App\Models\User; use App\Services\Notification\NotificationService; use App\Utils\Ninja; use App\Utils\Traits\AppSetup; @@ -384,7 +379,6 @@ class Company extends BaseModel $this->buildCache(true); $companies = Cache::get('countries'); - } return $companies->filter(function ($item) { @@ -449,14 +443,13 @@ class Company extends BaseModel } //if the cache is still dead, get from DB - if(!$languages && property_exists($this->settings, 'language_id')) + if (!$languages && property_exists($this->settings, 'language_id')) { return Language::find($this->settings->language_id); + } return $languages->filter(function ($item) { return $item->id == $this->settings->language_id; })->first(); - - } public function getLocale() @@ -686,5 +679,4 @@ class Company extends BaseModel return $item->id == $this->getSetting('date_format_id'); })->first()->format; } - } diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php index bdee65f7fe5f..9dc1f03c2453 100644 --- a/app/Models/CompanyGateway.php +++ b/app/Models/CompanyGateway.php @@ -11,12 +11,8 @@ namespace App\Models; -use App\Models\Filterable; -use App\Models\GatewayType; use App\Utils\Number; use Illuminate\Database\Eloquent\SoftDeletes; -use PDO; -use stdClass; class CompanyGateway extends BaseModel { @@ -106,7 +102,6 @@ class CompanyGateway extends BaseModel public function system_logs() { - return $this->company ->system_log_relation ->where('type_id', $this->gateway_consts[$this->gateway->key]) @@ -138,11 +133,11 @@ class CompanyGateway extends BaseModel { $class = static::driver_class(); - if(!$class) + if (!$class) { return false; + } return new $class($this, $client); - } private function driver_class() @@ -150,8 +145,9 @@ class CompanyGateway extends BaseModel $class = 'App\\PaymentDrivers\\'.$this->gateway->provider.'PaymentDriver'; $class = str_replace('_', '', $class); - if (class_exists($class)) + if (class_exists($class)) { return $class; + } return false; @@ -308,25 +304,20 @@ class CompanyGateway extends BaseModel $fee = $this->calcGatewayFee($amount, $gateway_type_id); - if($fee > 0) { - + if ($fee > 0) { $fees_and_limits = $this->fees_and_limits->{$gateway_type_id}; - if(strlen($fees_and_limits->fee_percent) >=1) + if (strlen($fees_and_limits->fee_percent) >=1) { $label .= $fees_and_limits->fee_percent . '%'; + } - if(strlen($fees_and_limits->fee_amount) >=1 && $fees_and_limits->fee_amount > 0){ - - if(strlen($label) > 1) { - + if (strlen($fees_and_limits->fee_amount) >=1 && $fees_and_limits->fee_amount > 0) { + if (strlen($label) > 1) { $label .= ' + ' . Number::formatMoney($fees_and_limits->fee_amount, $client); - - }else { + } else { $label .= Number::formatMoney($fees_and_limits->fee_amount, $client); } } - - } @@ -344,44 +335,38 @@ class CompanyGateway extends BaseModel $fee = 0; - if($fees_and_limits->adjust_fee_percent) - { - $adjusted_fee = 0; + if ($fees_and_limits->adjust_fee_percent) { + $adjusted_fee = 0; - if ($fees_and_limits->fee_amount) { - $adjusted_fee += $fees_and_limits->fee_amount + $amount; + if ($fees_and_limits->fee_amount) { + $adjusted_fee += $fees_and_limits->fee_amount + $amount; + } else { + $adjusted_fee = $amount; + } + + if ($fees_and_limits->fee_percent) { + $divisor = 1 - ($fees_and_limits->fee_percent/100); + + $gross_amount = round($adjusted_fee/$divisor, 2); + $fee = $gross_amount - $amount; + } + } else { + if ($fees_and_limits->fee_amount) { + $fee += $fees_and_limits->fee_amount; + } + + if ($fees_and_limits->fee_percent) { + if ($fees_and_limits->fee_percent == 100) { //unusual edge case if the user wishes to charge a fee of 100% 09/01/2022 + $fee += $amount; + } else { + $fee += round(($amount * $fees_and_limits->fee_percent / 100), 2); } - else - $adjusted_fee = $amount; - - if ($fees_and_limits->fee_percent) { - - $divisor = 1 - ($fees_and_limits->fee_percent/100); - - $gross_amount = round($adjusted_fee/$divisor,2); - $fee = $gross_amount - $amount; - - } - - } - else - { - if ($fees_and_limits->fee_amount) { - $fee += $fees_and_limits->fee_amount; - } - - if ($fees_and_limits->fee_percent) { - if($fees_and_limits->fee_percent == 100){ //unusual edge case if the user wishes to charge a fee of 100% 09/01/2022 - $fee += $amount; - } - else - $fee += round(($amount * $fees_and_limits->fee_percent / 100), 2); - //elseif ($fees_and_limits->adjust_fee_percent) { - // $fee += round(($amount / (1 - $fees_and_limits->fee_percent / 100) - $amount), 2); - //} else { + //elseif ($fees_and_limits->adjust_fee_percent) { + // $fee += round(($amount / (1 - $fees_and_limits->fee_percent / 100) - $amount), 2); + //} else { - //} - } + //} + } } /* Cap fee if we have to here. */ if ($fees_and_limits->fee_cap > 0 && ($fee > $fees_and_limits->fee_cap)) { @@ -415,5 +400,4 @@ class CompanyGateway extends BaseModel { return route('payment_webhook', ['company_key' => $this->company->company_key, 'company_gateway_id' => $this->hashed_id]); } - } diff --git a/app/Models/Country.php b/app/Models/Country.php index 1bd3ecb33a60..7e6c467b7098 100644 --- a/app/Models/Country.php +++ b/app/Models/Country.php @@ -35,8 +35,8 @@ class Country extends StaticModel { return trans('texts.country_'.$this->name); } - public function getID() :string - { - return $this->id; - } + public function getID() :string + { + return $this->id; + } } diff --git a/app/Models/Credit.php b/app/Models/Credit.php index 060301f525ad..577501ee9c28 100644 --- a/app/Models/Credit.php +++ b/app/Models/Credit.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Events\Credit\CreditWasUpdated; use App\Helpers\Invoice\InvoiceSum; use App\Helpers\Invoice\InvoiceSumInclusive; use App\Jobs\Entity\CreateEntityPdf; diff --git a/app/Models/Document.php b/app/Models/Document.php index ee0be33a276f..27de8d36514f 100644 --- a/app/Models/Document.php +++ b/app/Models/Document.php @@ -12,7 +12,6 @@ namespace App\Models; use App\Helpers\Document\WithTypeHelpers; -use App\Models\Filterable; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Storage; diff --git a/app/Models/ExpenseCategory.php b/app/Models/ExpenseCategory.php index 0b24741f09f0..92f07ac0f0e0 100644 --- a/app/Models/ExpenseCategory.php +++ b/app/Models/ExpenseCategory.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Models\Filterable; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\SoftDeletes; diff --git a/app/Models/GroupSetting.php b/app/Models/GroupSetting.php index b465c8a03039..f8ac3bc1e959 100644 --- a/app/Models/GroupSetting.php +++ b/app/Models/GroupSetting.php @@ -13,8 +13,8 @@ namespace App\Models; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; +use Illuminate\Database\Eloquent\SoftDeletes; class GroupSetting extends StaticModel { @@ -73,7 +73,6 @@ class GroupSetting extends StaticModel */ public function resolveRouteBinding($value, $field = null) { - if (is_numeric($value)) { throw new ModelNotFoundException("Record with value {$value} not found"); } @@ -82,7 +81,5 @@ class GroupSetting extends StaticModel ->withTrashed() ->company() ->where('id', $this->decodePrimaryKey($value))->firstOrFail(); - } } - diff --git a/app/Models/Invoice.php b/app/Models/Invoice.php index 4b0a89b2bbb5..c3a6bf966536 100644 --- a/app/Models/Invoice.php +++ b/app/Models/Invoice.php @@ -16,9 +16,7 @@ use App\Events\Invoice\InvoiceWasEmailed; use App\Helpers\Invoice\InvoiceSum; use App\Helpers\Invoice\InvoiceSumInclusive; use App\Jobs\Entity\CreateEntityPdf; -use App\Models\Expense; use App\Models\Presenters\InvoicePresenter; -use App\Models\Task; use App\Services\Invoice\InvoiceService; use App\Services\Ledger\LedgerService; use App\Utils\Ninja; @@ -579,52 +577,40 @@ class Invoice extends BaseModel public function expense_documents() { - $line_items = $this->line_items; $expense_ids = []; - foreach($line_items as $item) - { - - if(property_exists($item, 'expense_id')) - { + foreach ($line_items as $item) { + if (property_exists($item, 'expense_id')) { $expense_ids[] = $item->expense_id; } - } return Expense::whereIn('id', $this->transformKeys($expense_ids)) ->where('invoice_documents', 1) ->where('company_id', $this->company_id) ->cursor(); - } public function task_documents() { - $line_items = $this->line_items; $task_ids = []; - foreach($line_items as $item) - { - - if(property_exists($item, 'task_id')) - { + foreach ($line_items as $item) { + if (property_exists($item, 'task_id')) { $task_ids[] = $item->task_id; } - } return Task::whereIn('id', $this->transformKeys($task_ids)) - ->whereHas('company', function($query){ - $query->where('invoice_task_documents', 1); + ->whereHas('company', function ($query) { + $query->where('invoice_task_documents', 1); }) ->where('company_id', $this->company_id) ->cursor(); - } public function translate_entity() diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 32a3e2cf3101..88d936dc1360 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -13,7 +13,6 @@ namespace App\Models; use App\Events\Payment\PaymentWasRefunded; use App\Events\Payment\PaymentWasVoided; -use App\Models\GatewayType; use App\Services\Ledger\LedgerService; use App\Services\Payment\PaymentService; use App\Utils\Ninja; @@ -23,7 +22,6 @@ use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; use App\Utils\Traits\Payment\Refundable; use Illuminate\Database\Eloquent\SoftDeletes; -use Illuminate\Support\Facades\Cache; class Payment extends BaseModel { diff --git a/app/Models/PaymentTerm.php b/app/Models/PaymentTerm.php index fa8c40a13af2..28240282d320 100644 --- a/app/Models/PaymentTerm.php +++ b/app/Models/PaymentTerm.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Models\Filterable; use Illuminate\Database\Eloquent\SoftDeletes; /** diff --git a/app/Models/Paymentable.php b/app/Models/Paymentable.php index a06e9579e2bb..0a6df1e8fbd2 100644 --- a/app/Models/Paymentable.php +++ b/app/Models/Paymentable.php @@ -43,5 +43,4 @@ class Paymentable extends Pivot { return $this->belongsTo(Payment::class); } - } diff --git a/app/Models/Presenters/CompanyPresenter.php b/app/Models/Presenters/CompanyPresenter.php index d4ba609c7913..092bf2a5a9e4 100644 --- a/app/Models/Presenters/CompanyPresenter.php +++ b/app/Models/Presenters/CompanyPresenter.php @@ -12,8 +12,8 @@ namespace App\Models\Presenters; use App\Models\Country; -use Illuminate\Support\Str; use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Str; /** * Class CompanyPresenter. @@ -28,7 +28,6 @@ class CompanyPresenter extends EntityPresenter $settings = $this->entity->settings; return $this->settings->name ?: ctrans('texts.untitled_account'); - } @@ -38,20 +37,18 @@ class CompanyPresenter extends EntityPresenter $settings = $this->entity->settings; } - if(strlen($settings->company_logo) >= 1 && (strpos($settings->company_logo, 'http') !== false)) + if (strlen($settings->company_logo) >= 1 && (strpos($settings->company_logo, 'http') !== false)) { return $settings->company_logo; - else if(strlen($settings->company_logo) >= 1) + } elseif (strlen($settings->company_logo) >= 1) { return url('') . $settings->company_logo; - else{ + } else { return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; //return asset('images/new_logo.png'); } - } public function logoDocker($settings = null) { - if (! $settings) { $settings = $this->entity->settings; } @@ -60,11 +57,11 @@ class CompanyPresenter extends EntityPresenter $logo = Storage::get("{$this->company_key}/{$basename}"); - if(!$logo) + if (!$logo) { return $this->logo($settings); + } return "data:image/png;base64, ". base64_encode($logo); - } /** @@ -76,25 +73,25 @@ class CompanyPresenter extends EntityPresenter $settings = $this->entity->settings; } - if(config('ninja.is_docker') || config('ninja.local_download')) + if (config('ninja.is_docker') || config('ninja.local_download')) { return $this->logoDocker($settings); + } - $context_options =array( - "ssl"=>array( + $context_options =[ + "ssl"=>[ "verify_peer"=>false, "verify_peer_name"=>false, - ), - ); + ], + ]; - if(strlen($settings->company_logo) >= 1 && (strpos($settings->company_logo, 'http') !== false)) + if (strlen($settings->company_logo) >= 1 && (strpos($settings->company_logo, 'http') !== false)) { return "data:image/png;base64, ". base64_encode(@file_get_contents($settings->company_logo, false, stream_context_create($context_options))); - else if(strlen($settings->company_logo) >= 1) + } elseif (strlen($settings->company_logo) >= 1) { return "data:image/png;base64, ". base64_encode(@file_get_contents(url('') . $settings->company_logo, false, stream_context_create($context_options))); - else{ + } else { return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; //return "data:image/png;base64, ". base64_encode(@file_get_contents(asset('images/new_logo.png'), false, stream_context_create($context_options))); } - } public function address($settings = null) @@ -185,8 +182,8 @@ class CompanyPresenter extends EntityPresenter /** * Return company website URL. - * - * @return string + * + * @return string */ public function website(): string { diff --git a/app/Models/Presenters/EntityPresenter.php b/app/Models/Presenters/EntityPresenter.php index 1f32c25cde84..ccfe0ca364da 100644 --- a/app/Models/Presenters/EntityPresenter.php +++ b/app/Models/Presenters/EntityPresenter.php @@ -13,7 +13,6 @@ namespace App\Models\Presenters; use App\Utils\Traits\MakesHash; use Laracasts\Presenter\Presenter; -use URL; /** * Class EntityPresenter. diff --git a/app/Models/Presenters/RecurringInvoicePresenter.php b/app/Models/Presenters/RecurringInvoicePresenter.php index a6631248812e..2c2a3793016c 100644 --- a/app/Models/Presenters/RecurringInvoicePresenter.php +++ b/app/Models/Presenters/RecurringInvoicePresenter.php @@ -11,10 +11,6 @@ namespace App\Models\Presenters; -use App\Utils\Number; -use App\Utils\Traits\MakesDates; -use Laracasts\Presenter\PresentableTrait; - /** * Class InvoicePresenter. * diff --git a/app/Models/Presenters/RecurringQuotePresenter.php b/app/Models/Presenters/RecurringQuotePresenter.php index 7e87051265a3..aecf3e640d1c 100644 --- a/app/Models/Presenters/RecurringQuotePresenter.php +++ b/app/Models/Presenters/RecurringQuotePresenter.php @@ -11,10 +11,6 @@ namespace App\Models\Presenters; -use App\Utils\Number; -use App\Utils\Traits\MakesDates; -use Laracasts\Presenter\PresentableTrait; - /** * Class QuotePresenter. * diff --git a/app/Models/PurchaseOrder.php b/app/Models/PurchaseOrder.php index cb369b180a78..ec01acec204e 100644 --- a/app/Models/PurchaseOrder.php +++ b/app/Models/PurchaseOrder.php @@ -11,10 +11,8 @@ namespace App\Models; - use App\Helpers\Invoice\InvoiceSum; use App\Helpers\Invoice\InvoiceSumInclusive; -use App\Jobs\Entity\CreateEntityPdf; use App\Jobs\Vendor\CreatePurchaseOrderPdf; use App\Services\PurchaseOrder\PurchaseOrderService; use App\Utils\Ninja; @@ -198,31 +196,30 @@ class PurchaseOrder extends BaseModel public function pdf_file_path($invitation = null, string $type = 'path', bool $portal = false) { if (! $invitation) { - - if($this->invitations()->exists()) + if ($this->invitations()->exists()) { $invitation = $this->invitations()->first(); - else{ + } else { $this->service()->createInvitations(); $invitation = $this->invitations()->first(); } - } - if(!$invitation) + if (!$invitation) { throw new \Exception('Hard fail, could not create an invitation - is there a valid contact?'); + } $file_path = $this->vendor->purchase_order_filepath($invitation).$this->numberFormatter().'.pdf'; - if(Ninja::isHosted() && $portal && Storage::disk(config('filesystems.default'))->exists($file_path)){ + if (Ninja::isHosted() && $portal && Storage::disk(config('filesystems.default'))->exists($file_path)) { return Storage::disk(config('filesystems.default'))->{$type}($file_path); - } - elseif(Ninja::isHosted() && $portal){ - $file_path = (new CreatePurchaseOrderPdf($invitation,config('filesystems.default')))->handle(); + } elseif (Ninja::isHosted() && $portal) { + $file_path = (new CreatePurchaseOrderPdf($invitation, config('filesystems.default')))->handle(); return Storage::disk(config('filesystems.default'))->{$type}($file_path); } - if(Storage::disk('public')->exists($file_path)) + if (Storage::disk('public')->exists($file_path)) { return Storage::disk('public')->{$type}($file_path); + } $file_path = (new CreatePurchaseOrderPdf($invitation))->handle(); return Storage::disk('public')->{$type}($file_path); diff --git a/app/Models/Quote.php b/app/Models/Quote.php index f03d8c9ff5d9..f0e35a5c57e3 100644 --- a/app/Models/Quote.php +++ b/app/Models/Quote.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Events\Quote\QuoteWasUpdated; use App\Helpers\Invoice\InvoiceSum; use App\Helpers\Invoice\InvoiceSumInclusive; use App\Jobs\Entity\CreateEntityPdf; @@ -242,7 +241,6 @@ class Quote extends BaseModel if (Ninja::isHosted() && $portal && Storage::disk(config('filesystems.default'))->exists($file_path)) { return Storage::disk(config('filesystems.default'))->{$type}($file_path); } elseif (Ninja::isHosted() && $portal) { - $file_path = (new CreateEntityPdf($invitation, config('filesystems.default')))->handle(); return Storage::disk(config('filesystems.default'))->{$type}($file_path); } @@ -362,5 +360,4 @@ class Quote extends BaseModel { return $entity_string; } - } diff --git a/app/Models/RecurringExpense.php b/app/Models/RecurringExpense.php index 47e5c6571287..502a568409e7 100644 --- a/app/Models/RecurringExpense.php +++ b/app/Models/RecurringExpense.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Models\RecurringInvoice; use App\Services\Recurring\RecurringService; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Carbon; @@ -203,7 +202,6 @@ class RecurringExpense extends BaseModel public function recurringDates() { - /* Return early if nothing to send back! */ if ($this->status_id == RecurringInvoice::STATUS_COMPLETED || $this->remaining_cycles == 0 || diff --git a/app/Models/RecurringInvoice.php b/app/Models/RecurringInvoice.php index ba388e38b848..a5b78f379627 100644 --- a/app/Models/RecurringInvoice.php +++ b/app/Models/RecurringInvoice.php @@ -250,8 +250,7 @@ class RecurringInvoice extends BaseModel /* If this setting is enabled, the recurring invoice may be set in the past */ if ($this->company->stop_on_unpaid_recurring) { - - /* Lets set the next send date to now so we increment from today, rather than in the past*/ + /* Lets set the next send date to now so we increment from today, rather than in the past*/ if (Carbon::parse($this->next_send_date)->lt(now()->subDays(3))) { $this->next_send_date_client = now()->format('Y-m-d'); } @@ -296,8 +295,7 @@ class RecurringInvoice extends BaseModel /* If this setting is enabled, the recurring invoice may be set in the past */ if ($this->company->stop_on_unpaid_recurring) { - - /* Lets set the next send date to now so we increment from today, rather than in the past*/ + /* Lets set the next send date to now so we increment from today, rather than in the past*/ if (Carbon::parse($this->next_send_date)->lt(now()->subDays(3))) { $this->next_send_date_client = now()->format('Y-m-d'); } @@ -499,7 +497,6 @@ class RecurringInvoice extends BaseModel */ public function recurringDates() { - /* Return early if nothing to send back! */ if ($this->status_id == self::STATUS_COMPLETED || $this->remaining_cycles == 0 || @@ -553,7 +550,7 @@ class RecurringInvoice extends BaseModel case '0': return $this->calculateDateFromTerms($date); break; - + case 'on_receipt': return Carbon::parse($date)->copy(); break; diff --git a/app/Models/RecurringQuote.php b/app/Models/RecurringQuote.php index 55ece05b0dce..67d710942d0b 100644 --- a/app/Models/RecurringQuote.php +++ b/app/Models/RecurringQuote.php @@ -14,8 +14,6 @@ namespace App\Models; use App\Helpers\Invoice\InvoiceSum; use App\Helpers\Invoice\InvoiceSumInclusive; use App\Models\Presenters\RecurringQuotePresenter; -use App\Models\Quote; -use App\Models\RecurringQuoteInvitation; use App\Services\Recurring\RecurringService; use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; @@ -418,7 +416,6 @@ class RecurringQuote extends BaseModel */ public function recurringDates() { - /* Return early if nothing to send back! */ if ($this->status_id == self::STATUS_COMPLETED || $this->remaining_cycles == 0 || diff --git a/app/Models/RecurringQuoteInvitation.php b/app/Models/RecurringQuoteInvitation.php index 20ec337aa49c..ea9888312250 100644 --- a/app/Models/RecurringQuoteInvitation.php +++ b/app/Models/RecurringQuoteInvitation.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Models\RecurringQuote; use App\Utils\Traits\Inviteable; use App\Utils\Traits\MakesDates; use Illuminate\Database\Eloquent\Relations\BelongsTo; diff --git a/app/Models/StaticModel.php b/app/Models/StaticModel.php index 5f5b9df0bd13..cb86f5126bd9 100644 --- a/app/Models/StaticModel.php +++ b/app/Models/StaticModel.php @@ -51,13 +51,11 @@ class StaticModel extends Model */ public function resolveRouteBinding($value, $field = null) { - if (is_numeric($value)) { throw new ModelNotFoundException("Record with value {$value} not found"); } return $this ->where('id', $this->decodePrimaryKey($value))->firstOrFail(); - } } diff --git a/app/Models/Subscription.php b/app/Models/Subscription.php index 5aa543d65a2a..a9c788be1162 100644 --- a/app/Models/Subscription.php +++ b/app/Models/Subscription.php @@ -11,11 +11,8 @@ namespace App\Models; -use App\Models\Filterable; -use App\Models\RecurringInvoice; use App\Services\Subscription\SubscriptionService; use Illuminate\Database\Eloquent\Factories\HasFactory; -use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Subscription extends BaseModel @@ -96,7 +93,6 @@ class Subscription extends BaseModel public function nextDateByInterval($date, $frequency_id) { switch ($frequency_id) { - case RecurringInvoice::FREQUENCY_DAILY: return $date->addDay(); case RecurringInvoice::FREQUENCY_WEEKLY: diff --git a/app/Models/TaskStatus.php b/app/Models/TaskStatus.php index f476cc1b1c79..6b1a7fd67139 100644 --- a/app/Models/TaskStatus.php +++ b/app/Models/TaskStatus.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Models\Filterable; use Illuminate\Database\Eloquent\SoftDeletes; /** diff --git a/app/Models/TaxRate.php b/app/Models/TaxRate.php index 5e29f2ddbee0..9a893b001538 100644 --- a/app/Models/TaxRate.php +++ b/app/Models/TaxRate.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Models\Filterable; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\SoftDeletes; diff --git a/app/Models/Traits/Excludable.php b/app/Models/Traits/Excludable.php index 1d23541f3c3b..ba8f87431da2 100644 --- a/app/Models/Traits/Excludable.php +++ b/app/Models/Traits/Excludable.php @@ -11,14 +11,15 @@ namespace App\Models\Traits; -trait Excludable { - +trait Excludable +{ /** * Get the array of columns - * + * * @return mixed */ - private function getTableColumns() { + private function getTableColumns() + { return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable()); } @@ -26,13 +27,11 @@ trait Excludable { * Exclude an array of elements from the result. * @param $query * @param $columns - * + * * @return mixed */ public function scopeExclude($query, $columns) { return $query->select(array_diff($this->getTableColumns(), (array) $columns)); } - } - diff --git a/app/Models/User.php b/app/Models/User.php index d0c09fb1270e..d0b59d4f1248 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -29,9 +29,7 @@ use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Carbon; -use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Cache; use Laracasts\Presenter\PresentableTrait; class User extends Authenticatable implements MustVerifyEmail @@ -319,7 +317,7 @@ class User extends Authenticatable implements MustVerifyEmail /** * Returns true is user is an admin _or_ owner - * + * * @return boolean */ public function isSuperUser() :bool @@ -367,18 +365,17 @@ class User extends Authenticatable implements MustVerifyEmail */ public function hasPermission($permission) : bool { - - /** - * We use the limit parameter here to ensure we don't split on permissions that have multiple underscores. - * - * For example view_recurring_invoice without the limit would split to view bank recurring invoice - * - * Using only part 0 and 1 would search for permission view_recurring / edit_recurring so this would - * leak permissions for other recurring_* entities - * - * The solution here will split the word - consistently - into view _ {entity} and edit _ {entity} - * - */ + /** + * We use the limit parameter here to ensure we don't split on permissions that have multiple underscores. + * + * For example view_recurring_invoice without the limit would split to view bank recurring invoice + * + * Using only part 0 and 1 would search for permission view_recurring / edit_recurring so this would + * leak permissions for other recurring_* entities + * + * The solution here will split the word - consistently - into view _ {entity} and edit _ {entity} + * + */ $parts = explode('_', $permission, 2); $all_permission = '____'; $edit_all = '____'; @@ -389,11 +386,10 @@ class User extends Authenticatable implements MustVerifyEmail $all_permission = $parts[0].'_all'; /*If this is a view search, make sure we add in the edit_{entity} AND edit_all permission into the checks*/ - if($parts[0] == 'view') { + if ($parts[0] == 'view') { $edit_all = 'edit_all'; $edit_entity = "edit_{$parts[1]}"; } - } return $this->isOwner() || @@ -402,7 +398,6 @@ class User extends Authenticatable implements MustVerifyEmail (stripos($this->token()->cu->permissions, $all_permission) !== false) || (stripos($this->token()->cu->permissions, $edit_all) !== false) || (stripos($this->token()->cu->permissions, $edit_entity) !== false); - } /** @@ -411,13 +406,12 @@ class User extends Authenticatable implements MustVerifyEmail * * This method is used when we need to scope down the query * and display a limited subset. - * + * * @param string $permission '["view_all"]' - * @return boolean + * @return boolean */ public function hasExactPermission(string $permission = '___'): bool { - $parts = explode('_', $permission); $all_permission = '__'; @@ -427,7 +421,6 @@ class User extends Authenticatable implements MustVerifyEmail return (stripos($this->token()->cu->permissions, $all_permission) !== false) || (stripos($this->token()->cu->permissions, $permission) !== false); - } /** @@ -436,23 +429,19 @@ class User extends Authenticatable implements MustVerifyEmail * * This method is used when we need to scope down the query * and display a limited subset. - * - * @param array $permissions - * @return boolean + * + * @param array $permissions + * @return boolean */ public function hasIntersectPermissions(array $permissions = []): bool { - - foreach($permissions as $permission) - { - - if($this->hasExactPermission($permission)) + foreach ($permissions as $permission) { + if ($this->hasExactPermission($permission)) { return true; - + } } return false; - } /** @@ -461,26 +450,23 @@ class User extends Authenticatable implements MustVerifyEmail * * This method is used when we need to scope down the query * and display a limited subset. - * - * @param array $permissions - * @return boolean + * + * @param array $permissions + * @return boolean */ public function hasIntersectPermissionsOrAdmin(array $permissions = []): bool { - - if($this->isSuperUser()) + if ($this->isSuperUser()) { return true; + } - foreach($permissions as $permission) - { - - if($this->hasExactPermission($permission)) + foreach ($permissions as $permission) { + if ($this->hasExactPermission($permission)) { return true; - + } } return false; - } diff --git a/app/Models/Vendor.php b/app/Models/Vendor.php index 333f99bab0b0..20582ad23ab0 100644 --- a/app/Models/Vendor.php +++ b/app/Models/Vendor.php @@ -15,7 +15,6 @@ use App\DataMapper\CompanySettings; use App\Models\Presenters\VendorPresenter; use App\Utils\Traits\AppSetup; use App\Utils\Traits\GeneratesCounter; -use App\Utils\Traits\NumberFormatter; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Support\Facades\Cache; use Laracasts\Presenter\PresentableTrait; @@ -114,7 +113,6 @@ class Vendor extends BaseModel return $currencies->filter(function ($item) { return $item->id == $this->currency_id; })->first(); - } public function timezone() @@ -192,5 +190,4 @@ class Vendor extends BaseModel { return $this->company->date_format(); } - } diff --git a/app/Models/VendorContact.php b/app/Models/VendorContact.php index 75fb8a4eb692..68dccb66ea32 100644 --- a/app/Models/VendorContact.php +++ b/app/Models/VendorContact.php @@ -157,10 +157,8 @@ class VendorContact extends Authenticatable implements HasLocalePreference public function getLoginLink() { - $domain = isset($this->company->portal_domain) ? $this->company->portal_domain : $this->company->domain(); return $domain.'/vendor/key_login/'.$this->contact_key; - } } diff --git a/app/Notifications/Admin/EntitySentNotification.php b/app/Notifications/Admin/EntitySentNotification.php index 42e7e9cf060d..11b40dbb8650 100644 --- a/app/Notifications/Admin/EntitySentNotification.php +++ b/app/Notifications/Admin/EntitySentNotification.php @@ -12,14 +12,9 @@ namespace App\Notifications\Admin; use App\Utils\Number; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; //@deprecated class EntitySentNotification extends Notification diff --git a/app/Notifications/Admin/EntityViewedNotification.php b/app/Notifications/Admin/EntityViewedNotification.php index 48541a6f3774..4b916800a173 100644 --- a/app/Notifications/Admin/EntityViewedNotification.php +++ b/app/Notifications/Admin/EntityViewedNotification.php @@ -12,14 +12,9 @@ namespace App\Notifications\Admin; use App\Utils\Number; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; class EntityViewedNotification extends Notification { diff --git a/app/Notifications/Admin/NewPaymentNotification.php b/app/Notifications/Admin/NewPaymentNotification.php index 5d27ec1e24be..082f70b7fe6c 100644 --- a/app/Notifications/Admin/NewPaymentNotification.php +++ b/app/Notifications/Admin/NewPaymentNotification.php @@ -12,14 +12,9 @@ namespace App\Notifications\Admin; use App\Utils\Number; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; class NewPaymentNotification extends Notification { diff --git a/app/Notifications/BaseNotification.php b/app/Notifications/BaseNotification.php index db2335dc4797..6985f8c731ce 100644 --- a/app/Notifications/BaseNotification.php +++ b/app/Notifications/BaseNotification.php @@ -16,7 +16,6 @@ use App\Models\Invoice; use App\Utils\TempFile; use App\Utils\Traits\MakesInvoiceHtml; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; diff --git a/app/Notifications/ClientContactRequestCancellation.php b/app/Notifications/ClientContactRequestCancellation.php index e0c66ae5e454..69ea4b2ef52f 100644 --- a/app/Notifications/ClientContactRequestCancellation.php +++ b/app/Notifications/ClientContactRequestCancellation.php @@ -13,7 +13,6 @@ namespace App\Notifications; use Closure; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; diff --git a/app/Notifications/NewAccountCreated.php b/app/Notifications/NewAccountCreated.php index e0337b35d20d..997b8ab0e51b 100644 --- a/app/Notifications/NewAccountCreated.php +++ b/app/Notifications/NewAccountCreated.php @@ -12,7 +12,6 @@ namespace App\Notifications; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; diff --git a/app/Notifications/Ninja/ClientAccountNotFound.php b/app/Notifications/Ninja/ClientAccountNotFound.php index 5a2418cedd2d..d913d9c4f001 100644 --- a/app/Notifications/Ninja/ClientAccountNotFound.php +++ b/app/Notifications/Ninja/ClientAccountNotFound.php @@ -11,26 +11,21 @@ namespace App\Notifications\Ninja; -use App\Models\User; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; -class ClientAccountNotFound extends Notification +class ClientAccountNotFound extends Notification { - /** * Create a new notification instance. * * @return void */ - public function __construct(protected string $account_key, protected string $email){} + public function __construct(protected string $account_key, protected string $email) + { + } /** * Get the notification's delivery channels. @@ -68,7 +63,6 @@ class ClientAccountNotFound extends Notification public function toSlack($notifiable) { - $content = "Client not found, unable to remove account\n"; $content .= "Account: {$this->account_key }\n"; $content .= "Email: {$this->email}\n"; diff --git a/app/Notifications/Ninja/DomainFailureNotification.php b/app/Notifications/Ninja/DomainFailureNotification.php index 9fdcdf8ff1a5..f22f08926572 100644 --- a/app/Notifications/Ninja/DomainFailureNotification.php +++ b/app/Notifications/Ninja/DomainFailureNotification.php @@ -11,20 +11,12 @@ namespace App\Notifications\Ninja; -use App\Models\Account; -use App\Models\Client; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; -class DomainFailureNotification extends Notification +class DomainFailureNotification extends Notification { - /** * Create a new notification instance. * @@ -75,7 +67,7 @@ class DomainFailureNotification extends Notification public function toSlack($notifiable) { $content = "Domain Certificate failure:\n"; - $content .= "{$this->domain}\n"; + $content .= "{$this->domain}\n"; return (new SlackMessage) ->success() diff --git a/app/Notifications/Ninja/DomainRenewalFailureNotification.php b/app/Notifications/Ninja/DomainRenewalFailureNotification.php index 3c31d5df9cd9..860c6ae8b65f 100644 --- a/app/Notifications/Ninja/DomainRenewalFailureNotification.php +++ b/app/Notifications/Ninja/DomainRenewalFailureNotification.php @@ -11,20 +11,12 @@ namespace App\Notifications\Ninja; -use App\Models\Account; -use App\Models\Client; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; -class DomainRenewalFailureNotification extends Notification +class DomainRenewalFailureNotification extends Notification { - /** * Create a new notification instance. * @@ -75,7 +67,7 @@ class DomainRenewalFailureNotification extends Notification public function toSlack($notifiable) { $content = "Domain Certificate _renewal_ failure:\n"; - $content .= "{$this->domain}\n"; + $content .= "{$this->domain}\n"; return (new SlackMessage) ->success() diff --git a/app/Notifications/Ninja/EmailBounceNotification.php b/app/Notifications/Ninja/EmailBounceNotification.php index 61d4128fca2f..9af33db98043 100644 --- a/app/Notifications/Ninja/EmailBounceNotification.php +++ b/app/Notifications/Ninja/EmailBounceNotification.php @@ -11,14 +11,9 @@ namespace App\Notifications\Ninja; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; class EmailBounceNotification extends Notification { diff --git a/app/Notifications/Ninja/EmailQualityNotification.php b/app/Notifications/Ninja/EmailQualityNotification.php index 4c6b0f3ed91c..3ec56255ad65 100644 --- a/app/Notifications/Ninja/EmailQualityNotification.php +++ b/app/Notifications/Ninja/EmailQualityNotification.php @@ -12,18 +12,12 @@ namespace App\Notifications\Ninja; use App\Models\Company; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; -class EmailQualityNotification extends Notification +class EmailQualityNotification extends Notification { - /** * Create a new notification instance. * @@ -76,7 +70,6 @@ class EmailQualityNotification extends Notification public function toSlack($notifiable) { - $content = "Email Quality notification for Company {$this->company->company_key} \n"; $owner = $this->company->owner(); diff --git a/app/Notifications/Ninja/EmailQuotaNotification.php b/app/Notifications/Ninja/EmailQuotaNotification.php index cfb2cf851eff..24eab8d21664 100644 --- a/app/Notifications/Ninja/EmailQuotaNotification.php +++ b/app/Notifications/Ninja/EmailQuotaNotification.php @@ -11,14 +11,9 @@ namespace App\Notifications\Ninja; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; class EmailQuotaNotification extends Notification { diff --git a/app/Notifications/Ninja/EmailSpamNotification.php b/app/Notifications/Ninja/EmailSpamNotification.php index 567a1f71d015..b3b95c7f8ca3 100644 --- a/app/Notifications/Ninja/EmailSpamNotification.php +++ b/app/Notifications/Ninja/EmailSpamNotification.php @@ -11,14 +11,9 @@ namespace App\Notifications\Ninja; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; class EmailSpamNotification extends Notification { diff --git a/app/Notifications/Ninja/GmailCredentialNotification.php b/app/Notifications/Ninja/GmailCredentialNotification.php index 63a5706ceb59..df9aee792fe9 100644 --- a/app/Notifications/Ninja/GmailCredentialNotification.php +++ b/app/Notifications/Ninja/GmailCredentialNotification.php @@ -11,14 +11,9 @@ namespace App\Notifications\Ninja; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; class GmailCredentialNotification extends Notification { diff --git a/app/Notifications/Ninja/NewAccountCreated.php b/app/Notifications/Ninja/NewAccountCreated.php index 2ec30a7b930e..f0e47d8cbdc2 100644 --- a/app/Notifications/Ninja/NewAccountCreated.php +++ b/app/Notifications/Ninja/NewAccountCreated.php @@ -12,7 +12,6 @@ namespace App\Notifications\Ninja; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; diff --git a/app/Notifications/Ninja/NewAccountNotification.php b/app/Notifications/Ninja/NewAccountNotification.php index 34149107e516..6c32ef582446 100644 --- a/app/Notifications/Ninja/NewAccountNotification.php +++ b/app/Notifications/Ninja/NewAccountNotification.php @@ -13,18 +13,12 @@ namespace App\Notifications\Ninja; use App\Models\Account; use App\Models\Client; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; -class NewAccountNotification extends Notification +class NewAccountNotification extends Notification { - /** * Create a new notification instance. * diff --git a/app/Notifications/Ninja/RenewalFailureNotification.php b/app/Notifications/Ninja/RenewalFailureNotification.php index 5dbbbe8a6d05..1ed7b15aed1f 100644 --- a/app/Notifications/Ninja/RenewalFailureNotification.php +++ b/app/Notifications/Ninja/RenewalFailureNotification.php @@ -11,25 +11,21 @@ namespace App\Notifications\Ninja; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; -class RenewalFailureNotification extends Notification +class RenewalFailureNotification extends Notification { - /** * Create a new notification instance. * * @return void */ - public function __construct(protected string $notification_message){} + public function __construct(protected string $notification_message) + { + } /** * Get the notification's delivery channels. diff --git a/app/Notifications/Ninja/SpamNotification.php b/app/Notifications/Ninja/SpamNotification.php index b1535c9a1831..27569488cde8 100644 --- a/app/Notifications/Ninja/SpamNotification.php +++ b/app/Notifications/Ninja/SpamNotification.php @@ -11,18 +11,12 @@ namespace App\Notifications\Ninja; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; -class SpamNotification extends Notification +class SpamNotification extends Notification { - /** * Create a new notification instance. * @@ -77,38 +71,30 @@ class SpamNotification extends Notification // foreach($this->spam_lists as $spam_list) // { - if(array_key_exists('companies', $this->spam_list)) - { - $content .= " Companies \n"; + if (array_key_exists('companies', $this->spam_list)) { + $content .= " Companies \n"; - foreach($this->spam_list['companies'] as $company) - { - $content .= "{$company['name']} - c_key={$company['company_key']} - a_key={$company['account_key']} - {$company['owner']} \n"; - } + foreach ($this->spam_list['companies'] as $company) { + $content .= "{$company['name']} - c_key={$company['company_key']} - a_key={$company['account_key']} - {$company['owner']} \n"; } + } - if(array_key_exists('templates', $this->spam_list)) - { - $content .= " Templates \n"; + if (array_key_exists('templates', $this->spam_list)) { + $content .= " Templates \n"; - foreach($this->spam_list['templates'] as $company) - { - $content .= "{$company['name']} - c_key={$company['company_key']} - a_key={$company['account_key']} - {$company['owner']} \n"; - } + foreach ($this->spam_list['templates'] as $company) { + $content .= "{$company['name']} - c_key={$company['company_key']} - a_key={$company['account_key']} - {$company['owner']} \n"; } + } - if(array_key_exists('users', $this->spam_list)) - { - - $content .= ' Users \n'; - - foreach($this->spam_list['users'] as $user) - { - $content .= "{$user['email']} - a_key={$user['account_key']} - created={$user['created']} \n"; - } + if (array_key_exists('users', $this->spam_list)) { + $content .= ' Users \n'; + foreach ($this->spam_list['users'] as $user) { + $content .= "{$user['email']} - a_key={$user['account_key']} - created={$user['created']} \n"; } + } // } diff --git a/app/Notifications/Ninja/UserQualityNotification.php b/app/Notifications/Ninja/UserQualityNotification.php index ec079bb2c68a..385f1c0ca9c8 100644 --- a/app/Notifications/Ninja/UserQualityNotification.php +++ b/app/Notifications/Ninja/UserQualityNotification.php @@ -12,18 +12,12 @@ namespace App\Notifications\Ninja; use App\Models\User; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; -class UserQualityNotification extends Notification +class UserQualityNotification extends Notification { - /** * Create a new notification instance. * @@ -76,7 +70,6 @@ class UserQualityNotification extends Notification public function toSlack($notifiable) { - $content = "User Quality notification {$this->user->present()->name()} \n"; $content .= "Account: {$this->account_key }\n"; diff --git a/app/Notifications/Ninja/VerifyUser.php b/app/Notifications/Ninja/VerifyUser.php index 9fd8f22444c1..c1311fba5d64 100644 --- a/app/Notifications/Ninja/VerifyUser.php +++ b/app/Notifications/Ninja/VerifyUser.php @@ -12,7 +12,6 @@ namespace App\Notifications\Ninja; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; diff --git a/app/Notifications/Ninja/WePayFailureNotification.php b/app/Notifications/Ninja/WePayFailureNotification.php index b1951801e545..1cbf759d5a6f 100644 --- a/app/Notifications/Ninja/WePayFailureNotification.php +++ b/app/Notifications/Ninja/WePayFailureNotification.php @@ -11,14 +11,9 @@ namespace App\Notifications\Ninja; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; -use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Notification; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Queue\SerializesModels; class WePayFailureNotification extends Notification { diff --git a/app/Observers/ClientContactObserver.php b/app/Observers/ClientContactObserver.php index b570d2d1ea88..7f7fee3a98a9 100644 --- a/app/Observers/ClientContactObserver.php +++ b/app/Observers/ClientContactObserver.php @@ -58,33 +58,29 @@ class ClientContactObserver //ensure entity state is preserved - InvoiceInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite){ - - if($invite->invoice()->doesnthave('invitations')) - $invite->invoice->service()->createInvitations(); - + InvoiceInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite) { + if ($invite->invoice()->doesnthave('invitations')) { + $invite->invoice->service()->createInvitations(); + } }); - QuoteInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite){ - - if($invite->quote()->doesnthave('invitations')) - $invite->quote->service()->createInvitations(); - + QuoteInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite) { + if ($invite->quote()->doesnthave('invitations')) { + $invite->quote->service()->createInvitations(); + } }); - RecurringInvoiceInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite){ - - if($invite->recurring_invoice()->doesnthave('invitations')) - $invite->recurring_invoice->service()->createInvitations(); - + RecurringInvoiceInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite) { + if ($invite->recurring_invoice()->doesnthave('invitations')) { + $invite->recurring_invoice->service()->createInvitations(); + } }); - CreditInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite){ - - if($invite->credit()->doesnthave('invitations')) - $invite->credit->service()->createInvitations(); - + CreditInvitation::withTrashed()->where('client_contact_id', $client_contact_id)->cursor()->each(function ($invite) { + if ($invite->credit()->doesnthave('invitations')) { + $invite->credit->service()->createInvitations(); + } }); } diff --git a/app/Observers/ClientObserver.php b/app/Observers/ClientObserver.php index de79d6c862e0..ed0a1e7c3310 100644 --- a/app/Observers/ClientObserver.php +++ b/app/Observers/ClientObserver.php @@ -31,9 +31,9 @@ class ClientObserver ->where('event_id', Webhook::EVENT_CREATE_CLIENT) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_CLIENT, $client, $client->company)->delay(0); - + } } /** @@ -44,24 +44,24 @@ class ClientObserver */ public function updated(Client $client) { - $event = Webhook::EVENT_UPDATE_CLIENT; - if($client->getOriginal('deleted_at') && !$client->deleted_at) + if ($client->getOriginal('deleted_at') && !$client->deleted_at) { $event = Webhook::EVENT_RESTORE_CLIENT; + } - if($client->is_deleted) - $event = Webhook::EVENT_DELETE_CLIENT; + if ($client->is_deleted) { + $event = Webhook::EVENT_DELETE_CLIENT; + } $subscriptions = Webhook::where('company_id', $client->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $client, $client->company, 'client')->delay(0); - - + } } /** @@ -72,16 +72,16 @@ class ClientObserver */ public function deleted(Client $client) { - if($client->is_deleted) + if ($client->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $client->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_CLIENT) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_CLIENT, $client, $client->company)->delay(0); - + } } - } diff --git a/app/Observers/CompanyGatewayObserver.php b/app/Observers/CompanyGatewayObserver.php index 22e0c8e8fa96..bc40e9fb0232 100644 --- a/app/Observers/CompanyGatewayObserver.php +++ b/app/Observers/CompanyGatewayObserver.php @@ -15,7 +15,6 @@ class CompanyGatewayObserver */ public function created(CompanyGateway $company_gateway) { - /* Set company gateway if not exists*/ if (! $company_gateway->label) { $company_gateway->label = $company_gateway->gateway->name; diff --git a/app/Observers/CreditObserver.php b/app/Observers/CreditObserver.php index 43fc322fe4bd..d0bcb982d1be 100644 --- a/app/Observers/CreditObserver.php +++ b/app/Observers/CreditObserver.php @@ -11,7 +11,6 @@ namespace App\Observers; -use App\Jobs\Util\UnlinkFile; use App\Jobs\Util\WebhookHandler; use App\Models\Client; use App\Models\Credit; @@ -19,7 +18,6 @@ use App\Models\Webhook; class CreditObserver { - public $afterCommit = true; /** @@ -49,19 +47,21 @@ class CreditObserver { $event = Webhook::EVENT_UPDATE_CREDIT; - if($credit->getOriginal('deleted_at') && !$credit->deleted_at) + if ($credit->getOriginal('deleted_at') && !$credit->deleted_at) { $event = Webhook::EVENT_RESTORE_CREDIT; + } - if($credit->is_deleted) - $event = Webhook::EVENT_DELETE_CREDIT; + if ($credit->is_deleted) { + $event = Webhook::EVENT_DELETE_CREDIT; + } $subscriptions = Webhook::where('company_id', $credit->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $credit, $credit->company)->delay(0); - + } } /** @@ -72,16 +72,17 @@ class CreditObserver */ public function deleted(Credit $credit) { - if($credit->is_deleted) + if ($credit->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $credit->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_CREDIT) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_CREDIT, $credit, $credit->company)->delay(0); - + } } /** diff --git a/app/Observers/ExpenseObserver.php b/app/Observers/ExpenseObserver.php index 84ec3e7d6cf9..c725f3edb5f3 100644 --- a/app/Observers/ExpenseObserver.php +++ b/app/Observers/ExpenseObserver.php @@ -31,9 +31,9 @@ class ExpenseObserver ->where('event_id', Webhook::EVENT_CREATE_EXPENSE) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_EXPENSE, $expense, $expense->company)->delay(0); - + } } /** @@ -46,20 +46,22 @@ class ExpenseObserver { $event = Webhook::EVENT_UPDATE_EXPENSE; - if($expense->getOriginal('deleted_at') && !$expense->deleted_at) + if ($expense->getOriginal('deleted_at') && !$expense->deleted_at) { $event = Webhook::EVENT_RESTORE_EXPENSE; + } - if($expense->is_deleted) - $event = Webhook::EVENT_DELETE_EXPENSE; + if ($expense->is_deleted) { + $event = Webhook::EVENT_DELETE_EXPENSE; + } $subscriptions = Webhook::where('company_id', $expense->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $expense, $expense->company)->delay(0); - + } } /** @@ -70,16 +72,17 @@ class ExpenseObserver */ public function deleted(Expense $expense) { - if($expense->is_deleted) + if ($expense->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $expense->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_EXPENSE) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_EXPENSE, $expense, $expense->company)->delay(0); - + } } /** diff --git a/app/Observers/InvoiceObserver.php b/app/Observers/InvoiceObserver.php index 2dc5431a6fc6..f78522e0a7d4 100644 --- a/app/Observers/InvoiceObserver.php +++ b/app/Observers/InvoiceObserver.php @@ -46,19 +46,22 @@ class InvoiceObserver { $event = Webhook::EVENT_UPDATE_INVOICE; - if($invoice->getOriginal('deleted_at') && !$invoice->deleted_at) + if ($invoice->getOriginal('deleted_at') && !$invoice->deleted_at) { $event = Webhook::EVENT_RESTORE_INVOICE; + } - if($invoice->is_deleted) - $event = Webhook::EVENT_DELETE_INVOICE; + if ($invoice->is_deleted) { + $event = Webhook::EVENT_DELETE_INVOICE; + } $subscriptions = Webhook::where('company_id', $invoice->company->id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $invoice, $invoice->company, 'client')->delay(0); + } } /** @@ -69,16 +72,17 @@ class InvoiceObserver */ public function deleted(Invoice $invoice) { - if($invoice->is_deleted) + if ($invoice->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $invoice->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_INVOICE) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_INVOICE, $invoice, $invoice->company, 'client')->delay(0); - + } } /** diff --git a/app/Observers/PaymentObserver.php b/app/Observers/PaymentObserver.php index 8b31dffdddad..b3c0f79fad41 100644 --- a/app/Observers/PaymentObserver.php +++ b/app/Observers/PaymentObserver.php @@ -17,7 +17,6 @@ use App\Models\Webhook; class PaymentObserver { - public $afterCommit = true; /** @@ -32,9 +31,9 @@ class PaymentObserver ->where('event_id', Webhook::EVENT_CREATE_PAYMENT) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_PAYMENT, $payment, $payment->company, 'invoices,client')->delay(20); - + } } /** @@ -47,19 +46,22 @@ class PaymentObserver { $event = Webhook::EVENT_UPDATE_PAYMENT; - if($payment->getOriginal('deleted_at') && !$payment->deleted_at) + if ($payment->getOriginal('deleted_at') && !$payment->deleted_at) { $event = Webhook::EVENT_RESTORE_PAYMENT; + } - if($payment->is_deleted) - $event = Webhook::EVENT_DELETE_PAYMENT; + if ($payment->is_deleted) { + $event = Webhook::EVENT_DELETE_PAYMENT; + } $subscriptions = Webhook::where('company_id', $payment->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $payment, $payment->company, 'invoices,client')->delay(25); + } } /** @@ -70,8 +72,9 @@ class PaymentObserver */ public function deleted(Payment $payment) { - if($payment->is_deleted) + if ($payment->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $payment->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_PAYMENT) diff --git a/app/Observers/ProductObserver.php b/app/Observers/ProductObserver.php index 0ef5cac0d575..7e24377dc571 100644 --- a/app/Observers/ProductObserver.php +++ b/app/Observers/ProductObserver.php @@ -17,7 +17,6 @@ use App\Models\Webhook; class ProductObserver { - public $afterCommit = true; /** @@ -32,8 +31,9 @@ class ProductObserver ->where('event_id', Webhook::EVENT_CREATE_PRODUCT) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_PRODUCT, $product, $product->company)->delay(0); + } } /** @@ -44,23 +44,24 @@ class ProductObserver */ public function updated(Product $product) { - $event = Webhook::EVENT_UPDATE_PRODUCT; - if($product->getOriginal('deleted_at') && !$product->deleted_at) + if ($product->getOriginal('deleted_at') && !$product->deleted_at) { $event = Webhook::EVENT_RESTORE_PRODUCT; + } - if($product->is_deleted) - $event = Webhook::EVENT_DELETE_PRODUCT; + if ($product->is_deleted) { + $event = Webhook::EVENT_DELETE_PRODUCT; + } $subscriptions = Webhook::where('company_id', $product->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $product, $product->company)->delay(0); - + } } /** @@ -71,15 +72,17 @@ class ProductObserver */ public function deleted(Product $product) { - if($product->is_deleted) + if ($product->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $product->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_PRODUCT) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_PRODUCT, $product, $product->company)->delay(0); + } } /** diff --git a/app/Observers/ProjectObserver.php b/app/Observers/ProjectObserver.php index 41f3028a8649..c6f169372831 100644 --- a/app/Observers/ProjectObserver.php +++ b/app/Observers/ProjectObserver.php @@ -31,9 +31,9 @@ class ProjectObserver ->where('event_id', Webhook::EVENT_PROJECT_CREATE) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_PROJECT_CREATE, $project, $project->company, 'client')->delay(0); - + } } /** @@ -44,23 +44,24 @@ class ProjectObserver */ public function updated(Project $project) { - $event = Webhook::EVENT_PROJECT_UPDATE; - if($project->getOriginal('deleted_at') && !$project->deleted_at) + if ($project->getOriginal('deleted_at') && !$project->deleted_at) { $event = Webhook::EVENT_RESTORE_PROJECT; + } - if($project->is_deleted) - $event = Webhook::EVENT_PROJECT_DELETE; + if ($project->is_deleted) { + $event = Webhook::EVENT_PROJECT_DELETE; + } $subscriptions = Webhook::where('company_id', $project->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $project, $project->company, 'client')->delay(0); - + } } /** @@ -71,16 +72,17 @@ class ProjectObserver */ public function deleted(Project $project) { - if($project->is_deleted) + if ($project->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $project->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_PROJECT) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_PROJECT, $project, $project->company, 'client')->delay(0); - + } } /** diff --git a/app/Observers/PurchaseOrderObserver.php b/app/Observers/PurchaseOrderObserver.php index b6675c0d74a5..a0cf35c28883 100644 --- a/app/Observers/PurchaseOrderObserver.php +++ b/app/Observers/PurchaseOrderObserver.php @@ -17,7 +17,6 @@ use App\Models\Webhook; class PurchaseOrderObserver { - public $afterCommit = true; /** @@ -28,14 +27,13 @@ class PurchaseOrderObserver */ public function created(PurchaseOrder $purchase_order) { - $subscriptions = Webhook::where('company_id', $purchase_order->company_id) ->where('event_id', Webhook::EVENT_CREATE_PURCHASE_ORDER) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_PURCHASE_ORDER, $purchase_order, $purchase_order->company, 'vendor')->delay(0); - + } } /** @@ -46,23 +44,24 @@ class PurchaseOrderObserver */ public function updated(PurchaseOrder $purchase_order) { - $event = Webhook::EVENT_UPDATE_PURCHASE_ORDER; - if($purchase_order->getOriginal('deleted_at') && !$purchase_order->deleted_at) + if ($purchase_order->getOriginal('deleted_at') && !$purchase_order->deleted_at) { $event = Webhook::EVENT_RESTORE_PURCHASE_ORDER; + } - if($purchase_order->is_deleted) - $event = Webhook::EVENT_DELETE_PURCHASE_ORDER; + if ($purchase_order->is_deleted) { + $event = Webhook::EVENT_DELETE_PURCHASE_ORDER; + } $subscriptions = Webhook::where('company_id', $purchase_order->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $purchase_order, $purchase_order->company, 'vendor')->delay(0); - + } } /** @@ -73,16 +72,17 @@ class PurchaseOrderObserver */ public function deleted(PurchaseOrder $purchase_order) { - if($purchase_order->is_deleted) + if ($purchase_order->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $purchase_order->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_PURCHASE_ORDER) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_PURCHASE_ORDER, $purchase_order, $purchase_order->company, 'vendor')->delay(0); - + } } /** diff --git a/app/Observers/QuoteObserver.php b/app/Observers/QuoteObserver.php index db2bdf67247b..1b12609f091a 100644 --- a/app/Observers/QuoteObserver.php +++ b/app/Observers/QuoteObserver.php @@ -17,7 +17,6 @@ use App\Models\Webhook; class QuoteObserver { - public $afterCommit = true; /** @@ -28,14 +27,13 @@ class QuoteObserver */ public function created(Quote $quote) { - $subscriptions = Webhook::where('company_id', $quote->company_id) ->where('event_id', Webhook::EVENT_CREATE_QUOTE) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_QUOTE, $quote, $quote->company, 'client')->delay(0); - + } } /** @@ -46,23 +44,24 @@ class QuoteObserver */ public function updated(Quote $quote) { - $event = Webhook::EVENT_UPDATE_QUOTE; - if($quote->getOriginal('deleted_at') && !$quote->deleted_at) + if ($quote->getOriginal('deleted_at') && !$quote->deleted_at) { $event = Webhook::EVENT_RESTORE_QUOTE; + } - if($quote->is_deleted) - $event = Webhook::EVENT_DELETE_QUOTE; + if ($quote->is_deleted) { + $event = Webhook::EVENT_DELETE_QUOTE; + } $subscriptions = Webhook::where('company_id', $quote->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $quote, $quote->company, 'client')->delay(0); - + } } /** @@ -73,16 +72,17 @@ class QuoteObserver */ public function deleted(Quote $quote) { - if($quote->is_deleted) + if ($quote->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $quote->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_QUOTE) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_QUOTE, $quote, $quote->company, 'client')->delay(0); - + } } /** diff --git a/app/Observers/TaskObserver.php b/app/Observers/TaskObserver.php index ff3e6d1a0260..3626fe9d0d6e 100644 --- a/app/Observers/TaskObserver.php +++ b/app/Observers/TaskObserver.php @@ -17,7 +17,6 @@ use App\Models\Webhook; class TaskObserver { - public $afterCommit = true; /** @@ -32,9 +31,9 @@ class TaskObserver ->where('event_id', Webhook::EVENT_CREATE_TASK) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_TASK, $task, $task->company)->delay(0); - + } } /** @@ -47,19 +46,22 @@ class TaskObserver { $event = Webhook::EVENT_UPDATE_TASK; - if($task->getOriginal('deleted_at') && !$task->deleted_at) + if ($task->getOriginal('deleted_at') && !$task->deleted_at) { $event = Webhook::EVENT_RESTORE_TASK; + } - if($task->is_deleted) - $event = Webhook::EVENT_DELETE_TASK; + if ($task->is_deleted) { + $event = Webhook::EVENT_DELETE_TASK; + } $subscriptions = Webhook::where('company_id', $task->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $task, $task->company)->delay(0); + } } /** @@ -70,16 +72,17 @@ class TaskObserver */ public function deleted(Task $task) { - if($task->is_deleted) + if ($task->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $task->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_TASK) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_ARCHIVE_TASK, $task, $task->company)->delay(0); - + } } /** diff --git a/app/Observers/UserObserver.php b/app/Observers/UserObserver.php index 7efa008f74c8..003f027e7fd8 100644 --- a/app/Observers/UserObserver.php +++ b/app/Observers/UserObserver.php @@ -38,14 +38,12 @@ class UserObserver */ public function updated(User $user) { - if (Ninja::isHosted() && $user->isDirty('email') && $user->company_users()->where('is_owner', true)->exists()) { //ensure they are owner user and update email on file. - if(class_exists(\Modules\Admin\Jobs\Account\UpdateOwnerUser::class)) + if (class_exists(\Modules\Admin\Jobs\Account\UpdateOwnerUser::class)) { \Modules\Admin\Jobs\Account\UpdateOwnerUser::dispatch($user->account->key, $user, $user->getOriginal('email')); - + } } - } /** diff --git a/app/Observers/VendorContactObserver.php b/app/Observers/VendorContactObserver.php index a0065cac2bad..64677305b57d 100644 --- a/app/Observers/VendorContactObserver.php +++ b/app/Observers/VendorContactObserver.php @@ -46,19 +46,15 @@ class VendorContactObserver */ public function deleted(VendorContact $vendorContact) { - $vendor_contact_id = $vendorContact->id; $vendorContact->purchase_order_invitations()->delete(); - PurchaseOrderInvitation::withTrashed()->where('vendor_contact_id', $vendor_contact_id)->cursor()->each(function ($invite){ - - if($invite->purchase_order()->doesnthave('invitations')) - $invite->purchase_order->service()->createInvitations(); - + PurchaseOrderInvitation::withTrashed()->where('vendor_contact_id', $vendor_contact_id)->cursor()->each(function ($invite) { + if ($invite->purchase_order()->doesnthave('invitations')) { + $invite->purchase_order->service()->createInvitations(); + } }); - - } /** @@ -69,7 +65,6 @@ class VendorContactObserver */ public function restored(VendorContact $vendorContact) { - } /** diff --git a/app/Observers/VendorObserver.php b/app/Observers/VendorObserver.php index 4e280a4a64a3..801591526425 100644 --- a/app/Observers/VendorObserver.php +++ b/app/Observers/VendorObserver.php @@ -17,7 +17,6 @@ use App\Models\Webhook; class VendorObserver { - public $afterCommit = true; /** @@ -32,9 +31,9 @@ class VendorObserver ->where('event_id', Webhook::EVENT_CREATE_VENDOR) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch(Webhook::EVENT_CREATE_VENDOR, $vendor, $vendor->company)->delay(0); - + } } /** @@ -47,19 +46,22 @@ class VendorObserver { $event = Webhook::EVENT_UPDATE_VENDOR; - if($vendor->getOriginal('deleted_at') && !$vendor->deleted_at) + if ($vendor->getOriginal('deleted_at') && !$vendor->deleted_at) { $event = Webhook::EVENT_RESTORE_VENDOR; + } - if($vendor->is_deleted) - $event = Webhook::EVENT_DELETE_VENDOR; + if ($vendor->is_deleted) { + $event = Webhook::EVENT_DELETE_VENDOR; + } $subscriptions = Webhook::where('company_id', $vendor->company_id) ->where('event_id', $event) ->exists(); - if ($subscriptions) + if ($subscriptions) { WebhookHandler::dispatch($event, $vendor, $vendor->company)->delay(0); + } } /** @@ -70,8 +72,9 @@ class VendorObserver */ public function deleted(Vendor $vendor) { - if($vendor->is_deleted) + if ($vendor->is_deleted) { return; + } $subscriptions = Webhook::where('company_id', $vendor->company_id) ->where('event_id', Webhook::EVENT_ARCHIVE_VENDOR) @@ -103,5 +106,4 @@ class VendorObserver { // } - } diff --git a/app/PaymentDrivers/Authorize/AuthorizeCreateCustomer.php b/app/PaymentDrivers/Authorize/AuthorizeCreateCustomer.php index c7e806e9df98..06e2162cf435 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeCreateCustomer.php +++ b/app/PaymentDrivers/Authorize/AuthorizeCreateCustomer.php @@ -164,8 +164,3 @@ class AuthorizeCreateCustomer // } - - - - - diff --git a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php index a15c12dfa0a8..c49a7831b64a 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php +++ b/app/PaymentDrivers/Authorize/AuthorizeCreditCard.php @@ -102,18 +102,18 @@ class AuthorizeCreditCard } // Delete a customer profile - // $request = new DeleteCustomerProfileRequest(); - // $request->setMerchantAuthentication($this->authorize->merchant_authentication); - // $request->setCustomerProfileId( $customer_profile_id ); + // $request = new DeleteCustomerProfileRequest(); + // $request->setMerchantAuthentication($this->authorize->merchant_authentication); + // $request->setCustomerProfileId( $customer_profile_id ); - // $controller = new DeleteCustomerProfileController($request); - // $response = $controller->executeWithApiResponse($this->authorize->mode()); - // if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") ) - // { + // $controller = new DeleteCustomerProfileController($request); + // $response = $controller->executeWithApiResponse($this->authorize->mode()); + // if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") ) + // { // nlog("SUCCESS: Delete Customer Payment Profile SUCCESS"); - // } - // else - // nlog("unable to delete profile {$customer_profile_id}"); + // } + // else + // nlog("unable to delete profile {$customer_profile_id}"); } private function processTokenPayment($request) diff --git a/app/PaymentDrivers/Authorize/AuthorizeCustomer.php b/app/PaymentDrivers/Authorize/AuthorizeCustomer.php index d7926da241bc..3e51b270db8e 100644 --- a/app/PaymentDrivers/Authorize/AuthorizeCustomer.php +++ b/app/PaymentDrivers/Authorize/AuthorizeCustomer.php @@ -12,7 +12,6 @@ namespace App\PaymentDrivers\Authorize; -use App\Exceptions\GenericPaymentDriverFailure; use App\Factory\ClientContactFactory; use App\Factory\ClientFactory; use App\Models\Client; @@ -21,11 +20,8 @@ use App\Models\ClientGatewayToken; use App\Models\GatewayType; use App\PaymentDrivers\AuthorizePaymentDriver; use Illuminate\Support\Facades\Cache; -use net\authorize\api\contract\v1\CreateCustomerProfileRequest; -use net\authorize\api\contract\v1\CustomerProfileType; use net\authorize\api\contract\v1\GetCustomerProfileIdsRequest; use net\authorize\api\contract\v1\GetCustomerProfileRequest; -use net\authorize\api\controller\CreateCustomerProfileController; use net\authorize\api\controller\GetCustomerProfileController; use net\authorize\api\controller\GetCustomerProfileIdsController; @@ -43,7 +39,6 @@ class AuthorizeCustomer private function getCustomerProfileIds() { - // Get all existing customer profile ID's $request = new GetCustomerProfileIdsRequest(); $request->setMerchantAuthentication($this->authorize->merchant_authentication); diff --git a/app/PaymentDrivers/AuthorizePaymentDriver.php b/app/PaymentDrivers/AuthorizePaymentDriver.php index ab6e98f05f24..dcb37d597d22 100644 --- a/app/PaymentDrivers/AuthorizePaymentDriver.php +++ b/app/PaymentDrivers/AuthorizePaymentDriver.php @@ -66,7 +66,6 @@ class AuthorizePaymentDriver extends BaseDriver public function getClientRequiredFields(): array { - $data = [ ['name' => 'client_name', 'label' => ctrans('texts.name'), 'type' => 'text', 'validation' => 'required|min:2'], ['name' => 'contact_email', 'label' => ctrans('texts.email'), 'type' => 'text', 'validation' => 'required|email:rfc'], @@ -88,33 +87,24 @@ class AuthorizePaymentDriver extends BaseDriver } if ($this->company_gateway->require_custom_value1) { - $fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value2) { - $fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value3) { - $fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value4) { - $fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required']; - } return array_merge($data, $fields); - } public function authorizeView($payment_method) diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index af1ba7d446ee..8321961048ad 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -20,7 +20,6 @@ use App\Jobs\Mail\NinjaMailer; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Jobs\Mail\PaymentFailedMailer; -use App\Jobs\Ninja\TransactionLog; use App\Jobs\Util\SystemLogger; use App\Mail\Admin\ClientPaymentFailureObject; use App\Models\Client; @@ -31,16 +30,12 @@ use App\Models\GatewayType; use App\Models\Invoice; use App\Models\Payment; use App\Models\PaymentHash; -use App\Models\PaymentType; use App\Models\SystemLog; -use App\Models\TransactionEvent; use App\Services\Subscription\SubscriptionService; use App\Utils\Helpers; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SystemLogTrait; -use Checkout\Library\Exceptions\CheckoutHttpException; -use Exception; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Illuminate\Support\Str; @@ -150,33 +145,24 @@ class BaseDriver extends AbstractPaymentDriver } if ($this->company_gateway->require_custom_value1) { - $fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value2) { - $fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value3) { - $fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value4) { - $fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required']; - } return $fields; - } /** @@ -369,11 +355,11 @@ class BaseDriver extends AbstractPaymentDriver event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); if (property_exists($this->payment_hash->data, 'billing_context') && $status == Payment::STATUS_COMPLETED) { - - if(is_int($this->payment_hash->data->billing_context->subscription_id)) + if (is_int($this->payment_hash->data->billing_context->subscription_id)) { $billing_subscription = \App\Models\Subscription::find($this->payment_hash->data->billing_context->subscription_id); - else + } else { $billing_subscription = \App\Models\Subscription::find($this->decodePrimaryKey($this->payment_hash->data->billing_context->subscription_id)); + } // To access campaign hash => $this->payment_hash->data->billing_context->campaign; // To access campaign data => Cache::get(CAMPAIGN_HASH) @@ -394,7 +380,6 @@ class BaseDriver extends AbstractPaymentDriver */ public function confirmGatewayFee() :void { - /*Payment invoices*/ $payment_invoices = $this->payment_hash->invoices(); @@ -408,7 +393,6 @@ class BaseDriver extends AbstractPaymentDriver if (collect($invoice->line_items)->contains('type_id', '3')) { $invoice->service()->toggleFeesPaid()->save(); } - }); } @@ -506,7 +490,7 @@ class BaseDriver extends AbstractPaymentDriver public function sendFailureMail($error) { - if(is_object($error)){ + if (is_object($error)) { $error = 'Payment Aborted'; } diff --git a/app/PaymentDrivers/Braintree/CreditCard.php b/app/PaymentDrivers/Braintree/CreditCard.php index 22b5efe2385d..0dc9f8760002 100644 --- a/app/PaymentDrivers/Braintree/CreditCard.php +++ b/app/PaymentDrivers/Braintree/CreditCard.php @@ -230,7 +230,6 @@ class CreditCard */ private function processUnsuccessfulPayment($response) { - $this->braintree->sendFailureMail($response?->transaction?->additionalProcessorResponse); $message = [ diff --git a/app/PaymentDrivers/Braintree/PayPal.php b/app/PaymentDrivers/Braintree/PayPal.php index 76b630d00fb1..fe95842bbc0c 100644 --- a/app/PaymentDrivers/Braintree/PayPal.php +++ b/app/PaymentDrivers/Braintree/PayPal.php @@ -111,10 +111,11 @@ class PayPal 'paymentMethodNonce' => $gateway_response->nonce, ]); - if($payment_method->success) + if ($payment_method->success) { return $payment_method->paymentMethod->token; - else + } else { throw new PaymentFailed(property_exists($payment_method, 'message') ? $payment_method->message : 'Undefined error storing payment token.', 0); + } } /** diff --git a/app/PaymentDrivers/BraintreePaymentDriver.php b/app/PaymentDrivers/BraintreePaymentDriver.php index 6f2101fbecfc..374f4cfc2b2c 100644 --- a/app/PaymentDrivers/BraintreePaymentDriver.php +++ b/app/PaymentDrivers/BraintreePaymentDriver.php @@ -126,17 +126,16 @@ class BraintreePaymentDriver extends BaseDriver return $result->customer; } - //12-08-2022 catch when the customer is not created. - $data = [ - 'transaction_reference' => null, - 'transaction_response' => $result, - 'success' => false, - 'description' => 'Could not create customer', - 'code' => 500, - ]; - - SystemLogger::dispatch(['server_response' => $result, 'data' => $data], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_BRAINTREE, $this->client, $this->client->company); + //12-08-2022 catch when the customer is not created. + $data = [ + 'transaction_reference' => null, + 'transaction_response' => $result, + 'success' => false, + 'description' => 'Could not create customer', + 'code' => 500, + ]; + SystemLogger::dispatch(['server_response' => $result, 'data' => $data], SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_FAILURE, SystemLog::TYPE_BRAINTREE, $this->client, $this->client->company); } public function refund(Payment $payment, $amount, $return_client_response = false) @@ -272,7 +271,8 @@ class BraintreePaymentDriver extends BaseDriver $this->init(); $webhookNotification = $this->gateway->webhookNotification()->parse( - $request->input('bt_signature'), $request->input('bt_payload') + $request->input('bt_signature'), + $request->input('bt_payload') ); nlog('braintree webhook'); diff --git a/app/PaymentDrivers/CheckoutCom/CreditCard.php b/app/PaymentDrivers/CheckoutCom/CreditCard.php index ffd93680a863..6aefc0845180 100644 --- a/app/PaymentDrivers/CheckoutCom/CreditCard.php +++ b/app/PaymentDrivers/CheckoutCom/CreditCard.php @@ -17,7 +17,6 @@ use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; use App\Jobs\Util\SystemLogger; use App\Models\ClientGatewayToken; use App\Models\GatewayType; -use App\Models\Payment; use App\Models\SystemLog; use App\PaymentDrivers\CheckoutComPaymentDriver; use App\PaymentDrivers\Common\MethodInterface; @@ -25,8 +24,6 @@ use App\Utils\Traits\MakesHash; use Checkout\CheckoutApiException; use Checkout\CheckoutArgumentException; use Checkout\CheckoutAuthorizationException; -use Checkout\Library\Exceptions\CheckoutHttpException; -use Checkout\Models\Payments\IdSource; use Checkout\Payments\Four\Request\PaymentRequest; use Checkout\Payments\Four\Request\Source\RequestTokenSource; use Checkout\Payments\PaymentRequest as PaymentsPaymentRequest; @@ -128,7 +125,7 @@ class CreditCard implements MethodInterface $http_status_code = $e->http_status_code ?: ''; $error_details = $e->error_details; - if(is_array($error_details)) { + if (is_array($error_details)) { $error_details = end($e->error_details['error_codes']); } @@ -137,13 +134,12 @@ class CreditCard implements MethodInterface $human_exception = "{$human_exception} - Request ID: {$request_id}"; throw new PaymentFailed($human_exception, $http_status_code); - } catch (CheckoutArgumentException $e) { // Bad arguments $error_details = $e->error_details; - if(is_array($error_details)) { + if (is_array($error_details)) { $error_details = end($e->error_details['error_codes']); } @@ -155,7 +151,7 @@ class CreditCard implements MethodInterface $error_details = $e->error_details; - if(is_array($error_details)) { + if (is_array($error_details)) { $error_details = end($e->error_details['error_codes']); } @@ -230,7 +226,7 @@ class CreditCard implements MethodInterface private function completePayment($paymentRequest, PaymentResponseRequest $request) { $paymentRequest->amount = $this->checkout->payment_hash->data->value; - $paymentRequest->reference = substr($this->checkout->getDescription(),0 , 49); + $paymentRequest->reference = substr($this->checkout->getDescription(), 0, 49); $paymentRequest->customer = $this->checkout->getCustomer(); $paymentRequest->metadata = ['udf1' => 'Invoice Ninja']; $paymentRequest->currency = $this->checkout->client->getCurrencyCode(); @@ -255,7 +251,6 @@ class CreditCard implements MethodInterface } try { - $response = $this->checkout->gateway->getPaymentsClient()->requestPayment($paymentRequest); if ($response['status'] == 'Authorized') { @@ -289,7 +284,7 @@ class CreditCard implements MethodInterface $http_status_code = $e->http_status_code; $error_details = $e->error_details; - if(is_array($error_details)) { + if (is_array($error_details)) { $error_details = end($e->error_details['error_codes']); } @@ -297,14 +292,14 @@ class CreditCard implements MethodInterface $human_exception = $error_details ? new \Exception($error_details, 400) : $e; - SystemLogger::dispatch( - $human_exception->getMessage(), - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_ERROR, - SystemLog::TYPE_CHECKOUT, - $this->checkout->client, - $this->checkout->client->company, - ); + SystemLogger::dispatch( + $human_exception->getMessage(), + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_ERROR, + SystemLog::TYPE_CHECKOUT, + $this->checkout->client, + $this->checkout->client->company, + ); return $this->checkout->processInternallyFailedPayment($this->checkout, $human_exception); } catch (CheckoutArgumentException $e) { @@ -312,7 +307,7 @@ class CreditCard implements MethodInterface $error_details = $e->error_details; - if(is_array($error_details)) { + if (is_array($error_details)) { $error_details = end($e->error_details['error_codes']); } @@ -320,14 +315,14 @@ class CreditCard implements MethodInterface $human_exception = $error_details ? new \Exception($error_details, 400) : $e; - SystemLogger::dispatch( - $human_exception->getMessage(), - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_ERROR, - SystemLog::TYPE_CHECKOUT, - $this->checkout->client, - $this->checkout->client->company, - ); + SystemLogger::dispatch( + $human_exception->getMessage(), + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_ERROR, + SystemLog::TYPE_CHECKOUT, + $this->checkout->client, + $this->checkout->client->company, + ); return $this->checkout->processInternallyFailedPayment($this->checkout, $human_exception); } catch (CheckoutAuthorizationException $e) { @@ -335,7 +330,7 @@ class CreditCard implements MethodInterface $error_details = $e->error_details; - if(is_array($error_details)) { + if (is_array($error_details)) { $error_details = end($e->error_details['error_codes']); } @@ -344,14 +339,14 @@ class CreditCard implements MethodInterface $human_exception = $error_details ? new \Exception($error_details, 400) : $e; - SystemLogger::dispatch( - $human_exception->getMessage(), - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_ERROR, - SystemLog::TYPE_CHECKOUT, - $this->checkout->client, - $this->checkout->client->company, - ); + SystemLogger::dispatch( + $human_exception->getMessage(), + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_ERROR, + SystemLog::TYPE_CHECKOUT, + $this->checkout->client, + $this->checkout->client->company, + ); return $this->checkout->processInternallyFailedPayment($this->checkout, $human_exception); } diff --git a/app/PaymentDrivers/CheckoutCom/Utilities.php b/app/PaymentDrivers/CheckoutCom/Utilities.php index 121406289b20..764eb224c07e 100644 --- a/app/PaymentDrivers/CheckoutCom/Utilities.php +++ b/app/PaymentDrivers/CheckoutCom/Utilities.php @@ -15,9 +15,7 @@ namespace App\PaymentDrivers\CheckoutCom; use App\Exceptions\PaymentFailed; use App\Jobs\Util\SystemLogger; use App\Models\GatewayType; -use App\Models\PaymentType; use App\Models\SystemLog; -use Checkout\Models\Payments\Payment; use Exception; use stdClass; @@ -84,7 +82,6 @@ trait Utilities public function processUnsuccessfulPayment($_payment, $throw_exception = true) { - $error_message = ''; nlog("checkout failure"); @@ -92,8 +89,7 @@ trait Utilities if (is_array($_payment) && array_key_exists('status', $_payment)) { $error_message = $_payment['status']; - } - else { + } else { $error_message = 'Error processing payment.'; } diff --git a/app/PaymentDrivers/CheckoutComPaymentDriver.php b/app/PaymentDrivers/CheckoutComPaymentDriver.php index 74a33e8fc751..d9c2dab2d5c2 100644 --- a/app/PaymentDrivers/CheckoutComPaymentDriver.php +++ b/app/PaymentDrivers/CheckoutComPaymentDriver.php @@ -38,8 +38,6 @@ use Checkout\Common\Phone; use Checkout\Customers\CustomerRequest; use Checkout\Customers\Four\CustomerRequest as FourCustomerRequest; use Checkout\Environment; -use Checkout\Library\Exceptions\CheckoutHttpException; -use Checkout\Models\Payments\IdSource; use Checkout\Models\Payments\Refund; use Checkout\Payments\Four\Request\PaymentRequest; use Checkout\Payments\Four\Request\Source\RequestIdSource as SourceRequestIdSource; @@ -214,7 +212,6 @@ class CheckoutComPaymentDriver extends BaseDriver } catch (CheckoutApiException $e) { // API error throw new PaymentFailed($e->getMessage(), $e->getCode()); - } catch (CheckoutArgumentException $e) { // Bad arguments @@ -248,73 +245,69 @@ class CheckoutComPaymentDriver extends BaseDriver $response = $this->gateway->getCustomersClient()->get($this->client->present()->email()); return $response; - } catch (\Exception $e) { - if ($this->is_four_api) { $request = new FourCustomerRequest(); - } - else{ + } else { $request = new CustomerRequest(); } - $phone = new Phone(); - // $phone->number = $this->client->present()->phone(); - $phone->number = substr(str_pad($this->client->present()->phone(),6, "0", STR_PAD_RIGHT), 0 , 24); + $phone = new Phone(); + // $phone->number = $this->client->present()->phone(); + $phone->number = substr(str_pad($this->client->present()->phone(), 6, "0", STR_PAD_RIGHT), 0, 24); - $request->email = $this->client->present()->email(); - $request->name = $this->client->present()->name(); - $request->phone = $phone; + $request->email = $this->client->present()->email(); + $request->name = $this->client->present()->name(); + $request->phone = $phone; - try { - $response = $this->gateway->getCustomersClient()->create($request); - } - catch (CheckoutApiException $e) { - // API error - $request_id = $e->request_id; - $http_status_code = $e->http_status_code; - $error_details = $e->error_details; + try { + $response = $this->gateway->getCustomersClient()->create($request); + } catch (CheckoutApiException $e) { + // API error + $request_id = $e->request_id; + $http_status_code = $e->http_status_code; + $error_details = $e->error_details; - if(is_array($error_details)) { - $error_details = end($e->error_details['error_codes']); - } - - $human_exception = $error_details ? new \Exception($error_details, 400) : $e; - - - throw new PaymentFailed($human_exception); - } catch (CheckoutArgumentException $e) { - // Bad arguments - - $error_details = $e->error_details; - - if(is_array($error_details)) { - $error_details = end($e->error_details['error_codes']); - } - - $human_exception = $error_details ? new \Exception($error_details, 400) : $e; - - throw new PaymentFailed($human_exception); - } catch (CheckoutAuthorizationException $e) { - // Bad Invalid authorization - - $error_details = $e->error_details; - - if(is_array($error_details)) { - $error_details = end($e->error_details['error_codes']); - } - - $human_exception = $error_details ? new \Exception($error_details, 400) : $e; - - throw new PaymentFailed($human_exception); + if (is_array($error_details)) { + $error_details = end($e->error_details['error_codes']); } + $human_exception = $error_details ? new \Exception($error_details, 400) : $e; - // catch (\Exception $e) { + throw new PaymentFailed($human_exception); + } catch (CheckoutArgumentException $e) { + // Bad arguments + + $error_details = $e->error_details; + + if (is_array($error_details)) { + $error_details = end($e->error_details['error_codes']); + } + + $human_exception = $error_details ? new \Exception($error_details, 400) : $e; + + throw new PaymentFailed($human_exception); + } catch (CheckoutAuthorizationException $e) { + // Bad Invalid authorization + + $error_details = $e->error_details; + + if (is_array($error_details)) { + $error_details = end($e->error_details['error_codes']); + } + + $human_exception = $error_details ? new \Exception($error_details, 400) : $e; + + throw new PaymentFailed($human_exception); + } + + + + // catch (\Exception $e) { // // API error // throw new PaymentFailed($e->getMessage(), $e->getCode()); - // } + // } return $response; } @@ -408,8 +401,9 @@ class CheckoutComPaymentDriver extends BaseDriver $error_details = ''; - if(property_exists($e, 'error_details')) + if (property_exists($e, 'error_details')) { $error_details = $e->error_details; + } $data = [ 'status' => $e->error_details, @@ -439,7 +433,6 @@ class CheckoutComPaymentDriver extends BaseDriver public function process3dsConfirmation(Checkout3dsRequest $request) { - $this->init(); $this->setPaymentHash($request->getPaymentHash()); diff --git a/app/PaymentDrivers/CustomPaymentDriver.php b/app/PaymentDrivers/CustomPaymentDriver.php index 6a95a6f05643..6cc437e53494 100644 --- a/app/PaymentDrivers/CustomPaymentDriver.php +++ b/app/PaymentDrivers/CustomPaymentDriver.php @@ -17,7 +17,6 @@ use App\Models\GatewayType; use App\Models\Invoice; use App\Models\Payment; use App\Utils\HtmlEngine; -use App\Utils\Number; use App\Utils\Traits\MakesHash; /** diff --git a/app/PaymentDrivers/Eway/CreditCard.php b/app/PaymentDrivers/Eway/CreditCard.php index 9c9690aafc90..f93057719b34 100644 --- a/app/PaymentDrivers/Eway/CreditCard.php +++ b/app/PaymentDrivers/Eway/CreditCard.php @@ -14,18 +14,11 @@ namespace App\PaymentDrivers\Eway; use App\Exceptions\PaymentFailed; use App\Jobs\Util\SystemLogger; -use App\Models\ClientGatewayToken; use App\Models\GatewayType; -use App\Models\Payment; -use App\Models\PaymentHash; use App\Models\PaymentType; use App\Models\SystemLog; -use App\PaymentDrivers\Eway\ErrorCode; use App\PaymentDrivers\EwayPaymentDriver; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; class CreditCard { diff --git a/app/PaymentDrivers/Eway/Token.php b/app/PaymentDrivers/Eway/Token.php index 7207ef13fa97..8deaf344bee0 100644 --- a/app/PaymentDrivers/Eway/Token.php +++ b/app/PaymentDrivers/Eway/Token.php @@ -12,20 +12,12 @@ namespace App\PaymentDrivers\Eway; -use App\Exceptions\PaymentFailed; -use App\Jobs\Util\SystemLogger; use App\Models\ClientGatewayToken; use App\Models\GatewayType; -use App\Models\Payment; use App\Models\PaymentHash; use App\Models\PaymentType; -use App\Models\SystemLog; -use App\PaymentDrivers\Eway\ErrorCode; use App\PaymentDrivers\EwayPaymentDriver; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; class Token { diff --git a/app/PaymentDrivers/EwayPaymentDriver.php b/app/PaymentDrivers/EwayPaymentDriver.php index 1db813f41120..3e7dca733f8b 100644 --- a/app/PaymentDrivers/EwayPaymentDriver.php +++ b/app/PaymentDrivers/EwayPaymentDriver.php @@ -192,28 +192,20 @@ class EwayPaymentDriver extends BaseDriver } if ($this->company_gateway->require_custom_value1) { - $fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value2) { - $fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value3) { - $fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value4) { - $fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required']; - } diff --git a/app/PaymentDrivers/Forte/ACH.php b/app/PaymentDrivers/Forte/ACH.php index 21c30530250e..87ad4d3d1013 100644 --- a/app/PaymentDrivers/Forte/ACH.php +++ b/app/PaymentDrivers/Forte/ACH.php @@ -12,16 +12,16 @@ namespace App\PaymentDrivers\Forte; -use App\Models\Payment; +use App\Http\Requests\Request; +use App\Jobs\Util\SystemLogger; use App\Models\GatewayType; +use App\Models\Payment; use App\Models\PaymentHash; use App\Models\PaymentType; -use App\Http\Requests\Request; +use App\Models\SystemLog; +use App\PaymentDrivers\FortePaymentDriver; use App\Utils\Traits\MakesHash; use Illuminate\Support\Facades\Validator; -use App\PaymentDrivers\FortePaymentDriver; -use App\Jobs\Util\SystemLogger; -use App\Models\SystemLog; class ACH { @@ -41,7 +41,7 @@ class ACH $this->forte = $forte; $this->forte_base_uri = "https://sandbox.forte.net/api/v3/"; - if($this->forte->company_gateway->getConfigField('testMode') == false){ + if ($this->forte->company_gateway->getConfigField('testMode') == false) { $this->forte_base_uri = "https://api.forte.net/v3/"; } $this->forte_api_access_id = $this->forte->company_gateway->getConfigField('apiAccessId'); @@ -60,7 +60,6 @@ class ACH public function authorizeResponse(Request $request) { - $payment_meta = new \stdClass; $payment_meta->brand = (string)ctrans('texts.ach'); $payment_meta->last4 = (string) $request->last_4; @@ -93,7 +92,7 @@ class ACH try { $curl = curl_init(); - curl_setopt_array($curl, array( + curl_setopt_array($curl, [ CURLOPT_URL => $this->forte_base_uri.'organizations/'.$this->forte_organization_id.'/locations/'.$this->forte_location_id.'/transactions', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', @@ -116,13 +115,13 @@ class ACH "one_time_token":"'.$request->payment_token.'" } }', - CURLOPT_HTTPHEADER => array( + CURLOPT_HTTPHEADER => [ 'X-Forte-Auth-Organization-Id: '.$this->forte_organization_id, 'Content-Type: application/json', 'Authorization: Basic '.base64_encode($this->forte_api_access_id.':'.$this->forte_secure_key), 'Cookie: visid_incap_621087=u18+3REYR/iISgzZxOF5s2ODW2IAAAAAQUIPAAAAAADuGqKgECQLS81FcSDrmhGe; nlbi_621087=YHngadhJ2VU+yr7/R1efXgAAAAD3mQyhqmnLls8PRu4iN58G; incap_ses_1136_621087=CVdrXUdhIlm9WJNDieLDD4QVXGIAAAAAvBwvkUcwhM0+OwvdPm2stg==' - ), - )); + ], + ]); $response = curl_exec($curl); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); diff --git a/app/PaymentDrivers/Forte/CreditCard.php b/app/PaymentDrivers/Forte/CreditCard.php index 2b851a88b7fb..c4a893a4fb02 100644 --- a/app/PaymentDrivers/Forte/CreditCard.php +++ b/app/PaymentDrivers/Forte/CreditCard.php @@ -12,17 +12,16 @@ namespace App\PaymentDrivers\Forte; -use App\Models\Payment; -use App\Models\GatewayType; -use App\Models\PaymentHash; -use App\Models\PaymentType; -use App\Utils\Traits\MakesHash; -use Illuminate\Support\Facades\Session; -use Illuminate\Support\Facades\Validator; -use App\PaymentDrivers\FortePaymentDriver; use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; use App\Jobs\Util\SystemLogger; +use App\Models\GatewayType; +use App\Models\Payment; +use App\Models\PaymentHash; +use App\Models\PaymentType; use App\Models\SystemLog; +use App\PaymentDrivers\FortePaymentDriver; +use App\Utils\Traits\MakesHash; +use Illuminate\Support\Facades\Validator; class CreditCard { @@ -42,9 +41,9 @@ class CreditCard $this->forte = $forte; $this->forte_base_uri = "https://sandbox.forte.net/api/v3/"; - if($this->forte->company_gateway->getConfigField('testMode') == false){ - $this->forte_base_uri = "https://api.forte.net/v3/"; - } + if ($this->forte->company_gateway->getConfigField('testMode') == false) { + $this->forte_base_uri = "https://api.forte.net/v3/"; + } $this->forte_api_access_id = $this->forte->company_gateway->getConfigField('apiAccessId'); $this->forte_secure_key = $this->forte->company_gateway->getConfigField('secureKey'); $this->forte_auth_organization_id = $this->forte->company_gateway->getConfigField('authOrganizationId'); @@ -96,15 +95,14 @@ class CreditCard $fees_and_limits = $this->forte->company_gateway->getFeesAndLimits(GatewayType::CREDIT_CARD); - if(property_exists($fees_and_limits, 'fee_percent') && $fees_and_limits->fee_percent > 0) - { + if (property_exists($fees_and_limits, 'fee_percent') && $fees_and_limits->fee_percent > 0) { $fee_total = 0; - for ($i = ($invoice_totals * 100) ; $i < ($amount_with_fee * 100); $i++) { - $calculated_fee = ( 3 * $i) / 100; - $calculated_amount_with_fee = round(($i + $calculated_fee) / 100,2); + for ($i = ($invoice_totals * 100) ; $i < ($amount_with_fee * 100); $i++) { + $calculated_fee = (3 * $i) / 100; + $calculated_amount_with_fee = round(($i + $calculated_fee) / 100, 2); if ($calculated_amount_with_fee == $amount_with_fee) { - $fee_total = round($calculated_fee / 100,2); + $fee_total = round($calculated_fee / 100, 2); $amount_with_fee = $calculated_amount_with_fee; break; } @@ -114,7 +112,7 @@ class CreditCard try { $curl = curl_init(); - curl_setopt_array($curl, array( + curl_setopt_array($curl, [ CURLOPT_URL => $this->forte_base_uri.'organizations/'.$this->forte_organization_id.'/locations/'.$this->forte_location_id.'/transactions', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', @@ -135,12 +133,12 @@ class CreditCard "one_time_token":"'.$request->payment_token.'" } }', - CURLOPT_HTTPHEADER => array( + CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'X-Forte-Auth-Organization-Id: '.$this->forte_organization_id, 'Authorization: Basic '.base64_encode($this->forte_api_access_id.':'.$this->forte_secure_key) - ), - )); + ], + ]); $response = curl_exec($curl); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); diff --git a/app/PaymentDrivers/FortePaymentDriver.php b/app/PaymentDrivers/FortePaymentDriver.php index c867a09198c8..0622f33c9b6b 100644 --- a/app/PaymentDrivers/FortePaymentDriver.php +++ b/app/PaymentDrivers/FortePaymentDriver.php @@ -11,13 +11,13 @@ namespace App\PaymentDrivers; -use App\Models\Payment; use App\Jobs\Util\SystemLogger; -use App\Models\SystemLog; use App\Models\GatewayType; -use App\Utils\Traits\MakesHash; +use App\Models\Payment; +use App\Models\SystemLog; use App\PaymentDrivers\Forte\ACH; use App\PaymentDrivers\Forte\CreditCard; +use App\Utils\Traits\MakesHash; class FortePaymentDriver extends BaseDriver { @@ -45,8 +45,8 @@ class FortePaymentDriver extends BaseDriver { $types = []; - $types[] = GatewayType::CREDIT_CARD; - $types[] = GatewayType::BANK_TRANSFER; + $types[] = GatewayType::CREDIT_CARD; + $types[] = GatewayType::BANK_TRANSFER; return $types; } @@ -83,9 +83,9 @@ class FortePaymentDriver extends BaseDriver public function refund(Payment $payment, $amount, $return_client_response = false) { $forte_base_uri = "https://sandbox.forte.net/api/v3/"; - if($this->company_gateway->getConfigField('testMode') == false){ - $forte_base_uri = "https://api.forte.net/v3/"; - } + if ($this->company_gateway->getConfigField('testMode') == false) { + $forte_base_uri = "https://api.forte.net/v3/"; + } $forte_api_access_id = $this->company_gateway->getConfigField('apiAccessId'); $forte_secure_key = $this->company_gateway->getConfigField('secureKey'); $forte_auth_organization_id = $this->company_gateway->getConfigField('authOrganizationId'); @@ -95,7 +95,7 @@ class FortePaymentDriver extends BaseDriver try { $curl = curl_init(); - curl_setopt_array($curl, array( + curl_setopt_array($curl, [ CURLOPT_URL => $forte_base_uri.'organizations/'.$forte_organization_id.'/locations/'.$forte_location_id.'/transactions', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', @@ -110,12 +110,12 @@ class FortePaymentDriver extends BaseDriver "original_transaction_id":"'.$payment->transaction_reference.'", "authorization_code": "9ZQ754" }', - CURLOPT_HTTPHEADER => array( + CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'X-Forte-Auth-Organization-Id: '.$forte_organization_id, 'Authorization: Basic '.base64_encode($forte_api_access_id.':'.$forte_secure_key) - ), - )); + ], + ]); $response = curl_exec($curl); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); @@ -123,7 +123,6 @@ class FortePaymentDriver extends BaseDriver curl_close($curl); $response=json_decode($response); - } catch (\Throwable $th) { $message = [ 'action' => 'error', diff --git a/app/PaymentDrivers/GoCardless/ACH.php b/app/PaymentDrivers/GoCardless/ACH.php index ad9838d0c3cb..f84b319e9199 100644 --- a/app/PaymentDrivers/GoCardless/ACH.php +++ b/app/PaymentDrivers/GoCardless/ACH.php @@ -15,7 +15,6 @@ namespace App\PaymentDrivers\GoCardless; use App\Exceptions\PaymentFailed; use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; use App\Jobs\Util\SystemLogger; -use App\Models\ClientGatewayToken; use App\Models\GatewayType; use App\Models\Invoice; use App\Models\Payment; diff --git a/app/PaymentDrivers/GoCardless/DirectDebit.php b/app/PaymentDrivers/GoCardless/DirectDebit.php index 382fda70c872..edb853ba3d85 100644 --- a/app/PaymentDrivers/GoCardless/DirectDebit.php +++ b/app/PaymentDrivers/GoCardless/DirectDebit.php @@ -16,7 +16,6 @@ use App\Exceptions\PaymentFailed; use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; use App\Jobs\Mail\PaymentFailureMailer; use App\Jobs\Util\SystemLogger; -use App\Models\ClientGatewayToken; use App\Models\GatewayType; use App\Models\Invoice; use App\Models\Payment; diff --git a/app/PaymentDrivers/GoCardless/SEPA.php b/app/PaymentDrivers/GoCardless/SEPA.php index ee0e2a264c6f..df92a500b3a6 100644 --- a/app/PaymentDrivers/GoCardless/SEPA.php +++ b/app/PaymentDrivers/GoCardless/SEPA.php @@ -15,7 +15,6 @@ namespace App\PaymentDrivers\GoCardless; use App\Exceptions\PaymentFailed; use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; use App\Jobs\Util\SystemLogger; -use App\Models\ClientGatewayToken; use App\Models\GatewayType; use App\Models\Invoice; use App\Models\Payment; diff --git a/app/PaymentDrivers/GoCardlessPaymentDriver.php b/app/PaymentDrivers/GoCardlessPaymentDriver.php index 2b57a6578f1e..a1f6f49ee709 100644 --- a/app/PaymentDrivers/GoCardlessPaymentDriver.php +++ b/app/PaymentDrivers/GoCardlessPaymentDriver.php @@ -11,7 +11,6 @@ namespace App\PaymentDrivers; -use App\Events\Payment\PaymentFailed; use App\Http\Requests\Payments\PaymentWebhookRequest; use App\Jobs\Util\SystemLogger; use App\Models\ClientGatewayToken; @@ -282,11 +281,10 @@ class GoCardlessPaymentDriver extends BaseDriver //after i resolve the payment hash, ensure the invoice has not been marked as paid and the payment does not already exist. //if it does exist, ensure it is completed and not pending. - if($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) { - + if ($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) { $hash = PaymentHash::whereJsonContains('data->billing_request', $event['links']['billing_request'])->first(); - if(!$hash){ + if (!$hash) { nlog("GoCardless: couldn't find a hash, need to abort => Billing Request => " . $event['links']['billing_request']); return response()->json([], 200); } @@ -302,40 +300,34 @@ class GoCardlessPaymentDriver extends BaseDriver ); if ($billing_request->status === 'fulfilled') { - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($hash->invoices(), 'invoice_id')))->withTrashed()->get(); $this->client = $invoices->first()->client; - $invoices->each(function ($invoice){ - + $invoices->each(function ($invoice) { //if payments exist already, they just need to be confirmed. - if($invoice->payments()->exists()){ - - $invoice->payments()->where('status_id', 1)->cursor()->each(function ($payment){ + if ($invoice->payments()->exists()) { + $invoice->payments()->where('status_id', 1)->cursor()->each(function ($payment) { $payment->status_id = 4; $payment->save(); }); - } }); // remove all paid invoices - $invoices->filter(function ($invoice){ + $invoices->filter(function ($invoice) { return $invoice->isPayable(); }); //return early if nothing to do - if($invoices->count() == 0){ + if ($invoices->count() == 0) { nlog("GoCardless: Could not harvest any invoices - probably all paid!!"); return response()->json([], 200); } $this->processSuccessfulPayment($payment); } - } - } return response()->json([], 200); @@ -364,7 +356,6 @@ class GoCardlessPaymentDriver extends BaseDriver $this->client, $this->client->company, ); - } diff --git a/app/PaymentDrivers/Mollie/CreditCard.php b/app/PaymentDrivers/Mollie/CreditCard.php index 4049750d7801..252ca0356d5a 100644 --- a/app/PaymentDrivers/Mollie/CreditCard.php +++ b/app/PaymentDrivers/Mollie/CreditCard.php @@ -72,7 +72,7 @@ class CreditCard 'sequenceType' => 'recurring', 'description' => $description, 'webhookUrl' => $this->mollie->company_gateway->webhookUrl(), - 'idempotencyKey' => uniqid("st",true), + 'idempotencyKey' => uniqid("st", true), 'metadata' => [ 'client_id' => $this->mollie->client->hashed_id, 'hash' => $this->mollie->payment_hash->hash, @@ -93,11 +93,11 @@ class CreditCard if ($payment->status === 'open') { $this->mollie->payment_hash->withData('payment_id', $payment->id); - if(!$payment->getCheckoutUrl()) + if (!$payment->getCheckoutUrl()) { return render('gateways.mollie.mollie_placeholder'); - else + } else { return redirect()->away($payment->getCheckoutUrl()); - + } } } catch (\Exception $e) { return $this->processUnsuccessfulPayment($e); @@ -111,7 +111,7 @@ class CreditCard 'value' => $amount, ], 'description' => $description, - 'idempotencyKey' => uniqid("st",true), + 'idempotencyKey' => uniqid("st", true), 'redirectUrl' => route('mollie.3ds_redirect', [ 'company_key' => $this->mollie->client->company->company_key, 'company_gateway_id' => $this->mollie->company_gateway->hashed_id, @@ -161,10 +161,11 @@ class CreditCard nlog("Mollie"); nlog($payment); - if(!$payment->getCheckoutUrl()) + if (!$payment->getCheckoutUrl()) { return render('gateways.mollie.mollie_placeholder'); - else + } else { return redirect()->away($payment->getCheckoutUrl()); + } } } catch (\Exception $e) { $this->processUnsuccessfulPayment($e); diff --git a/app/PaymentDrivers/MolliePaymentDriver.php b/app/PaymentDrivers/MolliePaymentDriver.php index 51835b17c2d6..4572fb06711e 100644 --- a/app/PaymentDrivers/MolliePaymentDriver.php +++ b/app/PaymentDrivers/MolliePaymentDriver.php @@ -321,7 +321,6 @@ class MolliePaymentDriver extends BaseDriver // record from the meta data in the payment hash. if ($payment && property_exists($payment->metadata, 'hash') && $payment->metadata->hash) { - /* Harvest Payment Hash*/ $payment_hash = PaymentHash::where('hash', $payment->metadata->hash)->first(); diff --git a/app/PaymentDrivers/PayFast/CreditCard.php b/app/PaymentDrivers/PayFast/CreditCard.php index 0125d5ffb1b1..393de3b9c697 100644 --- a/app/PaymentDrivers/PayFast/CreditCard.php +++ b/app/PaymentDrivers/PayFast/CreditCard.php @@ -14,10 +14,8 @@ namespace App\PaymentDrivers\PayFast; use App\Exceptions\PaymentFailed; use App\Jobs\Util\SystemLogger; -use App\Models\ClientGatewayToken; use App\Models\GatewayType; use App\Models\Payment; -use App\Models\PaymentHash; use App\Models\PaymentType; use App\Models\SystemLog; use App\PaymentDrivers\PayFastPaymentDriver; diff --git a/app/PaymentDrivers/PayFast/Token.php b/app/PaymentDrivers/PayFast/Token.php index b7734ff4ff70..4d0ef8caea2a 100644 --- a/app/PaymentDrivers/PayFast/Token.php +++ b/app/PaymentDrivers/PayFast/Token.php @@ -12,19 +12,10 @@ namespace App\PaymentDrivers\PayFast; -use App\Exceptions\PaymentFailed; -use App\Jobs\Util\SystemLogger; use App\Models\ClientGatewayToken; -use App\Models\GatewayType; -use App\Models\Payment; use App\Models\PaymentHash; -use App\Models\PaymentType; -use App\Models\SystemLog; use App\PaymentDrivers\PayFastPaymentDriver; use GuzzleHttp\RequestOptions; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; class Token { @@ -62,7 +53,6 @@ class Token protected function generate_parameter_string($api_data, $sort_data_before_merge = true, $skip_empty_values = true) { - // if sorting is required the passphrase should be added in before sort. if (! empty($this->payfast->company_gateway->getConfigField('passphrase')) && $sort_data_before_merge) { $api_data['passphrase'] = $this->payfast->company_gateway->getConfigField('passphrase'); @@ -118,9 +108,10 @@ class Token private function send($headers, $body, $token) { $client = new \GuzzleHttp\Client( - [ - 'headers' => $headers, - ]); + [ + 'headers' => $headers, + ] + ); try { $response = $client->post("https://api.payfast.co.za/subscriptions/{$token}/adhoc?testing=true", [ diff --git a/app/PaymentDrivers/PayTrace/CreditCard.php b/app/PaymentDrivers/PayTrace/CreditCard.php index 4783126f4b50..a07f17e5ea4e 100644 --- a/app/PaymentDrivers/PayTrace/CreditCard.php +++ b/app/PaymentDrivers/PayTrace/CreditCard.php @@ -12,20 +12,15 @@ namespace App\PaymentDrivers\PayTrace; -use App\Exceptions\PaymentFailed; -use App\Jobs\Util\SystemLogger; use App\Models\ClientGatewayToken; use App\Models\GatewayType; use App\Models\Invoice; use App\Models\Payment; -use App\Models\PaymentHash; use App\Models\PaymentType; use App\Models\SystemLog; -use App\PaymentDrivers\PayFastPaymentDriver; use App\PaymentDrivers\PaytracePaymentDriver; use App\Utils\Traits\MakesHash; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; class CreditCard diff --git a/app/PaymentDrivers/PaytracePaymentDriver.php b/app/PaymentDrivers/PaytracePaymentDriver.php index 2aeb6d8e3079..33196ee1d32e 100644 --- a/app/PaymentDrivers/PaytracePaymentDriver.php +++ b/app/PaymentDrivers/PaytracePaymentDriver.php @@ -90,7 +90,6 @@ class PaytracePaymentDriver extends BaseDriver public function refund(Payment $payment, $amount, $return_client_response = false) { - $data = [ 'amount' => $amount, 'transaction_id' => $payment->transaction_reference, diff --git a/app/PaymentDrivers/Razorpay/Hosted.php b/app/PaymentDrivers/Razorpay/Hosted.php index 240b8e008d6e..24493c780b22 100644 --- a/app/PaymentDrivers/Razorpay/Hosted.php +++ b/app/PaymentDrivers/Razorpay/Hosted.php @@ -21,7 +21,6 @@ use App\Models\PaymentType; use App\Models\SystemLog; use App\PaymentDrivers\Common\MethodInterface; use App\PaymentDrivers\RazorpayPaymentDriver; -use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\View\View; diff --git a/app/PaymentDrivers/Sample/CreditCard.php b/app/PaymentDrivers/Sample/CreditCard.php index 2567e6a170ef..2165a56d83a2 100644 --- a/app/PaymentDrivers/Sample/CreditCard.php +++ b/app/PaymentDrivers/Sample/CreditCard.php @@ -12,18 +12,10 @@ namespace App\PaymentDrivers\Sample; -use App\Exceptions\PaymentFailed; -use App\Jobs\Util\SystemLogger; -use App\Models\ClientGatewayToken; use App\Models\GatewayType; use App\Models\Payment; -use App\Models\PaymentHash; use App\Models\PaymentType; -use App\Models\SystemLog; use App\Utils\Traits\MakesHash; -use Illuminate\Http\Request; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; class CreditCard { diff --git a/app/PaymentDrivers/Square/CreditCard.php b/app/PaymentDrivers/Square/CreditCard.php index cbb1f129a427..a8b75426caf4 100644 --- a/app/PaymentDrivers/Square/CreditCard.php +++ b/app/PaymentDrivers/Square/CreditCard.php @@ -203,7 +203,6 @@ class CreditCard implements MethodInterface private function createClient() { - $country = $this->square_driver->client->country ? $this->square_driver->client->country->iso_3166_2 : $this->square_driver->client->company->country()->iso_3166_2; /* Step two - create the customer */ diff --git a/app/PaymentDrivers/SquarePaymentDriver.php b/app/PaymentDrivers/SquarePaymentDriver.php index eb4a0bfec9ba..bb2e9f6fef1e 100644 --- a/app/PaymentDrivers/SquarePaymentDriver.php +++ b/app/PaymentDrivers/SquarePaymentDriver.php @@ -105,7 +105,6 @@ class SquarePaymentDriver extends BaseDriver /** @var ApiResponse */ $response = $this->square->getRefundsApi()->refund($body); - } public function tokenBilling(ClientGatewayToken $cgt, PaymentHash $payment_hash) diff --git a/app/PaymentDrivers/Stripe/ACH.php b/app/PaymentDrivers/Stripe/ACH.php index 066bd30a8533..cc1dee538202 100644 --- a/app/PaymentDrivers/Stripe/ACH.php +++ b/app/PaymentDrivers/Stripe/ACH.php @@ -13,7 +13,6 @@ namespace App\PaymentDrivers\Stripe; use App\Exceptions\PaymentFailed; -use App\Http\Requests\ClientPortal\PaymentMethod\VerifyPaymentMethodRequest; use App\Http\Requests\Request; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; @@ -27,6 +26,7 @@ use App\Models\PaymentHash; use App\Models\PaymentType; use App\Models\SystemLog; use App\PaymentDrivers\StripePaymentDriver; +use App\Utils\Number; use App\Utils\Traits\MakesHash; use Exception; use Stripe\Customer; @@ -36,7 +36,6 @@ use Stripe\Exception\CardException; use Stripe\Exception\InvalidRequestException; use Stripe\Exception\RateLimitException; use Stripe\PaymentIntent; -use App\Utils\Number; class ACH { @@ -69,7 +68,7 @@ class ACH $customer = $this->stripe->findOrCreateCustomer(); try { - $source = Customer::createSource($customer->id, ['source' => $stripe_response->token->id], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + $source = Customer::createSource($customer->id, ['source' => $stripe_response->token->id], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); } catch (InvalidRequestException $e) { throw new PaymentFailed($e->getMessage(), $e->getCode()); } @@ -96,22 +95,18 @@ class ACH public function updateBankAccount(array $event) { - $stripe_event = $event['data']['object']; $token = ClientGatewayToken::where('token', $stripe_event['id']) ->where('gateway_customer_reference', $stripe_event['customer']) ->first(); - if($token && isset($stripe_event['object']) && $stripe_event['object'] == 'bank_account' && isset($stripe_event['status']) && $stripe_event['status'] == 'verified') { - + if ($token && isset($stripe_event['object']) && $stripe_event['object'] == 'bank_account' && isset($stripe_event['status']) && $stripe_event['status'] == 'verified') { $meta = $token->meta; $meta->state = 'authorized'; $token->meta = $meta; $token->save(); - } - } public function verificationView(ClientGatewayToken $token) @@ -128,8 +123,7 @@ class ACH $bank_account = Customer::retrieveSource($token->gateway_customer_reference, $token->token, [], $this->stripe->stripe_connect_auth); /* Catch externally validated bank accounts and mark them as verified */ - if(isset($bank_account->status) && $bank_account->status == 'verified'){ - + if (isset($bank_account->status) && $bank_account->status == 'verified') { $meta = $token->meta; $meta->state = 'authorized'; $token->meta = $meta; @@ -138,7 +132,6 @@ class ACH return redirect() ->route('client.payment_methods.show', $token->hashed_id) ->with('message', __('texts.payment_method_verified')); - } $data = [ @@ -222,7 +215,8 @@ class ACH if (count($data['tokens']) == 0) { $intent = - $this->stripe->createPaymentIntent([ + $this->stripe->createPaymentIntent( + [ 'amount' => $data['amount'], 'currency' => $data['currency'], 'setup_future_usage' => 'off_session', @@ -338,23 +332,23 @@ class ACH $data['error_code'] = $e->getError()->code; $data['param'] = $e->getError()->param; $data['message'] = $e->getError()->message; - break; + break; case $e instanceof RateLimitException: $data['message'] = 'Too many requests made to the API too quickly'; - break; + break; case $e instanceof InvalidRequestException: $data['message'] = 'Invalid parameters were supplied to Stripe\'s API'; - break; + break; case $e instanceof AuthenticationException: $data['message'] = 'Authentication with Stripe\'s API failed'; - break; + break; case $e instanceof ApiErrorException: $data['message'] = 'Network communication with Stripe failed'; - break; + break; default: $data['message'] = $e->getMessage(); - break; + break; } $this->stripe->processInternallyFailedPayment($this->stripe, $e); diff --git a/app/PaymentDrivers/Stripe/ACSS.php b/app/PaymentDrivers/Stripe/ACSS.php index e9b0bdc09602..fb364ce25dab 100644 --- a/app/PaymentDrivers/Stripe/ACSS.php +++ b/app/PaymentDrivers/Stripe/ACSS.php @@ -55,7 +55,7 @@ class ACSS $customer = $this->stripe->findOrCreateCustomer(); try { - $source = Customer::createSource($customer->id, ['source' => $stripe_response->token->id], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + $source = Customer::createSource($customer->id, ['source' => $stripe_response->token->id], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); } catch (InvalidRequestException $e) { throw new PaymentFailed($e->getMessage(), $e->getCode()); } diff --git a/app/PaymentDrivers/Stripe/ApplePay.php b/app/PaymentDrivers/Stripe/ApplePay.php index 461eb0a48d90..d8aa015abe4c 100644 --- a/app/PaymentDrivers/Stripe/ApplePay.php +++ b/app/PaymentDrivers/Stripe/ApplePay.php @@ -12,14 +12,9 @@ namespace App\PaymentDrivers\Stripe; -use App\Exceptions\PaymentFailed; use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; -use App\Jobs\Util\SystemLogger; use App\Models\GatewayType; -use App\Models\Payment; -use App\Models\PaymentType; use App\Models\SystemLog; -use App\PaymentDrivers\Stripe\CreditCard; use App\PaymentDrivers\StripePaymentDriver; use App\Utils\Ninja; diff --git a/app/PaymentDrivers/Stripe/BECS.php b/app/PaymentDrivers/Stripe/BECS.php index 02233112ef6b..f2ccc0a69674 100644 --- a/app/PaymentDrivers/Stripe/BECS.php +++ b/app/PaymentDrivers/Stripe/BECS.php @@ -60,7 +60,7 @@ class BECS 'payment_hash' => $this->stripe->payment_hash->hash, 'gateway_type_id' => GatewayType::BECS, ], - ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; diff --git a/app/PaymentDrivers/Stripe/Bancontact.php b/app/PaymentDrivers/Stripe/Bancontact.php index 169b814bf952..f4aa0ba1c3c6 100644 --- a/app/PaymentDrivers/Stripe/Bancontact.php +++ b/app/PaymentDrivers/Stripe/Bancontact.php @@ -57,7 +57,7 @@ class Bancontact 'gateway_type_id' => GatewayType::BANCONTACT, ], - ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; @@ -81,7 +81,7 @@ class Bancontact $this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all()); $this->stripe->payment_hash->save(); - if (in_array($request->redirect_status, ['succeeded','pending'])) { + if (in_array($request->redirect_status, ['succeeded','pending'])) { return $this->processSuccessfulPayment($request->payment_intent); } diff --git a/app/PaymentDrivers/Stripe/Charge.php b/app/PaymentDrivers/Stripe/Charge.php index b65a594ba222..f40918129707 100644 --- a/app/PaymentDrivers/Stripe/Charge.php +++ b/app/PaymentDrivers/Stripe/Charge.php @@ -12,7 +12,6 @@ namespace App\PaymentDrivers\Stripe; -use App\Events\Payment\PaymentWasCreated; use App\Jobs\Util\SystemLogger; use App\Models\ClientGatewayToken; use App\Models\GatewayType; @@ -22,17 +21,13 @@ use App\Models\PaymentHash; use App\Models\PaymentType; use App\Models\SystemLog; use App\PaymentDrivers\StripePaymentDriver; -use App\PaymentDrivers\Stripe\ACH; -use App\Utils\Ninja; +use App\Utils\Number; use App\Utils\Traits\MakesHash; -use Stripe\Exception\ApiConnectionException; use Stripe\Exception\ApiErrorException; use Stripe\Exception\AuthenticationException; use Stripe\Exception\CardException; use Stripe\Exception\InvalidRequestException; use Stripe\Exception\RateLimitException; -use Stripe\StripeClient; -use App\Utils\Number; class Charge { @@ -95,7 +90,7 @@ class Charge $data['off_session'] = true; } - $response = $this->stripe->createPaymentIntent($data, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + $response = $this->stripe->createPaymentIntent($data, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); SystemLogger::dispatch($response, SystemLog::CATEGORY_GATEWAY_RESPONSE, SystemLog::EVENT_GATEWAY_SUCCESS, SystemLog::TYPE_STRIPE, $this->stripe->client, $this->stripe->client->company); } catch (\Exception $e) { @@ -114,23 +109,23 @@ class Charge $data['error_code'] = $e->getError()->code; $data['param'] = $e->getError()->param; $data['message'] = $e->getError()->message; - break; + break; case $e instanceof RateLimitException: $data['message'] = 'Too many requests made to the API too quickly'; - break; + break; case $e instanceof InvalidRequestException: $data['message'] = 'Invalid parameters were supplied to Stripe\'s API'; - break; + break; case $e instanceof AuthenticationException: $data['message'] = 'Authentication with Stripe\'s API failed'; - break; + break; case $e instanceof ApiErrorException: $data['message'] = 'Network communication with Stripe failed'; - break; + break; default: $data['message'] = $e->getMessage(); - break; + break; } $this->stripe->processInternallyFailedPayment($this->stripe, $e); @@ -146,21 +141,20 @@ class Charge $payment_method_type = PaymentType::SEPA; $status = Payment::STATUS_PENDING; } else { - - if(isset($response->latest_charge)) { + if (isset($response->latest_charge)) { $charge = \Stripe\Charge::retrieve($response->latest_charge, $this->stripe->stripe_connect_auth); $payment_method_type = $charge->payment_method_details->card->brand; - } - elseif(isset($response->charges->data[0]->payment_method_details->card->brand)) + } elseif (isset($response->charges->data[0]->payment_method_details->card->brand)) { $payment_method_type = $response->charges->data[0]->payment_method_details->card->brand; - else + } else { $payment_method_type = 'visa'; + } $status = Payment::STATUS_COMPLETED; } - if(!in_array($response?->status, ['succeeded', 'processing'])){ - $this->stripe->processInternallyFailedPayment($this->stripe, new \Exception('Auto billing failed.',400)); + if (!in_array($response?->status, ['succeeded', 'processing'])) { + $this->stripe->processInternallyFailedPayment($this->stripe, new \Exception('Auto billing failed.', 400)); } $data = [ diff --git a/app/PaymentDrivers/Stripe/Connect/Verify.php b/app/PaymentDrivers/Stripe/Connect/Verify.php index 50909b23fe19..01d165db5103 100644 --- a/app/PaymentDrivers/Stripe/Connect/Verify.php +++ b/app/PaymentDrivers/Stripe/Connect/Verify.php @@ -12,25 +12,10 @@ namespace App\PaymentDrivers\Stripe\Connect; -use App\Exceptions\PaymentFailed; use App\Exceptions\StripeConnectFailure; -use App\Http\Requests\ClientPortal\PaymentMethod\VerifyPaymentMethodRequest; -use App\Http\Requests\Request; -use App\Jobs\Mail\NinjaMailerJob; -use App\Jobs\Mail\NinjaMailerObject; -use App\Jobs\Util\SystemLogger; -use App\Mail\Gateways\ACHVerificationNotification; -use App\Models\ClientGatewayToken; -use App\Models\GatewayType; -use App\Models\Payment; -use App\Models\PaymentType; -use App\Models\SystemLog; use App\PaymentDrivers\StripePaymentDriver; use App\Utils\Traits\MakesHash; -use Exception; use Stripe\Customer; -use Stripe\Exception\CardException; -use Stripe\Exception\InvalidRequestException; class Verify { diff --git a/app/PaymentDrivers/Stripe/CreditCard.php b/app/PaymentDrivers/Stripe/CreditCard.php index eba69f01d373..fadce23f6ac7 100644 --- a/app/PaymentDrivers/Stripe/CreditCard.php +++ b/app/PaymentDrivers/Stripe/CreditCard.php @@ -19,11 +19,11 @@ use App\Models\GatewayType; use App\Models\Payment; use App\Models\PaymentType; use App\Models\SystemLog; -use App\PaymentDrivers\StripePaymentDriver; use App\PaymentDrivers\Stripe\Jobs\UpdateCustomer; +use App\PaymentDrivers\StripePaymentDriver; +use App\Utils\Number; use Stripe\PaymentIntent; use Stripe\PaymentMethod; -use App\Utils\Number; class CreditCard { @@ -60,7 +60,6 @@ class CreditCard public function paymentView(array $data) { - $invoice_numbers = collect($data['invoices'])->pluck('invoice_number')->implode(','); $description = ctrans('texts.stripe_payment_text', ['invoicenumber' => $invoice_numbers, 'amount' => Number::formatMoney($data['total']['amount_with_fee'], $this->stripe->client), 'client' => $this->stripe->client->present()->name()], $this->stripe->client->company->locale()); @@ -111,7 +110,7 @@ class CreditCard $state['store_card'] = false; } - $state['payment_intent'] = PaymentIntent::retrieve($state['server_response']->id, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + $state['payment_intent'] = PaymentIntent::retrieve($state['server_response']->id, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $state['customer'] = $state['payment_intent']->customer; $this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $state); @@ -169,12 +168,12 @@ class CreditCard //If the user has come from a subscription double check here if we need to redirect. //08-08-2022 - if($payment->invoices()->whereHas('subscription')->exists()){ + if ($payment->invoices()->whereHas('subscription')->exists()) { $subscription = $payment->invoices()->first()->subscription; - if($subscription && array_key_exists('return_url', $subscription->webhook_configuration) && strlen($subscription->webhook_configuration['return_url']) >=1) - return redirect($subscription->webhook_configuration['return_url']); - + if ($subscription && array_key_exists('return_url', $subscription->webhook_configuration) && strlen($subscription->webhook_configuration['return_url']) >=1) { + return redirect($subscription->webhook_configuration['return_url']); + } } //08-08-2022 diff --git a/app/PaymentDrivers/Stripe/EPS.php b/app/PaymentDrivers/Stripe/EPS.php index 8dbed6cae3ff..0608c715c4eb 100644 --- a/app/PaymentDrivers/Stripe/EPS.php +++ b/app/PaymentDrivers/Stripe/EPS.php @@ -56,7 +56,7 @@ class EPS 'payment_hash' => $this->stripe->payment_hash->hash, 'gateway_type_id' => GatewayType::EPS, ], - ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; @@ -80,7 +80,7 @@ class EPS $this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all()); $this->stripe->payment_hash->save(); - if (in_array($request->redirect_status, ['succeeded','pending'])) { + if (in_array($request->redirect_status, ['succeeded','pending'])) { return $this->processSuccessfulPayment($request->payment_intent); } diff --git a/app/PaymentDrivers/Stripe/FPX.php b/app/PaymentDrivers/Stripe/FPX.php index 5fc7010f8297..fa835e4eb59e 100644 --- a/app/PaymentDrivers/Stripe/FPX.php +++ b/app/PaymentDrivers/Stripe/FPX.php @@ -57,7 +57,7 @@ class FPX 'payment_hash' => $this->stripe->payment_hash->hash, 'gateway_type_id' => GatewayType::FPX, ], - ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; @@ -81,7 +81,7 @@ class FPX $this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all()); $this->stripe->payment_hash->save(); - if (in_array($request->redirect_status, ['succeeded','pending'])) { + if (in_array($request->redirect_status, ['succeeded','pending'])) { return $this->processSuccessfulPayment($request->payment_intent); } diff --git a/app/PaymentDrivers/Stripe/GIROPAY.php b/app/PaymentDrivers/Stripe/GIROPAY.php index ff52848fe5cf..167d790eeab0 100644 --- a/app/PaymentDrivers/Stripe/GIROPAY.php +++ b/app/PaymentDrivers/Stripe/GIROPAY.php @@ -56,7 +56,7 @@ class GIROPAY 'payment_hash' => $this->stripe->payment_hash->hash, 'gateway_type_id' => GatewayType::GIROPAY, ], - ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; @@ -80,7 +80,7 @@ class GIROPAY $this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all()); $this->stripe->payment_hash->save(); - if (in_array($request->redirect_status, ['succeeded','pending'])) { + if (in_array($request->redirect_status, ['succeeded','pending'])) { return $this->processSuccessfulPayment($request->payment_intent); } diff --git a/app/PaymentDrivers/Stripe/ImportCustomers.php b/app/PaymentDrivers/Stripe/ImportCustomers.php index 7395428d4231..387544bdb2c8 100644 --- a/app/PaymentDrivers/Stripe/ImportCustomers.php +++ b/app/PaymentDrivers/Stripe/ImportCustomers.php @@ -15,20 +15,16 @@ namespace App\PaymentDrivers\Stripe; use App\Exceptions\StripeConnectFailure; use App\Factory\ClientContactFactory; use App\Factory\ClientFactory; -use App\Factory\ClientGatewayTokenFactory; use App\Models\Client; use App\Models\ClientGatewayToken; use App\Models\Country; use App\Models\Currency; -use App\Models\GatewayType; -use App\PaymentDrivers\Stripe\UpdatePaymentMethods; use App\PaymentDrivers\StripePaymentDriver; use App\Utils\Ninja; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; use Illuminate\Database\QueryException; use Stripe\Customer; -use Stripe\PaymentMethod; class ImportCustomers { @@ -66,7 +62,7 @@ class ImportCustomers $this->addCustomer($customer); } - //handle + //handle // if(is_array($customers->data) && end($customers->data) && array_key_exists('id', end($customers->data))) // $starting_after = end($customers->data)['id']; // else @@ -74,9 +70,9 @@ class ImportCustomers $starting_after = isset(end($customers->data)['id']) ? end($customers->data)['id'] : false; - if(!$starting_after) + if (!$starting_after) { break; - + } } while ($customers->has_more); } @@ -140,7 +136,6 @@ class ImportCustomers $client->name = $customer->name ? $customer->name : $customer->email; if (! isset($client->number) || empty($client->number)) { - $x = 1; do { @@ -157,11 +152,7 @@ class ImportCustomers } } } while ($this->completed); - - - - } - else{ + } else { $client->save(); } diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php index ab466ed19afc..466c0c49dbf0 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentFailureWebhook.php @@ -12,16 +12,10 @@ namespace App\PaymentDrivers\Stripe\Jobs; use App\Jobs\Mail\PaymentFailedMailer; -use App\Jobs\Util\SystemLogger; use App\Libraries\MultiDB; use App\Models\Company; -use App\Models\CompanyGateway; -use App\Models\GatewayType; -use App\Models\Invoice; use App\Models\Payment; use App\Models\PaymentHash; -use App\Models\PaymentType; -use App\Models\SystemLog; use App\PaymentDrivers\Stripe\Utilities; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -99,11 +93,11 @@ class PaymentIntentFailureWebhook implements ShouldQueue } PaymentFailedMailer::dispatch( - $payment_hash, - $client->company, - $client, - $error - ); + $payment_hash, + $client->company, + $client, + $error + ); } } } diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php index e6ae4ea7f602..06ce90182ef3 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentProcessingWebhook.php @@ -22,7 +22,6 @@ use App\Models\Payment; use App\Models\PaymentHash; use App\Models\PaymentType; use App\Models\SystemLog; -use App\PaymentDrivers\Stripe\UpdatePaymentMethods; use App\PaymentDrivers\Stripe\Utilities; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -56,53 +55,50 @@ class PaymentIntentProcessingWebhook implements ShouldQueue /* Stub processing payment intents with a pending payment */ public function handle() { - MultiDB::findAndSetDbByCompanyKey($this->company_key); $company = Company::where('company_key', $this->company_key)->first(); - foreach ($this->stripe_request as $transaction) { - - if(array_key_exists('payment_intent', $transaction)) - { - $payment = Payment::query() - ->where('company_id', $company->id) - ->where('transaction_reference', $transaction['payment_intent']) - ->first(); - - } - else - { - $payment = Payment::query() - ->where('company_id', $company->id) - ->where('transaction_reference', $transaction['id']) - ->first(); - } - - if ($payment) { - $payment->status_id = Payment::STATUS_PENDING; - $payment->save(); - - $this->payment_completed = true; - } + foreach ($this->stripe_request as $transaction) { + if (array_key_exists('payment_intent', $transaction)) { + $payment = Payment::query() + ->where('company_id', $company->id) + ->where('transaction_reference', $transaction['payment_intent']) + ->first(); + } else { + $payment = Payment::query() + ->where('company_id', $company->id) + ->where('transaction_reference', $transaction['id']) + ->first(); } + if ($payment) { + $payment->status_id = Payment::STATUS_PENDING; + $payment->save(); + + $this->payment_completed = true; + } + } - if($this->payment_completed) + + if ($this->payment_completed) { return; + } $company_gateway = CompanyGateway::find($this->company_gateway_id); $stripe_driver = $company_gateway->driver()->init(); $charge_id = false; - if(isset($this->stripe_request['object']['charges']) && optional($this->stripe_request['object']['charges']['data'][0])['id']) - $charge_id = $this->stripe_request['object']['charges']['data'][0]['id']; // API VERSION 2018 - elseif (isset($this->stripe_request['object']['latest_charge'])) - $charge_id = $this->stripe_request['object']['latest_charge']; // API VERSION 2022-11-15 + if (isset($this->stripe_request['object']['charges']) && optional($this->stripe_request['object']['charges']['data'][0])['id']) { + $charge_id = $this->stripe_request['object']['charges']['data'][0]['id']; + } // API VERSION 2018 + elseif (isset($this->stripe_request['object']['latest_charge'])) { + $charge_id = $this->stripe_request['object']['latest_charge']; + } // API VERSION 2022-11-15 - if(!$charge_id){ + if (!$charge_id) { nlog("could not resolve charge"); return; } @@ -111,8 +107,7 @@ class PaymentIntentProcessingWebhook implements ShouldQueue $charge = \Stripe\Charge::retrieve($charge_id, $stripe_driver->stripe_connect_auth); - if(!$charge) - { + if (!$charge) { nlog("no charge found"); nlog($this->stripe_request); return; @@ -125,25 +120,26 @@ class PaymentIntentProcessingWebhook implements ShouldQueue ->where('transaction_reference', $charge['id']) ->first(); - //return early - if($payment && $payment->status_id == Payment::STATUS_PENDING){ - nlog(" payment found and status correct - returning "); + //return early + if ($payment && $payment->status_id == Payment::STATUS_PENDING) { + nlog(" payment found and status correct - returning "); return; - } - elseif($payment){ + } elseif ($payment) { $payment->status_id = Payment::STATUS_PENDING; $payment->save(); } $hash = isset($charge['metadata']['payment_hash']) ? $charge['metadata']['payment_hash'] : false; - if(!$hash) + if (!$hash) { return; + } $payment_hash = PaymentHash::where('hash', $hash)->first(); - if(!$payment_hash) + if (!$payment_hash) { return; + } $stripe_driver->client = $payment_hash->fee_invoice->client; @@ -164,18 +160,16 @@ class PaymentIntentProcessingWebhook implements ShouldQueue $company, ); - if(isset($pi['payment_method_types']) && in_array('us_bank_account', $pi['payment_method_types'])) - { - + if (isset($pi['payment_method_types']) && in_array('us_bank_account', $pi['payment_method_types'])) { $invoice = Invoice::with('client')->withTrashed()->find($payment_hash->fee_invoice_id); $client = $invoice->client; - if($invoice->is_deleted) + if ($invoice->is_deleted) { return; + } $this->updateAchPayment($payment_hash, $client, $meta); } - } private function updateAchPayment($payment_hash, $client, $meta) @@ -208,7 +202,6 @@ class PaymentIntentProcessingWebhook implements ShouldQueue ); try { - $customer = $driver->getCustomer($meta['customer']); $method = $driver->getStripePaymentMethod($meta['payment_method']); $payment_method = $meta['payment_method']; @@ -244,12 +237,9 @@ class PaymentIntentProcessingWebhook implements ShouldQueue } $driver->storeGatewayToken($data, $additional_data); - - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog("failed to import payment methods"); nlog($e->getMessage()); } } - -} \ No newline at end of file +} diff --git a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php index a79679d39bf9..5881d1196d82 100644 --- a/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/PaymentIntentWebhook.php @@ -22,7 +22,6 @@ use App\Models\Payment; use App\Models\PaymentHash; use App\Models\PaymentType; use App\Models\SystemLog; -use App\PaymentDrivers\Stripe\UpdatePaymentMethods; use App\PaymentDrivers\Stripe\Utilities; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -55,53 +54,50 @@ class PaymentIntentWebhook implements ShouldQueue public function handle() { - MultiDB::findAndSetDbByCompanyKey($this->company_key); $company = Company::where('company_key', $this->company_key)->first(); - foreach ($this->stripe_request as $transaction) { - - if(array_key_exists('payment_intent', $transaction)) - { - $payment = Payment::query() - ->where('company_id', $company->id) - ->where('transaction_reference', $transaction['payment_intent']) - ->first(); - - } - else - { - $payment = Payment::query() - ->where('company_id', $company->id) - ->where('transaction_reference', $transaction['id']) - ->first(); - } - - if ($payment) { - $payment->status_id = Payment::STATUS_COMPLETED; - $payment->save(); - - $this->payment_completed = true; - } + foreach ($this->stripe_request as $transaction) { + if (array_key_exists('payment_intent', $transaction)) { + $payment = Payment::query() + ->where('company_id', $company->id) + ->where('transaction_reference', $transaction['payment_intent']) + ->first(); + } else { + $payment = Payment::query() + ->where('company_id', $company->id) + ->where('transaction_reference', $transaction['id']) + ->first(); } + if ($payment) { + $payment->status_id = Payment::STATUS_COMPLETED; + $payment->save(); + + $this->payment_completed = true; + } + } - if($this->payment_completed) + + if ($this->payment_completed) { return; + } $company_gateway = CompanyGateway::find($this->company_gateway_id); $stripe_driver = $company_gateway->driver()->init(); $charge_id = false; - if(isset($this->stripe_request['object']['charges']) && optional($this->stripe_request['object']['charges']['data'][0])['id']) - $charge_id = $this->stripe_request['object']['charges']['data'][0]['id']; // API VERSION 2018 - elseif (isset($this->stripe_request['object']['latest_charge'])) - $charge_id = $this->stripe_request['object']['latest_charge']; // API VERSION 2022-11-15 + if (isset($this->stripe_request['object']['charges']) && optional($this->stripe_request['object']['charges']['data'][0])['id']) { + $charge_id = $this->stripe_request['object']['charges']['data'][0]['id']; + } // API VERSION 2018 + elseif (isset($this->stripe_request['object']['latest_charge'])) { + $charge_id = $this->stripe_request['object']['latest_charge']; + } // API VERSION 2022-11-15 - if(!$charge_id){ + if (!$charge_id) { nlog("could not resolve charge"); return; } @@ -110,8 +106,7 @@ class PaymentIntentWebhook implements ShouldQueue $charge = \Stripe\Charge::retrieve($charge_id, $stripe_driver->stripe_connect_auth); - if(!$charge) - { + if (!$charge) { nlog("no charge found"); nlog($this->stripe_request); return; @@ -124,25 +119,26 @@ class PaymentIntentWebhook implements ShouldQueue ->where('transaction_reference', $charge['id']) ->first(); - //return early - if($payment && $payment->status_id == Payment::STATUS_COMPLETED){ - nlog(" payment found and status correct - returning "); + //return early + if ($payment && $payment->status_id == Payment::STATUS_COMPLETED) { + nlog(" payment found and status correct - returning "); return; - } - elseif($payment){ + } elseif ($payment) { $payment->status_id = Payment::STATUS_COMPLETED; $payment->save(); } $hash = isset($charge['metadata']['payment_hash']) ? $charge['metadata']['payment_hash'] : false; - if(!$hash) + if (!$hash) { return; + } $payment_hash = PaymentHash::where('hash', $hash)->first(); - if(!$payment_hash) + if (!$payment_hash) { return; + } $stripe_driver->client = $payment_hash->fee_invoice->client; @@ -163,40 +159,34 @@ class PaymentIntentWebhook implements ShouldQueue $company, ); - if(isset($pi['allowed_source_types']) && in_array('card', $pi['allowed_source_types'])) - { - + if (isset($pi['allowed_source_types']) && in_array('card', $pi['allowed_source_types'])) { $invoice = Invoice::with('client')->withTrashed()->find($payment_hash->fee_invoice_id); $client = $invoice->client; - if($invoice->is_deleted) + if ($invoice->is_deleted) { return; + } $this->updateCreditCardPayment($payment_hash, $client, $meta); - } - elseif(isset($pi['payment_method_types']) && in_array('card', $pi['payment_method_types'])) - { - + } elseif (isset($pi['payment_method_types']) && in_array('card', $pi['payment_method_types'])) { $invoice = Invoice::with('client')->withTrashed()->find($payment_hash->fee_invoice_id); $client = $invoice->client; - if($invoice->is_deleted) + if ($invoice->is_deleted) { return; + } $this->updateCreditCardPayment($payment_hash, $client, $meta); - } - elseif(isset($pi['payment_method_types']) && in_array('us_bank_account', $pi['payment_method_types'])) - { - + } elseif (isset($pi['payment_method_types']) && in_array('us_bank_account', $pi['payment_method_types'])) { $invoice = Invoice::with('client')->withTrashed()->find($payment_hash->fee_invoice_id); $client = $invoice->client; - if($invoice->is_deleted) + if ($invoice->is_deleted) { return; + } $this->updateAchPayment($payment_hash, $client, $meta); } - } private function updateAchPayment($payment_hash, $client, $meta) @@ -229,7 +219,6 @@ class PaymentIntentWebhook implements ShouldQueue ); try { - $customer = $driver->getCustomer($meta['customer']); $method = $driver->getStripePaymentMethod($meta['payment_method']); $payment_method = $meta['payment_method']; @@ -265,9 +254,7 @@ class PaymentIntentWebhook implements ShouldQueue } $driver->storeGatewayToken($data, $additional_data); - - } - catch(\Exception $e){ + } catch(\Exception $e) { nlog("failed to import payment methods"); nlog($e->getMessage()); } @@ -335,7 +322,5 @@ class PaymentIntentWebhook implements ShouldQueue $client, $client->company, ); - } - -} \ No newline at end of file +} diff --git a/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php b/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php index 444bb4b55f4f..13a25a8bce1c 100644 --- a/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php +++ b/app/PaymentDrivers/Stripe/Jobs/StripeWebhook.php @@ -11,17 +11,9 @@ namespace App\PaymentDrivers\Stripe\Jobs; -use App\Jobs\Mail\PaymentFailedMailer; -use App\Jobs\Util\SystemLogger; use App\Libraries\MultiDB; use App\Models\Company; use App\Models\CompanyGateway; -use App\Models\GatewayType; -use App\Models\Invoice; -use App\Models\Payment; -use App\Models\PaymentHash; -use App\Models\PaymentType; -use App\Models\SystemLog; use App\PaymentDrivers\Stripe\Utilities; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; diff --git a/app/PaymentDrivers/Stripe/Jobs/UpdateCustomer.php b/app/PaymentDrivers/Stripe/Jobs/UpdateCustomer.php index 07de063c7dfd..af6e9d490646 100644 --- a/app/PaymentDrivers/Stripe/Jobs/UpdateCustomer.php +++ b/app/PaymentDrivers/Stripe/Jobs/UpdateCustomer.php @@ -11,18 +11,10 @@ namespace App\PaymentDrivers\Stripe\Jobs; -use App\Jobs\Mail\PaymentFailedMailer; -use App\Jobs\Util\SystemLogger; use App\Libraries\MultiDB; use App\Models\Client; use App\Models\Company; use App\Models\CompanyGateway; -use App\Models\GatewayType; -use App\Models\Invoice; -use App\Models\Payment; -use App\Models\PaymentHash; -use App\Models\PaymentType; -use App\Models\SystemLog; use App\PaymentDrivers\Stripe\Utilities; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; @@ -53,7 +45,6 @@ class UpdateCustomer implements ShouldQueue public function handle() { - MultiDB::findAndSetDbByCompanyKey($this->company_key); $company = Company::where('company_key', $this->company_key)->first(); @@ -61,8 +52,9 @@ class UpdateCustomer implements ShouldQueue $company_gateway = CompanyGateway::find($this->company_gateway_id); $client = Client::withTrashed()->find($this->client_id); - if(!$company_gateway->update_details) + if (!$company_gateway->update_details) { return; + } $stripe = $company_gateway->driver($client)->init(); @@ -87,6 +79,5 @@ class UpdateCustomer implements ShouldQueue $data['shipping']['address']['country'] = $client->shipping_country ? $client->shipping_country->iso_3166_2 : ''; \Stripe\Customer::update($customer->id, $data, $stripe->stripe_connect_auth); - } } diff --git a/app/PaymentDrivers/Stripe/Klarna.php b/app/PaymentDrivers/Stripe/Klarna.php index 1a4cedd588a3..c15660c867c1 100644 --- a/app/PaymentDrivers/Stripe/Klarna.php +++ b/app/PaymentDrivers/Stripe/Klarna.php @@ -20,7 +20,6 @@ use App\Models\PaymentType; use App\Models\SystemLog; use App\PaymentDrivers\StripePaymentDriver; use App\Utils\Number; -use Illuminate\Support\Facades\Cache; class Klarna { @@ -68,7 +67,7 @@ class Klarna 'payment_hash' => $this->stripe->payment_hash->hash, 'gateway_type_id' => GatewayType::KLARNA, ], - ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; @@ -92,7 +91,7 @@ class Klarna $this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all()); $this->stripe->payment_hash->save(); - if (in_array($request->redirect_status, ['succeeded','pending'])) { + if (in_array($request->redirect_status, ['succeeded','pending'])) { return $this->processSuccessfulPayment($request->payment_intent); } @@ -101,7 +100,6 @@ class Klarna public function processSuccessfulPayment(string $payment_intent) { - $this->stripe->init(); //catch duplicate submissions. diff --git a/app/PaymentDrivers/Stripe/PRZELEWY24.php b/app/PaymentDrivers/Stripe/PRZELEWY24.php index 190b4e5dce37..206633034944 100644 --- a/app/PaymentDrivers/Stripe/PRZELEWY24.php +++ b/app/PaymentDrivers/Stripe/PRZELEWY24.php @@ -56,7 +56,7 @@ class PRZELEWY24 'payment_hash' => $this->stripe->payment_hash->hash, 'gateway_type_id' => GatewayType::PRZELEWY24, ], - ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; @@ -80,7 +80,7 @@ class PRZELEWY24 $this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all()); $this->stripe->payment_hash->save(); - if (in_array($request->redirect_status, ['succeeded','pending'])) { + if (in_array($request->redirect_status, ['succeeded','pending'])) { return $this->processSuccessfulPayment($request->payment_intent); } diff --git a/app/PaymentDrivers/Stripe/SEPA.php b/app/PaymentDrivers/Stripe/SEPA.php index 0500d46ee948..407aac4edc11 100644 --- a/app/PaymentDrivers/Stripe/SEPA.php +++ b/app/PaymentDrivers/Stripe/SEPA.php @@ -67,7 +67,7 @@ class SEPA ], ]; - $intent = \Stripe\PaymentIntent::create($intent_data, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + $intent = \Stripe\PaymentIntent::create($intent_data, array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; diff --git a/app/PaymentDrivers/Stripe/SOFORT.php b/app/PaymentDrivers/Stripe/SOFORT.php index 276fbe86347b..58067b9d5f18 100644 --- a/app/PaymentDrivers/Stripe/SOFORT.php +++ b/app/PaymentDrivers/Stripe/SOFORT.php @@ -56,7 +56,7 @@ class SOFORT 'payment_hash' => $this->stripe->payment_hash->hash, 'gateway_type_id' => GatewayType::SOFORT, ], - ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; @@ -77,11 +77,10 @@ class SOFORT public function paymentResponse($request) { - $this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all()); $this->stripe->payment_hash->save(); - if (in_array($request->redirect_status, ['succeeded','pending'])) { + if (in_array($request->redirect_status, ['succeeded','pending'])) { return $this->processSuccessfulPayment($request->payment_intent); } diff --git a/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php b/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php index 7df5b27a3042..c52a43ea63bf 100644 --- a/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php +++ b/app/PaymentDrivers/Stripe/UpdatePaymentMethods.php @@ -37,31 +37,37 @@ class UpdatePaymentMethods { $this->stripe->client = $client; - $card_methods = PaymentMethod::all([ + $card_methods = PaymentMethod::all( + [ 'customer' => $customer->id, 'type' => 'card', ], - $this->stripe->stripe_connect_auth); + $this->stripe->stripe_connect_auth + ); foreach ($card_methods as $method) { $this->addOrUpdateCard($method, $customer->id, $client, GatewayType::CREDIT_CARD); } - $alipay_methods = PaymentMethod::all([ + $alipay_methods = PaymentMethod::all( + [ 'customer' => $customer->id, 'type' => 'alipay', ], - $this->stripe->stripe_connect_auth); + $this->stripe->stripe_connect_auth + ); foreach ($alipay_methods as $method) { $this->addOrUpdateCard($method, $customer->id, $client, GatewayType::ALIPAY); } - $sofort_methods = PaymentMethod::all([ + $sofort_methods = PaymentMethod::all( + [ 'customer' => $customer->id, 'type' => 'sofort', ], - $this->stripe->stripe_connect_auth); + $this->stripe->stripe_connect_auth + ); foreach ($sofort_methods as $method) { $this->addOrUpdateCard($method, $customer->id, $client, GatewayType::SOFORT); @@ -74,8 +80,9 @@ class UpdatePaymentMethods { $sources = $customer->sources; - if(!$customer || is_null($sources) || !property_exists($sources, 'data')) + if (!$customer || is_null($sources) || !property_exists($sources, 'data')) { return; + } foreach ($sources->data as $method) { $token_exists = ClientGatewayToken::where([ diff --git a/app/PaymentDrivers/Stripe/iDeal.php b/app/PaymentDrivers/Stripe/iDeal.php index bb36c3b2fb71..dd32756e0be8 100644 --- a/app/PaymentDrivers/Stripe/iDeal.php +++ b/app/PaymentDrivers/Stripe/iDeal.php @@ -56,7 +56,7 @@ class iDeal 'payment_hash' => $this->stripe->payment_hash->hash, 'gateway_type_id' => GatewayType::IDEAL, ], - ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + ], array_merge($this->stripe->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); $data['pi_client_secret'] = $intent->client_secret; @@ -80,7 +80,7 @@ class iDeal $this->stripe->payment_hash->data = array_merge((array) $this->stripe->payment_hash->data, $request->all()); $this->stripe->payment_hash->save(); - if (in_array($request->redirect_status, ['succeeded','pending'])) { + if (in_array($request->redirect_status, ['succeeded','pending'])) { return $this->processSuccessfulPayment($request->payment_intent); } diff --git a/app/PaymentDrivers/StripeConnectPaymentDriver.php b/app/PaymentDrivers/StripeConnectPaymentDriver.php index 3d33fcf962fa..f6a4b30211c3 100644 --- a/app/PaymentDrivers/StripeConnectPaymentDriver.php +++ b/app/PaymentDrivers/StripeConnectPaymentDriver.php @@ -12,34 +12,8 @@ namespace App\PaymentDrivers; -use App\Factory\PaymentFactory; -use App\Http\Requests\Payments\PaymentWebhookRequest; -use App\Http\Requests\Request; -use App\Jobs\Util\SystemLogger; use App\Models\Client; -use App\Models\ClientGatewayToken; use App\Models\CompanyGateway; -use App\Models\GatewayType; -use App\Models\Payment; -use App\Models\PaymentHash; -use App\Models\SystemLog; -use App\PaymentDrivers\Stripe\ACH; -use App\PaymentDrivers\Stripe\Alipay; -use App\PaymentDrivers\Stripe\Charge; -use App\PaymentDrivers\Stripe\CreditCard; -use App\PaymentDrivers\Stripe\SEPA; -use App\PaymentDrivers\Stripe\SOFORT; -use App\PaymentDrivers\Stripe\Utilities; -use App\Utils\Traits\MakesHash; -use Exception; -use Illuminate\Support\Carbon; -use Stripe\Customer; -use Stripe\Exception\ApiErrorException; -use Stripe\PaymentIntent; -use Stripe\PaymentMethod; -use Stripe\SetupIntent; -use Stripe\Stripe; -use Stripe\StripeClient; class StripeConnectPaymentDriver extends StripePaymentDriver { diff --git a/app/PaymentDrivers/StripePaymentDriver.php b/app/PaymentDrivers/StripePaymentDriver.php index 71530b9c989b..2e0a352d53f4 100644 --- a/app/PaymentDrivers/StripePaymentDriver.php +++ b/app/PaymentDrivers/StripePaymentDriver.php @@ -14,23 +14,19 @@ namespace App\PaymentDrivers; use App\Exceptions\PaymentFailed; use App\Exceptions\StripeConnectFailure; -use App\Factory\PaymentFactory; use App\Http\Requests\Payments\PaymentWebhookRequest; use App\Http\Requests\Request; use App\Jobs\Util\SystemLogger; use App\Models\ClientGatewayToken; -use App\Models\Country; use App\Models\GatewayType; use App\Models\Payment; use App\Models\PaymentHash; -use App\Models\PaymentType; use App\Models\SystemLog; use App\PaymentDrivers\Stripe\ACH; use App\PaymentDrivers\Stripe\ACSS; use App\PaymentDrivers\Stripe\Alipay; -use App\PaymentDrivers\Stripe\ApplePay; -use App\PaymentDrivers\Stripe\BECS; use App\PaymentDrivers\Stripe\Bancontact; +use App\PaymentDrivers\Stripe\BECS; use App\PaymentDrivers\Stripe\BrowserPay; use App\PaymentDrivers\Stripe\Charge; use App\PaymentDrivers\Stripe\Connect\Verify; @@ -38,6 +34,7 @@ use App\PaymentDrivers\Stripe\CreditCard; use App\PaymentDrivers\Stripe\EPS; use App\PaymentDrivers\Stripe\FPX; use App\PaymentDrivers\Stripe\GIROPAY; +use App\PaymentDrivers\Stripe\iDeal; use App\PaymentDrivers\Stripe\ImportCustomers; use App\PaymentDrivers\Stripe\Jobs\PaymentIntentFailureWebhook; use App\PaymentDrivers\Stripe\Jobs\PaymentIntentProcessingWebhook; @@ -48,12 +45,9 @@ use App\PaymentDrivers\Stripe\SEPA; use App\PaymentDrivers\Stripe\SOFORT; use App\PaymentDrivers\Stripe\UpdatePaymentMethods; use App\PaymentDrivers\Stripe\Utilities; -use App\PaymentDrivers\Stripe\iDeal; use App\Utils\Traits\MakesHash; use Exception; -use Google\Service\ServiceConsumerManagement\CustomError; use Illuminate\Http\RedirectResponse; -use Illuminate\Support\Carbon; use Laracasts\Presenter\Exceptions\PresenterException; use Stripe\Account; use Stripe\Customer; @@ -120,14 +114,12 @@ class StripePaymentDriver extends BaseDriver throw new StripeConnectFailure('Stripe Connect has not been configured'); } } else { - $this->stripe = new StripeClient( $this->company_gateway->getConfigField('apiKey') ); Stripe::setApiKey($this->company_gateway->getConfigField('apiKey')); Stripe::setApiVersion('2022-11-15'); - } return $this; @@ -161,7 +153,7 @@ class StripePaymentDriver extends BaseDriver if ($this->client && isset($this->client->country) && in_array($this->client->country->iso_3166_3, ['USA']) - ) { + ) { $types[] = GatewayType::BANK_TRANSFER; } @@ -355,30 +347,22 @@ class StripePaymentDriver extends BaseDriver } if ($this->company_gateway->require_custom_value1) { - $fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value2) { - $fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value3) { - $fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value4) { - $fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required']; - } @@ -436,7 +420,7 @@ class StripePaymentDriver extends BaseDriver $meta = $this->stripe_connect_auth; - return PaymentIntent::create($data, array_merge($meta, ['idempotency_key' => uniqid("st",true)])); + return PaymentIntent::create($data, array_merge($meta, ['idempotency_key' => uniqid("st", true)])); } /** @@ -453,7 +437,7 @@ class StripePaymentDriver extends BaseDriver $params = ['usage' => 'off_session']; $meta = $this->stripe_connect_auth; - return SetupIntent::create($params, array_merge($meta, ['idempotency_key' => uniqid("st",true)])); + return SetupIntent::create($params, array_merge($meta, ['idempotency_key' => uniqid("st", true)])); } /** @@ -530,7 +514,7 @@ class StripePaymentDriver extends BaseDriver $data['address']['state'] = $this->client->state; $data['address']['country'] = $this->client->country ? $this->client->country->iso_3166_2 : ''; - $customer = Customer::create($data, array_merge($this->stripe_connect_auth, ['idempotency_key' => uniqid("st",true)])); + $customer = Customer::create($data, array_merge($this->stripe_connect_auth, ['idempotency_key' => uniqid("st", true)])); if (! $customer) { throw new Exception('Unable to create gateway customer'); @@ -565,9 +549,7 @@ class StripePaymentDriver extends BaseDriver public function updateCustomer() { - if($this->client) - { - + if ($this->client) { $customer = $this->findOrCreateCustomer(); //Else create a new record $data['name'] = $this->client->present()->name(); @@ -589,7 +571,6 @@ class StripePaymentDriver extends BaseDriver $data['shipping']['address']['country'] = $this->client->shipping_country ? $this->client->shipping_country->iso_3166_2 : ''; \Stripe\Customer::update($customer->id, $data, $this->stripe_connect_auth); - } } @@ -659,12 +640,12 @@ class StripePaymentDriver extends BaseDriver // if($request->type === 'payment_intent.requires_action') // nlog($request->all()); - if($request->type === 'customer.source.updated') { + if ($request->type === 'customer.source.updated') { $ach = new ACH($this); $ach->updateBankAccount($request->all()); } - if($request->type === 'payment_intent.processing') { + if ($request->type === 'payment_intent.processing') { PaymentIntentProcessingWebhook::dispatch($request->data, $request->company_key, $this->company_gateway->id)->delay(now()->addSeconds(2)); return response()->json([], 200); } @@ -719,17 +700,14 @@ class StripePaymentDriver extends BaseDriver ], $this->stripe_connect_auth); if ($charge->captured) { - $payment = false; - if(isset($transaction['payment_intent'])) - { + if (isset($transaction['payment_intent'])) { $payment = Payment::query() ->where('transaction_reference', $transaction['payment_intent']) ->where('company_id', $request->getCompany()->id) ->first(); - } - elseif(isset($transaction['id'])) { + } elseif (isset($transaction['id'])) { $payment = Payment::query() ->where('transaction_reference', $transaction['id']) ->where('company_id', $request->getCompany()->id) @@ -770,14 +748,17 @@ class StripePaymentDriver extends BaseDriver } catch (ApiErrorException | Exception $e) { nlog($e->getMessage()); - SystemLogger::dispatch([ + SystemLogger::dispatch( + [ 'server_response' => $e->getMessage(), 'data' => request()->all(), ], - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_FAILURE, - SystemLog::TYPE_STRIPE, - $this->client, $this->client->company); + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_FAILURE, + SystemLog::TYPE_STRIPE, + $this->client, + $this->client->company + ); } } @@ -798,14 +779,17 @@ class StripePaymentDriver extends BaseDriver } catch (ApiErrorException | Exception $e) { nlog($e->getMessage()); - SystemLogger::dispatch([ + SystemLogger::dispatch( + [ 'server_response' => $e->getMessage(), 'data' => request()->all(), ], - SystemLog::CATEGORY_GATEWAY_RESPONSE, - SystemLog::EVENT_GATEWAY_FAILURE, - SystemLog::TYPE_STRIPE, - $this->client, $this->client->company); + SystemLog::CATEGORY_GATEWAY_RESPONSE, + SystemLog::EVENT_GATEWAY_FAILURE, + SystemLog::TYPE_STRIPE, + $this->client, + $this->client->company + ); } } diff --git a/app/PaymentDrivers/WePay/ACH.php b/app/PaymentDrivers/WePay/ACH.php index 8b5e91131324..7143bda330a0 100644 --- a/app/PaymentDrivers/WePay/ACH.php +++ b/app/PaymentDrivers/WePay/ACH.php @@ -19,11 +19,9 @@ use App\Models\GatewayType; use App\Models\Payment; use App\Models\SystemLog; use App\Notifications\Ninja\WePayFailureNotification; -use App\PaymentDrivers\WePay\WePayCommon; use App\PaymentDrivers\WePayPaymentDriver; use App\Utils\Traits\MakesHash; use Illuminate\Http\Request; -use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Support\Str; class ACH diff --git a/app/PaymentDrivers/WePay/CreditCard.php b/app/PaymentDrivers/WePay/CreditCard.php index f7b5f6ecd7bc..6d1c00a6b969 100644 --- a/app/PaymentDrivers/WePay/CreditCard.php +++ b/app/PaymentDrivers/WePay/CreditCard.php @@ -17,9 +17,7 @@ use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; use App\Jobs\Util\SystemLogger; use App\Models\GatewayType; use App\Models\Payment; -use App\Models\PaymentType; use App\Models\SystemLog; -use App\PaymentDrivers\WePay\WePayCommon; use App\PaymentDrivers\WePayPaymentDriver; use Illuminate\Support\Str; diff --git a/app/PaymentDrivers/WePay/Setup.php b/app/PaymentDrivers/WePay/Setup.php index 66ca2b29c99a..e8af7f5e9d7d 100644 --- a/app/PaymentDrivers/WePay/Setup.php +++ b/app/PaymentDrivers/WePay/Setup.php @@ -12,7 +12,6 @@ namespace App\PaymentDrivers\WePay; use App\PaymentDrivers\WePayPaymentDriver; -use Illuminate\Http\Request; class Setup { diff --git a/app/PaymentDrivers/WePayPaymentDriver.php b/app/PaymentDrivers/WePayPaymentDriver.php index 862329adeea9..fde608b67937 100644 --- a/app/PaymentDrivers/WePayPaymentDriver.php +++ b/app/PaymentDrivers/WePayPaymentDriver.php @@ -345,29 +345,21 @@ class WePayPaymentDriver extends BaseDriver if ($this->company_gateway->require_custom_value1) { - $fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value2) { - $fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value3) { - $fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required']; - } if ($this->company_gateway->require_custom_value4) { - $fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required']; - } diff --git a/app/Policies/EntityPolicy.php b/app/Policies/EntityPolicy.php index 621f8668380a..f5c6f33fc5ea 100644 --- a/app/Policies/EntityPolicy.php +++ b/app/Policies/EntityPolicy.php @@ -32,7 +32,7 @@ class EntityPolicy public function before($user, $ability) { //if($user->isAdmin()) - // return true; + // return true; } /** diff --git a/app/Policies/WebhookPolicy.php b/app/Policies/WebhookPolicy.php index 36344a1c0bd5..2bdb0713b2b6 100644 --- a/app/Policies/WebhookPolicy.php +++ b/app/Policies/WebhookPolicy.php @@ -28,5 +28,4 @@ class WebhookPolicy extends EntityPolicy { return $user->isAdmin(); } - } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index a0c93ab683fb..92e3bbee8124 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -40,7 +40,6 @@ class AppServiceProvider extends ServiceProvider */ public function boot() { - // DB::listen(function($query) { // nlog( // $query->sql, @@ -94,18 +93,15 @@ class AppServiceProvider extends ServiceProvider }); Mailer::macro('postmark_config', function (string $postmark_key) { - Mailer::setSymfonyTransport(app('mail.manager')->createSymfonyTransport([ 'transport' => 'postmark', 'token' => $postmark_key ])); return $this; - }); Mailer::macro('mailgun_config', function ($secret, $domain) { - Mailer::setSymfonyTransport(app('mail.manager')->createSymfonyTransport([ 'transport' => 'mailgun', 'secret' => $secret, @@ -124,7 +120,5 @@ class AppServiceProvider extends ServiceProvider ParallelTesting::setUpTestDatabase(function ($database, $token) { Artisan::call('db:seed'); }); - } - } diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index 11671d396697..1b7d2ba1a4d4 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -65,7 +65,6 @@ use App\Events\PurchaseOrder\PurchaseOrderWasArchived; use App\Events\PurchaseOrder\PurchaseOrderWasCreated; use App\Events\PurchaseOrder\PurchaseOrderWasDeleted; use App\Events\PurchaseOrder\PurchaseOrderWasEmailed; -use App\Events\PurchaseOrder\PurchaseOrderWasMarkedSent; use App\Events\PurchaseOrder\PurchaseOrderWasRestored; use App\Events\PurchaseOrder\PurchaseOrderWasUpdated; use App\Events\PurchaseOrder\PurchaseOrderWasViewed; @@ -163,8 +162,8 @@ use App\Listeners\Invoice\InvoiceCancelledActivity; use App\Listeners\Invoice\InvoiceCreatedNotification; use App\Listeners\Invoice\InvoiceDeletedActivity; use App\Listeners\Invoice\InvoiceEmailActivity; -use App\Listeners\Invoice\InvoiceEmailFailedActivity; use App\Listeners\Invoice\InvoiceEmailedNotification; +use App\Listeners\Invoice\InvoiceEmailFailedActivity; use App\Listeners\Invoice\InvoiceFailedEmailNotification; use App\Listeners\Invoice\InvoicePaidActivity; use App\Listeners\Invoice\InvoiceReminderEmailActivity; @@ -174,8 +173,8 @@ use App\Listeners\Invoice\InvoiceViewedActivity; use App\Listeners\Invoice\UpdateInvoiceActivity; use App\Listeners\Mail\MailSentListener; use App\Listeners\Misc\InvitationViewedListener; -use App\Listeners\Payment\PaymentEmailFailureActivity; use App\Listeners\Payment\PaymentEmailedActivity; +use App\Listeners\Payment\PaymentEmailFailureActivity; use App\Listeners\Payment\PaymentNotification; use App\Listeners\Payment\PaymentRestoredActivity; use App\Listeners\PurchaseOrder\CreatePurchaseOrderActivity; @@ -188,7 +187,6 @@ use App\Listeners\PurchaseOrder\PurchaseOrderEmailActivity; use App\Listeners\PurchaseOrder\PurchaseOrderEmailedNotification; use App\Listeners\PurchaseOrder\PurchaseOrderRestoredActivity; use App\Listeners\PurchaseOrder\PurchaseOrderViewedActivity; -use App\Listeners\PurchaseOrder\PurchaseOrderViewedNotification; use App\Listeners\PurchaseOrder\UpdatePurchaseOrderActivity; use App\Listeners\Quote\QuoteApprovedActivity; use App\Listeners\Quote\QuoteApprovedNotification; @@ -221,8 +219,8 @@ use App\Listeners\User\ArchivedUserActivity; use App\Listeners\User\CreatedUserActivity; use App\Listeners\User\DeletedUserActivity; use App\Listeners\User\RestoredUserActivity; -use App\Listeners\User\UpdateUserLastLogin; use App\Listeners\User\UpdatedUserActivity; +use App\Listeners\User\UpdateUserLastLogin; use App\Models\Account; use App\Models\Client; use App\Models\ClientContact; diff --git a/app/Providers/MailCssInlinerServiceProvider.php b/app/Providers/MailCssInlinerServiceProvider.php index de53679d80fb..c1c5984c1c93 100644 --- a/app/Providers/MailCssInlinerServiceProvider.php +++ b/app/Providers/MailCssInlinerServiceProvider.php @@ -12,8 +12,6 @@ namespace App\Providers; use App\Utils\CssInlinerPlugin; -use Illuminate\Container\Container; -use Illuminate\Mail\MailManager; use Illuminate\Support\ServiceProvider; class MailCssInlinerServiceProvider extends ServiceProvider diff --git a/app/Providers/NinjaTranslationServiceProvider.php b/app/Providers/NinjaTranslationServiceProvider.php index 0c7676f263bb..a9d83915d5f6 100644 --- a/app/Providers/NinjaTranslationServiceProvider.php +++ b/app/Providers/NinjaTranslationServiceProvider.php @@ -18,7 +18,6 @@ class NinjaTranslationServiceProvider extends TranslationServiceProvider { public function boot() { - /* * To reset the translator instance we call * diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index 5fdacb276c3d..e476a7943ecb 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -31,7 +31,6 @@ class RouteServiceProvider extends ServiceProvider parent::boot(); Route::bind('task_scheduler', function ($value) { - if (is_numeric($value)) { throw new ModelNotFoundException("Record with value {$value} not found"); } @@ -40,10 +39,7 @@ class RouteServiceProvider extends ServiceProvider ->withTrashed() ->company() ->where('id', $this->decodePrimaryKey($value))->firstOrFail(); - }); - - } /** diff --git a/app/Repositories/ActivityRepository.php b/app/Repositories/ActivityRepository.php index b90c6751835f..91ede279b5fd 100644 --- a/app/Repositories/ActivityRepository.php +++ b/app/Repositories/ActivityRepository.php @@ -60,7 +60,7 @@ class ActivityRepository extends BaseRepository $activity->save(); //rate limiter - $this->createBackup($entity, $activity); + $this->createBackup($entity, $activity); } /** diff --git a/app/Repositories/BankIntegrationRepository.php b/app/Repositories/BankIntegrationRepository.php index 8eabfd05176b..d4d8d543ce12 100644 --- a/app/Repositories/BankIntegrationRepository.php +++ b/app/Repositories/BankIntegrationRepository.php @@ -12,23 +12,18 @@ namespace App\Repositories; use App\Models\BankIntegration; -use App\Models\Task; -use App\Models\TaskStatus; /** * Class for bank integration repository. */ class BankIntegrationRepository extends BaseRepository { - public function save($data, BankIntegration $bank_integration) { - //stub to store $bank_integration->fill($data); $bank_integration->save(); return $bank_integration->fresh(); } - } diff --git a/app/Repositories/BankTransactionRepository.php b/app/Repositories/BankTransactionRepository.php index 35e2ea73e1f6..2f2cd569dc22 100644 --- a/app/Repositories/BankTransactionRepository.php +++ b/app/Repositories/BankTransactionRepository.php @@ -13,20 +13,17 @@ namespace App\Repositories; use App\Jobs\Bank\MatchBankTransactions; use App\Models\BankTransaction; -use App\Models\Task; -use App\Models\TaskStatus; /** * Class for bank transaction repository. */ class BankTransactionRepository extends BaseRepository { - public function save($data, BankTransaction $bank_transaction) { - - if(array_key_exists('bank_integration_id', $data)) + if (array_key_exists('bank_integration_id', $data)) { $bank_transaction->bank_integration_id = $data['bank_integration_id']; + } $bank_transaction->fill($data); $bank_transaction->save(); @@ -38,16 +35,10 @@ class BankTransactionRepository extends BaseRepository public function convert_matched($bank_transactions) { - - $data['transactions'] = $bank_transactions->map(function ($bt){ + $data['transactions'] = $bank_transactions->map(function ($bt) { return ['id' => $bt->id, 'invoice_ids' => $bt->invoice_ids, 'ninja_category_id' => $bt->ninja_category_id]; - })->toArray(); $bts = (new MatchBankTransactions(auth()->user()->company()->id, auth()->user()->company()->db, $data))->handle(); - - } - - } diff --git a/app/Repositories/BankTransactionRuleRepository.php b/app/Repositories/BankTransactionRuleRepository.php index 87c2c3170578..4d8d1515e2f8 100644 --- a/app/Repositories/BankTransactionRuleRepository.php +++ b/app/Repositories/BankTransactionRuleRepository.php @@ -12,24 +12,18 @@ namespace App\Repositories; use App\Models\BankTransactionRule; -use App\Models\Task; -use App\Models\TaskStatus; /** * Class for bank transaction rule repository. */ class BankTransactionRuleRepository extends BaseRepository { - public function save($data, BankTransactionRule $bank_transaction_rule) { - $bank_transaction_rule->fill($data); $bank_transaction_rule->save(); return $bank_transaction_rule; - } - } diff --git a/app/Repositories/BaseRepository.php b/app/Repositories/BaseRepository.php index 713559736639..3678a789829a 100644 --- a/app/Repositories/BaseRepository.php +++ b/app/Repositories/BaseRepository.php @@ -12,33 +12,24 @@ namespace App\Repositories; use App\Jobs\Product\UpdateOrCreateProduct; -use App\Jobs\Util\WebhookHandler; use App\Models\Client; use App\Models\ClientContact; use App\Models\Company; use App\Models\Credit; -use App\Models\Expense; use App\Models\Invoice; -use App\Models\Payment; -use App\Models\Project; use App\Models\Quote; use App\Models\RecurringInvoice; -use App\Models\Task; -use App\Models\Vendor; -use App\Models\Webhook; use App\Utils\Helpers; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; -use Google\Service\Vision\Property; -use ReflectionClass; class BaseRepository { use MakesHash; use SavesDocuments; - public bool $import_mode = false; + public bool $import_mode = false; private bool $new_model = false; /** @@ -68,7 +59,6 @@ class BaseRepository if (class_exists($className)) { event(new $className($entity, $entity->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); } - } /** @@ -95,7 +85,6 @@ class BaseRepository if (class_exists($className)) { event(new $className($entity, $fromDeleted, $entity->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); } - } /** @@ -122,8 +111,9 @@ class BaseRepository /* Returns an invoice if defined as a key in the $resource array*/ public function getInvitation($invitation, $resource) { - if (is_array($invitation) && ! array_key_exists('key', $invitation)) + if (is_array($invitation) && ! array_key_exists('key', $invitation)) { return false; + } $invitation_class = sprintf('App\\Models\\%sInvitation', $resource); @@ -158,8 +148,9 @@ class BaseRepository protected function alternativeSave($data, $model) { //$start = microtime(true); //forces the client_id if it doesn't exist - if(array_key_exists('client_id', $data)) + if (array_key_exists('client_id', $data)) { $model->client_id = $data['client_id']; + } $client = Client::with('group_settings')->where('id', $model->client_id)->withTrashed()->firstOrFail(); @@ -180,11 +171,13 @@ class BaseRepository $tmp_data = $data; //preserves the $data array /* We need to unset some variable as we sometimes unguard the model */ - if (isset($tmp_data['invitations'])) + if (isset($tmp_data['invitations'])) { unset($tmp_data['invitations']); + } - if (isset($tmp_data['client_contacts'])) + if (isset($tmp_data['client_contacts'])) { unset($tmp_data['client_contacts']); + } $model->fill($tmp_data); @@ -193,17 +186,14 @@ class BaseRepository $model->custom_surcharge_tax3 = $client->company->custom_surcharge_taxes3; $model->custom_surcharge_tax4 = $client->company->custom_surcharge_taxes4; - if(!$model->id){ + if (!$model->id) { $this->new_model = true; - if(is_array($model->line_items) && !($model instanceof RecurringInvoice)) - { - $model->line_items = (collect($model->line_items))->map(function ($item) use($model,$client) { - + if (is_array($model->line_items) && !($model instanceof RecurringInvoice)) { + $model->line_items = (collect($model->line_items))->map(function ($item) use ($model, $client) { $item->notes = Helpers::processReservedKeywords($item->notes, $client); return $item; - }); } } @@ -212,15 +202,18 @@ class BaseRepository /* Model now persisted, now lets do some child tasks */ - if($model instanceof Invoice) + if ($model instanceof Invoice) { $model->service()->setReminder()->save(); + } /* Save any documents */ - if (array_key_exists('documents', $data)) + if (array_key_exists('documents', $data)) { $this->saveDocuments($data['documents'], $model); + } - if (array_key_exists('file', $data)) + if (array_key_exists('file', $data)) { $this->saveDocuments($data['file'], $model); + } /* If invitations are present we need to filter existing invitations with the new ones */ if (isset($data['invitations'])) { @@ -231,25 +224,22 @@ class BaseRepository $invitation_class = sprintf('App\\Models\\%sInvitation', $resource); $invitation = $invitation_class::where('key', $invitation)->first(); - if ($invitation){ + if ($invitation) { $invitation->delete(); } - }); foreach ($data['invitations'] as $invitation) { - //if no invitations are present - create one. if (! $this->getInvitation($invitation, $resource)) { - - if (isset($invitation['id'])) + if (isset($invitation['id'])) { unset($invitation['id']); + } //make sure we are creating an invite for a contact who belongs to the client only! $contact = ClientContact::find($invitation['client_contact_id']); if ($contact && $model->client_id == $contact->client_id) { - $invitation_class = sprintf('App\\Models\\%sInvitation', $resource); $new_invitation = $invitation_class::withTrashed() @@ -259,16 +249,13 @@ class BaseRepository if ($new_invitation && $new_invitation->trashed()) { $new_invitation->restore(); - } else { - $invitation_factory_class = sprintf('App\\Factory\\%sInvitationFactory', $resource); $new_invitation = $invitation_factory_class::create($model->company_id, $model->user_id); $new_invitation->{$lcfirst_resource_id} = $model->id; $new_invitation->client_contact_id = $contact->id; $new_invitation->key = $this->createDbHash($model->company->db); $new_invitation->saveQuietly(); - } } } @@ -276,8 +263,9 @@ class BaseRepository } /* If no invitations have been created, this is our fail safe to maintain state*/ - if ($model->invitations()->count() == 0) + if ($model->invitations()->count() == 0) { $model->service()->createInvitations(); + } /* Recalculate invoice amounts */ $model = $model->calc()->getInvoice(); @@ -289,85 +277,88 @@ class BaseRepository $model = $model->service()->applyNumber()->save(); /* Handle attempts where the deposit is greater than the amount/balance of the invoice */ - if((int)$model->balance != 0 && $model->partial > $model->amount && $model->amount > 0) + if ((int)$model->balance != 0 && $model->partial > $model->amount && $model->amount > 0) { $model->partial = min($model->amount, $model->balance); + } /* Update product details if necessary - if we are inside a transaction - do nothing */ - if ($model->company->update_products && $model->id && \DB::transactionLevel() == 0) + if ($model->company->update_products && $model->id && \DB::transactionLevel() == 0) { UpdateOrCreateProduct::dispatch($model->line_items, $model, $model->company); + } /* Perform model specific tasks */ if ($model instanceof Invoice) { - if (($state['finished_amount'] != $state['starting_amount']) && ($model->status_id != Invoice::STATUS_DRAFT)) { - $model->service()->updateStatus()->save(); $model->client->service()->updateBalance(($state['finished_amount'] - $state['starting_amount']))->save(); $model->ledger()->updateInvoiceBalance(($state['finished_amount'] - $state['starting_amount']), "Update adjustment for invoice {$model->number}"); - } - if (! $model->design_id) + if (! $model->design_id) { $model->design_id = $this->decodePrimaryKey($client->getSetting('invoice_design_id')); + } //links tasks and expenses back to the invoice, but only if we are not in the middle of a transaction. - if (\DB::transactionLevel() == 0) + if (\DB::transactionLevel() == 0) { $model->service()->linkEntities()->save(); + } - if($this->new_model) + if ($this->new_model) { event('eloquent.created: App\Models\Invoice', $model); - else + } else { event('eloquent.updated: App\Models\Invoice', $model); - + } } if ($model instanceof Credit) { - $model = $model->calc()->getCredit(); - if (! $model->design_id) + if (! $model->design_id) { $model->design_id = $this->decodePrimaryKey($client->getSetting('credit_design_id')); - - if(array_key_exists('invoice_id', $data) && $data['invoice_id']) - $model->invoice_id = $data['invoice_id']; - - if($this->new_model) - event('eloquent.created: App\Models\Credit', $model); - else - event('eloquent.updated: App\Models\Credit', $model); - - if (($state['finished_amount'] != $state['starting_amount']) && ($model->status_id != Credit::STATUS_DRAFT)) { - - $model->client->service()->adjustCreditBalance(($state['finished_amount'] - $state['starting_amount']))->save(); } + if (array_key_exists('invoice_id', $data) && $data['invoice_id']) { + $model->invoice_id = $data['invoice_id']; + } + + if ($this->new_model) { + event('eloquent.created: App\Models\Credit', $model); + } else { + event('eloquent.updated: App\Models\Credit', $model); + } + + if (($state['finished_amount'] != $state['starting_amount']) && ($model->status_id != Credit::STATUS_DRAFT)) { + $model->client->service()->adjustCreditBalance(($state['finished_amount'] - $state['starting_amount']))->save(); + } } if ($model instanceof Quote) { - - if (! $model->design_id) + if (! $model->design_id) { $model->design_id = $this->decodePrimaryKey($client->getSetting('quote_design_id')); + } $model = $model->calc()->getQuote(); - if($this->new_model) + if ($this->new_model) { event('eloquent.created: App\Models\Quote', $model); - else + } else { event('eloquent.updated: App\Models\Quote', $model); + } } if ($model instanceof RecurringInvoice) { - - if (! $model->design_id) + if (! $model->design_id) { $model->design_id = $this->decodePrimaryKey($client->getSetting('invoice_design_id')); + } $model = $model->calc()->getRecurringInvoice(); - if($this->new_model) + if ($this->new_model) { event('eloquent.created: App\Models\RecurringInvoice', $model); - else + } else { event('eloquent.updated: App\Models\RecurringInvoice', $model); + } } $model->saveQuietly(); diff --git a/app/Repositories/ClientContactRepository.php b/app/Repositories/ClientContactRepository.php index 5356175e792a..ed1b81be267c 100644 --- a/app/Repositories/ClientContactRepository.php +++ b/app/Repositories/ClientContactRepository.php @@ -30,19 +30,12 @@ class ClientContactRepository extends BaseRepository { //06-09-2022 sometimes users pass a contact object instead of a nested array, this sequence handles this scenario if (isset($data['contacts']) && (count($data['contacts']) !== count($data['contacts'], COUNT_RECURSIVE))) { - $contacts = collect($data['contacts']); - - } elseif(isset($data['contacts'])){ - + } elseif (isset($data['contacts'])) { $temp_array[] = $data['contacts']; $contacts = collect($temp_array); - - } - else { - + } else { $contacts = collect(); - } $client->contacts->pluck('id')->diff($contacts->pluck('id'))->each(function ($contact) { @@ -56,7 +49,6 @@ class ClientContactRepository extends BaseRepository /* Set first record to primary - always */ $contacts = $contacts->sortByDesc('is_primary')->map(function ($contact) { - $contact['is_primary'] = $this->is_primary; $this->is_primary = false; diff --git a/app/Repositories/ClientRepository.php b/app/Repositories/ClientRepository.php index d776977c48e3..851dd83e7d06 100644 --- a/app/Repositories/ClientRepository.php +++ b/app/Repositories/ClientRepository.php @@ -14,7 +14,6 @@ namespace App\Repositories; use App\Factory\ClientFactory; use App\Models\Client; use App\Models\Company; -use App\Utils\Traits\ClientGroupSettingsSaver; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\SavesDocuments; use Illuminate\Database\QueryException; @@ -79,7 +78,6 @@ class ClientRepository extends BaseRepository $client->save(); if (! isset($client->number) || empty($client->number) || strlen($client->number) == 0) { - $x = 1; do { @@ -104,8 +102,9 @@ class ClientRepository extends BaseRepository //24-01-2023 when a logo is uploaded, no other data is set, so we need to catch here and not update //the contacts array UNLESS there are no contacts and we need to maintain state. - if(array_key_exists('contacts', $contact_data) || $client->contacts()->count() == 0) + if (array_key_exists('contacts', $contact_data) || $client->contacts()->count() == 0) { $this->contact_repo->save($contact_data, $client); + } return $client; } diff --git a/app/Repositories/CreditRepository.php b/app/Repositories/CreditRepository.php index 572fb85dc470..f5097e8f9adf 100644 --- a/app/Repositories/CreditRepository.php +++ b/app/Repositories/CreditRepository.php @@ -53,7 +53,6 @@ class CreditRepository extends BaseRepository $credit = $credit->service()->deleteCredit()->save(); return parent::delete($credit); - } public function restore($credit) @@ -69,5 +68,4 @@ class CreditRepository extends BaseRepository return $credit; } - } diff --git a/app/Repositories/DocumentRepository.php b/app/Repositories/DocumentRepository.php index 74206fa6f117..2740c847a54c 100644 --- a/app/Repositories/DocumentRepository.php +++ b/app/Repositories/DocumentRepository.php @@ -12,7 +12,6 @@ namespace App\Repositories; use App\Models\Document; -use App\Utils\Ninja; /** * Class for document repository. @@ -27,7 +26,6 @@ class DocumentRepository extends BaseRepository public function restore($document) { - // if (! $document->trashed()) { // return; // } diff --git a/app/Repositories/ExpenseRepository.php b/app/Repositories/ExpenseRepository.php index e83d8c608f58..3d7c2a08285c 100644 --- a/app/Repositories/ExpenseRepository.php +++ b/app/Repositories/ExpenseRepository.php @@ -17,8 +17,8 @@ use App\Libraries\Currency\Conversion\CurrencyApi; use App\Models\Expense; use App\Utils\Traits\GeneratesCounter; use Carbon\Exceptions\InvalidFormatException; -use Illuminate\Support\Carbon; use Illuminate\Database\QueryException; +use Illuminate\Support\Carbon; /** * ExpenseRepository. @@ -35,7 +35,7 @@ class ExpenseRepository extends BaseRepository * @param array $data The data * @param \App\Models\Expense $expense The expense * - * @return \App\Models\Expense + * @return \App\Models\Expense */ public function save(array $data, Expense $expense): Expense { @@ -45,8 +45,9 @@ class ExpenseRepository extends BaseRepository $expense = $this->processExchangeRates($data, $expense); } - if (empty($expense->number)) + if (empty($expense->number)) { $expense = $this->findAndSaveNumber($expense); + } $expense->saveQuietly(); @@ -73,10 +74,10 @@ class ExpenseRepository extends BaseRepository } /** - * @param mixed $data - * @param mixed $expense - * @return Expense - * @throws InvalidFormatException + * @param mixed $data + * @param mixed $expense + * @return Expense + * @throws InvalidFormatException */ public function processExchangeRates($data, $expense): Expense { @@ -106,23 +107,20 @@ class ExpenseRepository extends BaseRepository */ private function findAndSaveNumber($expense): Expense { - $x = 1; do { - try { - $expense->number = $this->getNextExpenseNumber($expense); $expense->saveQuietly(); $this->completed = false; } catch (QueryException $e) { - $x++; - if ($x > 50) + if ($x > 50) { $this->completed = false; + } } } while ($this->completed); diff --git a/app/Repositories/Migration/InvoiceMigrationRepository.php b/app/Repositories/Migration/InvoiceMigrationRepository.php index 5f5d53e05604..40725e62020e 100644 --- a/app/Repositories/Migration/InvoiceMigrationRepository.php +++ b/app/Repositories/Migration/InvoiceMigrationRepository.php @@ -11,7 +11,6 @@ namespace App\Repositories\Migration; -use App\Jobs\Product\UpdateOrCreateProduct; use App\Models\Client; use App\Models\ClientContact; use App\Models\Credit; diff --git a/app/Repositories/Migration/PaymentMigrationRepository.php b/app/Repositories/Migration/PaymentMigrationRepository.php index cd25c7ade5fe..11d40e8f976c 100644 --- a/app/Repositories/Migration/PaymentMigrationRepository.php +++ b/app/Repositories/Migration/PaymentMigrationRepository.php @@ -69,7 +69,6 @@ class PaymentMigrationRepository extends BaseRepository */ private function applyPayment(array $data, Payment $payment): ?Payment { - //check currencies here and fill the exchange rate data if necessary if (! $payment->id) { $this->processExchangeRates($data, $payment); diff --git a/app/Repositories/PaymentRepository.php b/app/Repositories/PaymentRepository.php index 7d06feb822d6..305cdbd28bf3 100644 --- a/app/Repositories/PaymentRepository.php +++ b/app/Repositories/PaymentRepository.php @@ -14,13 +14,11 @@ namespace App\Repositories; use App\Events\Payment\PaymentWasCreated; use App\Events\Payment\PaymentWasDeleted; use App\Jobs\Credit\ApplyCreditPayment; -use App\Jobs\Ninja\TransactionLog; use App\Libraries\Currency\Conversion\CurrencyApi; use App\Models\Client; use App\Models\Credit; use App\Models\Invoice; use App\Models\Payment; -use App\Models\TransactionEvent; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use App\Utils\Traits\SavesDocuments; @@ -30,20 +28,22 @@ use Illuminate\Support\Carbon; /** * PaymentRepository. */ -class PaymentRepository extends BaseRepository { - use MakesHash; - use SavesDocuments; +class PaymentRepository extends BaseRepository +{ + use MakesHash; + use SavesDocuments; - protected $credit_repo; + protected $credit_repo; - public function __construct( CreditRepository $credit_repo ) { - $this->credit_repo = $credit_repo; - } + public function __construct(CreditRepository $credit_repo) + { + $this->credit_repo = $credit_repo; + } - /** - * Saves and updates a payment. //todo refactor to handle refunds and payments. - * - * @param array $data the request object + /** + * Saves and updates a payment. //todo refactor to handle refunds and payments. + * + * @param array $data the request object * @param Payment $payment The Payment object * @return Payment|null Payment $payment */ @@ -60,7 +60,6 @@ class PaymentRepository extends BaseRepository { */ private function applyPayment(array $data, Payment $payment): ?Payment { - $is_existing_payment = true; $client = false; @@ -69,13 +68,13 @@ class PaymentRepository extends BaseRepository { $payment = $this->processExchangeRates($data, $payment); /* This is needed here otherwise the ->fill() overwrites anything that exists*/ - if($payment->exchange_rate != 1) + if ($payment->exchange_rate != 1) { unset($data['exchange_rate']); + } $is_existing_payment = false; \DB::connection(config('database.default'))->transaction(function () use ($data) { - $client = Client::where('id', $data['client_id'])->withTrashed()->lockForUpdate()->first(); /*We only update the paid to date ONCE per payment*/ @@ -86,9 +85,7 @@ class PaymentRepository extends BaseRepository { $client->service()->updatePaidToDate($data['amount'])->save(); $client->saveQuietly(); - } - - else{ + } else { //this fixes an edge case with unapplied payments $client->service()->updatePaidToDate($data['amount'])->save(); // $client->paid_to_date += $data['amount']; @@ -102,9 +99,7 @@ class PaymentRepository extends BaseRepository { // $client->paid_to_date += $_credit_totals; $client->saveQuietly(); } - - }, 1); - + }, 1); } /*Fill the payment*/ @@ -113,12 +108,11 @@ class PaymentRepository extends BaseRepository { $payment->status_id = Payment::STATUS_COMPLETED; if (! $payment->currency_id && $client) { - - if(property_exists($client->settings, 'currency_id')) + if (property_exists($client->settings, 'currency_id')) { $payment->currency_id = $client->settings->currency_id; - else + } else { $payment->currency_id = $client->company->settings->currency_id; - + } } $payment->saveQuietly(); @@ -140,7 +134,6 @@ class PaymentRepository extends BaseRepository { /*Iterate through invoices and apply payments*/ if (array_key_exists('invoices', $data) && is_array($data['invoices']) && count($data['invoices']) > 0) { - $invoice_totals = array_sum(array_column($data['invoices'], 'amount')); $invoices = Invoice::withTrashed()->whereIn('id', array_column($data['invoices'], 'invoice_id'))->get(); @@ -186,15 +179,15 @@ class PaymentRepository extends BaseRepository { } } - if ( ! $is_existing_payment && ! $this->import_mode ) { - - if (array_key_exists('email_receipt', $data) && $data['email_receipt'] == 'true') + if (! $is_existing_payment && ! $this->import_mode) { + if (array_key_exists('email_receipt', $data) && $data['email_receipt'] == 'true') { $payment->service()->sendEmail(); - elseif(!array_key_exists('email_receipt', $data) && $payment->client->getSetting('client_manual_payment_notification')) + } elseif (!array_key_exists('email_receipt', $data) && $payment->client->getSetting('client_manual_payment_notification')) { $payment->service()->sendEmail(); + } - event( new PaymentWasCreated( $payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null) ) ); - } + event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); + } $payment->applied += ($invoice_totals - $credit_totals); //wont work because - check tests @@ -212,8 +205,7 @@ class PaymentRepository extends BaseRepository { */ public function processExchangeRates($data, $payment) { - - if(array_key_exists('exchange_rate', $data) && isset($data['exchange_rate']) && $data['exchange_rate'] != 1){ + if (array_key_exists('exchange_rate', $data) && isset($data['exchange_rate']) && $data['exchange_rate'] != 1) { return $payment; } @@ -223,7 +215,6 @@ class PaymentRepository extends BaseRepository { $company_currency = $client->company->settings->currency_id; if ($company_currency != $client_currency) { - $exchange_rate = new CurrencyApi(); $payment->exchange_rate = $exchange_rate->exchangeRate($client_currency, $company_currency, Carbon::parse($payment->date)); @@ -247,11 +238,11 @@ class PaymentRepository extends BaseRepository { $payment = $payment->service()->deletePayment(); - if($payment) + if ($payment) { event(new PaymentWasDeleted($payment, $payment->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); + } return $payment; - } public function restore($payment) diff --git a/app/Repositories/PurchaseOrderRepository.php b/app/Repositories/PurchaseOrderRepository.php index e1b514b25ca0..321b4fa89891 100644 --- a/app/Repositories/PurchaseOrderRepository.php +++ b/app/Repositories/PurchaseOrderRepository.php @@ -44,7 +44,6 @@ class PurchaseOrderRepository extends BaseRepository }); foreach ($data['invitations'] as $invitation) { - //if no invitations are present - create one. if (! $this->getInvitation($invitation)) { if (isset($invitation['id'])) { diff --git a/app/Repositories/RecurringInvoiceRepository.php b/app/Repositories/RecurringInvoiceRepository.php index f5d19e731390..c0b4e87f121e 100644 --- a/app/Repositories/RecurringInvoiceRepository.php +++ b/app/Repositories/RecurringInvoiceRepository.php @@ -11,7 +11,6 @@ namespace App\Repositories; -use App\Helpers\Invoice\InvoiceSum; use App\Models\RecurringInvoice; use App\Models\RecurringInvoiceInvitation; diff --git a/app/Repositories/SchedulerRepository.php b/app/Repositories/SchedulerRepository.php index f03ca0213481..f067984b1027 100644 --- a/app/Repositories/SchedulerRepository.php +++ b/app/Repositories/SchedulerRepository.php @@ -15,24 +15,20 @@ use App\Models\Scheduler; class SchedulerRepository extends BaseRepository { - /** * Saves the scheduler. * * @param array $data The data * @param \App\Models\Scheduler $scheduler The scheduler * - * @return \App\Models\Scheduler + * @return \App\Models\Scheduler */ public function save(array $data, Scheduler $scheduler): Scheduler { - $scheduler->fill($data); $scheduler->save(); return $scheduler; - } - } diff --git a/app/Repositories/SubscriptionRepository.php b/app/Repositories/SubscriptionRepository.php index 8a8b25972a32..dd647ca5d32f 100644 --- a/app/Repositories/SubscriptionRepository.php +++ b/app/Repositories/SubscriptionRepository.php @@ -17,7 +17,6 @@ use App\DataMapper\InvoiceItem; use App\Factory\InvoiceFactory; use App\Models\Client; use App\Models\ClientContact; -use App\Models\Invoice; use App\Models\InvoiceInvitation; use App\Models\Subscription; use App\Utils\Traits\CleanLineItems; @@ -45,7 +44,6 @@ class SubscriptionRepository extends BaseRepository private function calculatePrice($subscription) :array { - // DB::beginTransaction(); DB::connection(config('database.default'))->beginTransaction(); $data = []; @@ -124,21 +122,16 @@ class SubscriptionRepository extends BaseRepository $line_items = []; - $line_items = collect($bundle)->filter(function ($item){ - + $line_items = collect($bundle)->filter(function ($item) { return $item->is_recurring; - - })->map(function ($item){ - - $line_item = new InvoiceItem; - $line_item->product_key = $item->product_key; - $line_item->quantity = (float)$item->qty; - $line_item->cost = (float)$item->unit_cost; - $line_item->notes = $item->description; - - return $line_item; - + })->map(function ($item) { + $line_item = new InvoiceItem; + $line_item->product_key = $item->product_key; + $line_item->quantity = (float)$item->qty; + $line_item->cost = (float)$item->unit_cost; + $line_item->notes = $item->description; + return $line_item; })->toArray(); diff --git a/app/Repositories/TaskRepository.php b/app/Repositories/TaskRepository.php index 4d5749a73db0..562a7a7c3d36 100644 --- a/app/Repositories/TaskRepository.php +++ b/app/Repositories/TaskRepository.php @@ -251,30 +251,22 @@ class TaskRepository extends BaseRepository private function trySaving(Task $task) { - $x=1; - do{ - - try{ - + do { + try { $task->number = $this->getNextTaskNumber($task); $task->saveQuietly(); $this->completed = false; - - } - catch(QueryException $e){ - + } catch(QueryException $e) { $x++; - if($x>50) + if ($x>50) { $this->completed = false; + } } - - } - while($this->completed); + } while ($this->completed); return $task->number; - } } diff --git a/app/Repositories/TaskStatusRepository.php b/app/Repositories/TaskStatusRepository.php index 88f7bbb83df4..8692ed51fd35 100644 --- a/app/Repositories/TaskStatusRepository.php +++ b/app/Repositories/TaskStatusRepository.php @@ -19,9 +19,8 @@ use App\Models\TaskStatus; */ class TaskStatusRepository extends BaseRepository { - - public function delete($task_status) - { + public function delete($task_status) + { $ts = TaskStatus::where('company_id', $task_status->company_id) ->first(); @@ -35,11 +34,10 @@ class TaskStatusRepository extends BaseRepository parent::delete($task_status); return $task_status; - - } + } - public function archive($task_status) - { + public function archive($task_status) + { $task_status = TaskStatus::where('id', $task_status->id) ->where('company_id', $task_status->company_id) ->first(); @@ -54,6 +52,5 @@ class TaskStatusRepository extends BaseRepository parent::archive($task_status); return $task_status; - - } + } } diff --git a/app/Repositories/UserRepository.php b/app/Repositories/UserRepository.php index cf66bf09a9ee..6b8707d158a9 100644 --- a/app/Repositories/UserRepository.php +++ b/app/Repositories/UserRepository.php @@ -59,7 +59,7 @@ class UserRepository extends BaseRepository // if(array_key_exists('oauth_provider_id', $details)) // unset($details['oauth_provider_id']); - if (request()->has('validated_phone')){ + if (request()->has('validated_phone')) { $details['phone'] = request()->input('validated_phone'); $user->verified_phone_number = false; } @@ -93,17 +93,15 @@ class UserRepository extends BaseRepository $user->companies()->attach($company->id, $data['company_user']); } else { if (auth()->user()->isAdmin()) { - $cu->fill($data['company_user']); $cu->restore(); $cu->tokens()->restore(); $cu->save(); //05-08-2022 - if($cu->tokens()->count() == 0){ + if ($cu->tokens()->count() == 0) { (new CreateCompanyToken($cu->company, $cu->user, 'restored_user'))->handle(); } - } else { $cu->notifications = $data['company_user']['notifications']; $cu->settings = $data['company_user']['settings']; @@ -221,28 +219,23 @@ class UserRepository extends BaseRepository * and there are some that are not admins, * we force all companies to large to ensure * the queries are appropriate for all users - * - * @param User $user + * + * @param User $user * @return void */ private function verifyCorrectCompanySizeForPermissions(User $user): void { - - if(Ninja::isSelfHost() || (Ninja::isHosted() && $user->account->isEnterpriseClient())) - { - + if (Ninja::isSelfHost() || (Ninja::isHosted() && $user->account->isEnterpriseClient())) { $user->account() - ->whereHas('companies', function ($query){ - $query->where('is_large',0); + ->whereHas('companies', function ($query) { + $query->where('is_large', 0); }) - ->whereHas('company_users', function ($query){ - $query->where('is_admin', 0); - }) - ->cursor()->each(function ($account){ - $account->companies()->update(['is_large' => true]); + ->whereHas('company_users', function ($query) { + $query->where('is_admin', 0); + }) + ->cursor()->each(function ($account) { + $account->companies()->update(['is_large' => true]); }); - } - } } diff --git a/app/Services/Bank/BankMatchingService.php b/app/Services/Bank/BankMatchingService.php index 663e7204114a..906e21fe918d 100644 --- a/app/Services/Bank/BankMatchingService.php +++ b/app/Services/Bank/BankMatchingService.php @@ -11,50 +11,37 @@ namespace App\Services\Bank; -use App\Factory\ExpenseCategoryFactory; -use App\Factory\ExpenseFactory; use App\Libraries\MultiDB; use App\Models\BankTransaction; -use App\Models\Company; -use App\Models\ExpenseCategory; -use App\Models\Invoice; -use App\Services\Bank\BankService; -use App\Utils\Traits\GeneratesCounter; use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; -use Illuminate\Support\Carbon; -use Illuminate\Support\Facades\Cache; class BankMatchingService implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - public function __construct(public $company_id, public $db){} + public function __construct(public $company_id, public $db) + { + } public function handle() :void { - MultiDB::setDb($this->db); BankTransaction::where('company_id', $this->company_id) ->where('status_id', BankTransaction::STATUS_UNMATCHED) ->cursor() - ->each(function ($bt){ - + ->each(function ($bt) { (new BankService($bt))->processRules(); - }); - } public function middleware() - { + { return [(new WithoutOverlapping($this->company_id))]; } - } diff --git a/app/Services/Bank/BankService.php b/app/Services/Bank/BankService.php index 94916752a57c..1fc3a77ba946 100644 --- a/app/Services/Bank/BankService.php +++ b/app/Services/Bank/BankService.php @@ -13,20 +13,17 @@ namespace App\Services\Bank; use App\Models\BankTransaction; use App\Models\Invoice; -use App\Services\Bank\ProcessBankRules; class BankService { - - public function __construct(public BankTransaction $bank_transaction) {} + public function __construct(public BankTransaction $bank_transaction) + { + } public function matchInvoiceNumber() { - - if(strlen($this->bank_transaction->description) > 1) - { - + if (strlen($this->bank_transaction->description) > 1) { $i = Invoice::where('company_id', $this->bank_transaction->company_id) ->whereIn('status_id', [1,2,3]) ->where('is_deleted', 0) @@ -37,12 +34,10 @@ class BankService } return false; - } public function processRules() { (new ProcessBankRules($this->bank_transaction))->run(); } - -} \ No newline at end of file +} diff --git a/app/Services/Bank/ProcessBankRules.php b/app/Services/Bank/ProcessBankRules.php index 2077fb244242..54277d5f693d 100644 --- a/app/Services/Bank/ProcessBankRules.php +++ b/app/Services/Bank/ProcessBankRules.php @@ -31,91 +31,76 @@ class ProcessBankRules extends AbstractService protected $categories; - public function __construct(public BankTransaction $bank_transaction){} + public function __construct(public BankTransaction $bank_transaction) + { + } public function run() { - if($this->bank_transaction->base_type == 'DEBIT') + if ($this->bank_transaction->base_type == 'DEBIT') { $this->matchDebit(); - else + } else { $this->matchCredit(); + } } private function matchCredit() { - $this->invoices = Invoice::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){ - + $invoice = $this->invoices->first(function ($value, $key) { return str_contains($this->bank_transaction->description, $value->number); - }); - if($invoice) - { + if ($invoice) { $this->bank_transaction->invoice_ids = $invoice->hashed_id; $this->bank_transaction->status_id = BankTransaction::STATUS_MATCHED; - $this->bank_transaction->save(); + $this->bank_transaction->save(); return; } $this->credit_rules = $this->bank_transaction->company->credit_rules(); //stub for credit rules - foreach($this->credit_rules as $rule) - { + foreach ($this->credit_rules as $rule) { // $this->bank_transaction->bank_transaction_rule_id = $bank_transaction_rule->id; - } - } private function matchDebit() { - $this->debit_rules = $this->bank_transaction->company->debit_rules(); $this->categories = collect(Cache::get('bank_categories')); - foreach($this->debit_rules as $bank_transaction_rule) - { - + foreach ($this->debit_rules as $bank_transaction_rule) { $matches = 0; - if(!is_array($bank_transaction_rule['rules'])) + if (!is_array($bank_transaction_rule['rules'])) { continue; + } - foreach($bank_transaction_rule['rules'] as $rule) - { + foreach ($bank_transaction_rule['rules'] as $rule) { $rule_count = count($bank_transaction_rule['rules']); - if($rule['search_key'] == 'description') - { - - if($this->matchStringOperator($this->bank_transaction->description, $rule['value'], $rule['operator'])){ + if ($rule['search_key'] == 'description') { + if ($this->matchStringOperator($this->bank_transaction->description, $rule['value'], $rule['operator'])) { $matches++; } - } - if($rule['search_key'] == 'amount') - { - - if($this->matchNumberOperator($this->bank_transaction->amount, $rule['value'] , $rule['operator'])){ + if ($rule['search_key'] == 'amount') { + if ($this->matchNumberOperator($this->bank_transaction->amount, $rule['value'], $rule['operator'])) { $matches++; } - } - if(($bank_transaction_rule['matches_on_all'] && ($matches == $rule_count)) || (!$bank_transaction_rule['matches_on_all'] && $matches > 0)) - { - + if (($bank_transaction_rule['matches_on_all'] && ($matches == $rule_count)) || (!$bank_transaction_rule['matches_on_all'] && $matches > 0)) { // $this->bank_transaction->client_id = empty($rule['client_id']) ? null : $rule['client_id']; $this->bank_transaction->vendor_id = $bank_transaction_rule->vendor_id; $this->bank_transaction->ninja_category_id = $bank_transaction_rule->category_id; @@ -123,9 +108,7 @@ class ProcessBankRules extends AbstractService $this->bank_transaction->bank_transaction_rule_id = $bank_transaction_rule->id; $this->bank_transaction->save(); - if($bank_transaction_rule['auto_convert']) - { - + if ($bank_transaction_rule['auto_convert']) { $expense = ExpenseFactory::create($this->bank_transaction->company_id, $this->bank_transaction->user_id); $expense->category_id = $bank_transaction_rule->category_id ?: $this->resolveCategory(); $expense->amount = $this->bank_transaction->amount; @@ -145,14 +128,10 @@ class ProcessBankRules extends AbstractService $this->bank_transaction->save(); break; - } - } } - } - } private function resolveCategory() @@ -161,11 +140,11 @@ class ProcessBankRules extends AbstractService $ec = ExpenseCategory::where('company_id', $this->bank_transaction->company_id)->where('bank_category_id', $this->bank_transaction->category_id)->first(); - if($ec) + if ($ec) { return $ec->id; + } - if($category) - { + if ($category) { $ec = ExpenseCategoryFactory::create($this->bank_transaction->company_id, $this->bank_transaction->user_id); $ec->bank_category_id = $this->bank_transaction->category_id; $ec->name = $category->highLevelCategoryName; @@ -177,7 +156,6 @@ class ProcessBankRules extends AbstractService private function matchNumberOperator($bt_value, $rule_value, $operator) :bool { - return match ($operator) { '>' => floatval($bt_value) > floatval($rule_value), '>=' => floatval($bt_value) >= floatval($rule_value), @@ -186,7 +164,6 @@ class ProcessBankRules extends AbstractService '<=' => floatval($bt_value) <= floatval($rule_value), default => false, }; - } private function matchStringOperator($bt_value, $rule_value, $operator) :bool @@ -202,10 +179,5 @@ class ProcessBankRules extends AbstractService 'is_empty' => empty($bt_value), default => false, }; - } - - - - -} \ No newline at end of file +} diff --git a/app/Services/Chart/ChartQueries.php b/app/Services/Chart/ChartQueries.php index 4cd2fc73c020..fc996b00d32f 100644 --- a/app/Services/Chart/ChartQueries.php +++ b/app/Services/Chart/ChartQueries.php @@ -11,9 +11,6 @@ namespace App\Services\Chart; -use App\Models\Expense; -use App\Models\Invoice; -use App\Models\Payment; use Illuminate\Support\Facades\DB; /** diff --git a/app/Services/Chart/ChartService.php b/app/Services/Chart/ChartService.php index 85d0ef8bf7eb..6c7c9914e82f 100644 --- a/app/Services/Chart/ChartService.php +++ b/app/Services/Chart/ChartService.php @@ -14,8 +14,6 @@ namespace App\Services\Chart; use App\Models\Client; use App\Models\Company; use App\Models\Expense; -use App\Models\Payment; -use App\Services\Chart\ChartQueries; use Illuminate\Support\Facades\Cache; class ChartService diff --git a/app/Services/Client/ClientService.php b/app/Services/Client/ClientService.php index ad74f22c0c84..df0641c2eda8 100644 --- a/app/Services/Client/ClientService.php +++ b/app/Services/Client/ClientService.php @@ -13,8 +13,6 @@ namespace App\Services\Client; use App\Models\Client; use App\Models\Credit; -use App\Services\Client\Merge; -use App\Services\Client\PaymentMethod; use App\Services\Email\EmailObject; use App\Services\Email\EmailService; use App\Utils\Number; @@ -30,76 +28,61 @@ class ClientService private string $client_end_date; - public function __construct(private Client $client){} + public function __construct(private Client $client) + { + } public function updateBalance(float $amount) { - try { - DB::connection(config('database.default'))->transaction(function () use($amount) { - + DB::connection(config('database.default'))->transaction(function () use ($amount) { $this->client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first(); $this->client->balance += $amount; $this->client->saveQuietly(); - }, 2); - } - catch (\Throwable $throwable) { + } catch (\Throwable $throwable) { nlog("DB ERROR " . $throwable->getMessage()); } return $this; - } public function updateBalanceAndPaidToDate(float $balance, float $paid_to_date) { - try { - DB::connection(config('database.default'))->transaction(function () use($balance, $paid_to_date) { - + DB::connection(config('database.default'))->transaction(function () use ($balance, $paid_to_date) { $this->client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first(); $this->client->balance += $balance; $this->client->paid_to_date += $paid_to_date; $this->client->saveQuietly(); - }, 2); - } - catch (\Throwable $throwable) { + } catch (\Throwable $throwable) { nlog("DB ERROR " . $throwable->getMessage()); } return $this; - } public function updatePaidToDate(float $amount) { - - DB::connection(config('database.default'))->transaction(function () use($amount) { - + DB::connection(config('database.default'))->transaction(function () use ($amount) { $this->client = Client::withTrashed()->where('id', $this->client->id)->lockForUpdate()->first(); $this->client->paid_to_date += $amount; $this->client->saveQuietly(); - }, 2); return $this; - } public function adjustCreditBalance(float $amount) { - $this->client->credit_balance += $amount; return $this; - } public function getCreditBalance() :float { - $credits = Credit::withTrashed()->where('client_id', $this->client->id) ->where('is_deleted', false) ->where(function ($query) { @@ -109,7 +92,6 @@ class ClientService ->orderBy('created_at', 'ASC'); return Number::roundValue($credits->sum('balance'), $this->client->currency()->precision); - } public function getCredits() @@ -148,40 +130,38 @@ class ClientService $pdf = $statement->run(); - if($send_email) + if ($send_email) { return $this->emailStatement($pdf, $statement->options); + } return $pdf; } /** * Emails the statement to the client - * + * * @param mixed $pdf The pdf blob * @param array $options The statement options array - * @return void + * @return void */ private function emailStatement($pdf, array $options): void { - $this->client_start_date = $this->translateDate($options['start_date'], $this->client->date_format(), $this->client->locale()); $this->client_end_date = $this->translateDate($options['end_date'], $this->client->date_format(), $this->client->locale()); $email_service = new EmailService($this->buildStatementMailableData($pdf), $this->client->company); $email_service->send(); - } /** * Builds and returns an EmailObject for Client Statements - * + * * @param mixed $pdf The PDF to send * @return EmailObject The EmailObject to send */ public function buildStatementMailableData($pdf) :EmailObject { - $email_object = new EmailObject; $email_object->to = [new Address($this->client->present()->email(), $this->client->present()->name())]; $email_object->attachments = [['file' => base64_encode($pdf), 'name' => ctrans('texts.statement') . ".pdf"]]; @@ -197,12 +177,11 @@ class ClientService ]; return $email_object; - } /** * Saves the client instance - * + * * @return Client The Client Model */ public function save() :Client diff --git a/app/Services/Client/Merge.php b/app/Services/Client/Merge.php index b8700b458bb2..eeef8e5632e5 100644 --- a/app/Services/Client/Merge.php +++ b/app/Services/Client/Merge.php @@ -14,14 +14,8 @@ namespace App\Services\Client; use App\Factory\CompanyLedgerFactory; use App\Models\Activity; use App\Models\Client; -use App\Models\CompanyGateway; use App\Models\CompanyLedger; -use App\Models\GatewayType; -use App\Models\Invoice; -use App\Models\Payment; use App\Services\AbstractService; -use App\Utils\Ninja; -use App\Utils\Traits\MakesHash; class Merge extends AbstractService { diff --git a/app/Services/Client/PaymentMethod.php b/app/Services/Client/PaymentMethod.php index 56b850c1db64..8f095ea22fa3 100644 --- a/app/Services/Client/PaymentMethod.php +++ b/app/Services/Client/PaymentMethod.php @@ -14,9 +14,7 @@ namespace App\Services\Client; use App\Models\Client; use App\Models\CompanyGateway; use App\Models\GatewayType; -use App\Models\Invoice; use App\Models\Payment; -use App\Utils\Ninja; use App\Utils\Traits\MakesHash; class PaymentMethod @@ -121,7 +119,6 @@ class PaymentMethod $this->payment_methods = []; foreach ($this->gateways as $gateway) { - //if gateway doesn't exist or is not implemented - continue here //todo if (! $gateway->driver($this->client)) { continue; @@ -187,7 +184,6 @@ class PaymentMethod } if (($this->client->getSetting('use_credits_payment') == 'option' || $this->client->getSetting('use_credits_payment') == 'always') && $this->client->service()->getCreditBalance() > 0) { - // Show credits as only payment option if both statements are true. if ( $this->client->service()->getCreditBalance() > $this->amount diff --git a/app/Services/Client/Statement.php b/app/Services/Client/Statement.php index 1d02a4c77f89..4881aa83156d 100644 --- a/app/Services/Client/Statement.php +++ b/app/Services/Client/Statement.php @@ -40,7 +40,9 @@ class Statement protected bool $rollback = false; - public function __construct(protected Client $client, public array $options){} + public function __construct(protected Client $client, public array $options) + { + } public function run() :?string { diff --git a/app/Services/ClientPortal/InstantPayment.php b/app/Services/ClientPortal/InstantPayment.php index b1136f5d605b..359d1e9b8b73 100644 --- a/app/Services/ClientPortal/InstantPayment.php +++ b/app/Services/ClientPortal/InstantPayment.php @@ -13,9 +13,6 @@ namespace App\Services\ClientPortal; use App\Exceptions\PaymentFailed; -use App\Factory\PaymentFactory; -use App\Http\Controllers\Controller; -use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; use App\Jobs\Invoice\CheckGatewayFee; use App\Jobs\Invoice\InjectSignature; use App\Jobs\Util\SystemLogger; @@ -24,17 +21,13 @@ use App\Models\Invoice; use App\Models\Payment; use App\Models\PaymentHash; use App\Models\SystemLog; -use App\Services\Subscription\SubscriptionService; use App\Utils\Ninja; use App\Utils\Number; use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; -use Illuminate\Contracts\View\Factory; -use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; -use Illuminate\View\View; class InstantPayment { @@ -50,7 +43,6 @@ class InstantPayment public function run() { - $is_credit_payment = false; $tokens = []; @@ -96,7 +88,6 @@ class InstantPayment /* This loop checks for under / over payments and returns the user if a check fails */ foreach ($payable_invoices as $payable_invoice) { - /*Match the payable invoice to the Model Invoice*/ $invoice = $invoices->first(function ($inv) use ($payable_invoice) { @@ -197,8 +188,9 @@ class InstantPayment $starting_invoice_amount = $first_invoice->balance; /* Schedule a job to check the gateway fees for this invoice*/ - if(Ninja::isHosted()) + if (Ninja::isHosted()) { CheckGatewayFee::dispatch($first_invoice->id, $client->company->db)->delay(600); + } if ($gateway) { $first_invoice->service()->addGatewayFee($gateway, $payment_method_id, $invoice_totals)->save(); @@ -226,17 +218,12 @@ class InstantPayment if ($this->request->query('hash')) { $hash_data['billing_context'] = Cache::get($this->request->query('hash')); - } - elseif($this->request->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()) { - - if(isset($old_hash->data->billing_context)) - { + } elseif ($old_hash = PaymentHash::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; } - } $payment_hash = new PaymentHash; @@ -297,7 +284,7 @@ class InstantPayment } public function processCreditPayment(Request $request, array $data) - { + { return render('gateways.credit.index', $data); } } diff --git a/app/Services/Credit/ApplyPayment.php b/app/Services/Credit/ApplyPayment.php index f5494a4a2291..f9eeb7ec46e8 100644 --- a/app/Services/Credit/ApplyPayment.php +++ b/app/Services/Credit/ApplyPayment.php @@ -42,7 +42,6 @@ class ApplyPayment public function run() :Credit { - //$available_credit_balance = $this->credit->balance; $applicable_amount = min($this->amount, $this->credit->balance); $invoice_balance = $this->invoice->balance; diff --git a/app/Services/Credit/CreditService.php b/app/Services/Credit/CreditService.php index db02b1127d46..d9051df17224 100644 --- a/app/Services/Credit/CreditService.php +++ b/app/Services/Credit/CreditService.php @@ -19,8 +19,6 @@ use App\Models\Payment; use App\Models\PaymentType; use App\Repositories\CreditRepository; use App\Repositories\PaymentRepository; -use App\Services\Credit\CreateInvitations; -use App\Services\Credit\TriggeredActions; use App\Utils\Traits\MakesHash; class CreditService @@ -271,7 +269,6 @@ class CreditService public function restoreCredit() { - $this->credit ->client ->service() diff --git a/app/Services/Credit/GetCreditPdf.php b/app/Services/Credit/GetCreditPdf.php index ed8e8e2619ca..0ad1d9aac220 100644 --- a/app/Services/Credit/GetCreditPdf.php +++ b/app/Services/Credit/GetCreditPdf.php @@ -13,8 +13,6 @@ namespace App\Services\Credit; use App\Jobs\Entity\CreateEntityPdf; use App\Services\AbstractService; -use App\Utils\TempFile; -use Illuminate\Support\Facades\Storage; class GetCreditPdf extends AbstractService { diff --git a/app/Services/Credit/MarkSent.php b/app/Services/Credit/MarkSent.php index d8ad848dbc70..3402a019aab9 100644 --- a/app/Services/Credit/MarkSent.php +++ b/app/Services/Credit/MarkSent.php @@ -12,7 +12,6 @@ namespace App\Services\Credit; use App\Events\Credit\CreditWasMarkedSent; -use App\Jobs\Util\WebhookHandler; use App\Models\Credit; use App\Models\Webhook; use App\Utils\Ninja; @@ -31,7 +30,6 @@ class MarkSent public function run() { - /* Return immediately if status is not draft */ if ($this->credit->status_id != Credit::STATUS_DRAFT) { return $this->credit; diff --git a/app/Services/Credit/SendEmail.php b/app/Services/Credit/SendEmail.php index 6c0c5154d266..1f01f6ba67f1 100644 --- a/app/Services/Credit/SendEmail.php +++ b/app/Services/Credit/SendEmail.php @@ -11,8 +11,6 @@ namespace App\Services\Credit; -use App\Helpers\Email\CreditEmail; -use App\Jobs\Credit\EmailCredit; use App\Jobs\Entity\EmailEntity; use App\Models\ClientContact; diff --git a/app/Services/Credit/TriggeredActions.php b/app/Services/Credit/TriggeredActions.php index e08151736c48..fb909373959b 100644 --- a/app/Services/Credit/TriggeredActions.php +++ b/app/Services/Credit/TriggeredActions.php @@ -45,7 +45,7 @@ class TriggeredActions extends AbstractService $this->credit = $this->credit->service()->markSent()->save(); } - if($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') { + if ($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') { $company = $this->credit->company; $settings = $company->settings; $settings->credit_footer = $this->credit->footer; @@ -53,7 +53,7 @@ class TriggeredActions extends AbstractService $company->save(); } - if($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') { + if ($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') { $company = $this->credit->company; $settings = $company->settings; $settings->credit_terms = $this->credit->terms; diff --git a/app/Services/Email/EmailDefaults.php b/app/Services/Email/EmailDefaults.php index 698705dba8a1..153d14c2e349 100644 --- a/app/Services/Email/EmailDefaults.php +++ b/app/Services/Email/EmailDefaults.php @@ -13,14 +13,10 @@ namespace App\Services\Email; use App\DataMapper\EmailTemplateDefaults; use App\Models\Account; -use App\Models\Company; -use App\Services\Email\EmailObject; use App\Utils\Ninja; use Illuminate\Mail\Mailables\Address; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Mail; use League\CommonMark\CommonMarkConverter; -use Illuminate\Mail\Attachment; class EmailDefaults { @@ -46,12 +42,14 @@ class EmailDefaults * @param EmailService $email_service The email service class * @param EmailObject $email_object the email object class */ - public function __construct(protected EmailService $email_service, public EmailObject $email_object){} + public function __construct(protected EmailService $email_service, public EmailObject $email_object) + { + } /** - * Entry point for generating + * Entry point for generating * the defaults for the email object - * + * * @return EmailObject $email_object The email object */ public function run() @@ -70,7 +68,6 @@ class EmailDefaults ->setVariables(); return $this->email_object; - } /** @@ -78,7 +75,6 @@ class EmailDefaults */ private function setMetaData(): self { - $this->email_object->company_key = $this->email_service->company->company_key; $this->email_object->logo = $this->email_service->company->present()->logo(); @@ -88,7 +84,6 @@ class EmailDefaults $this->email_object->whitelabel = $this->email_object->company->account->isPaid() ? true : false; return $this; - } /** @@ -96,13 +91,13 @@ class EmailDefaults */ private function setLocale(): self { - - if($this->email_object->client) + if ($this->email_object->client) { $this->locale = $this->email_object->client->locale(); - elseif($this->email_object->vendor) + } elseif ($this->email_object->vendor) { $this->locale = $this->email_object->vendor->locale(); - else + } else { $this->locale = $this->email_service->company->locale(); + } App::setLocale($this->locale); App::forgetInstance('translator'); @@ -119,14 +114,14 @@ class EmailDefaults { $this->template = $this->email_object->settings->email_style; - match($this->email_object->settings->email_style){ + match ($this->email_object->settings->email_style) { 'light' => $this->template = 'email.template.client', 'dark' => $this->template = 'email.template.client', 'custom' => $this->template = 'email.template.custom', default => $this->template = 'email.template.client', - }; + }; - $this->email_object->html_template = $this->template; + $this->email_object->html_template = $this->template; return $this; } @@ -135,44 +130,39 @@ class EmailDefaults * Sets the FROM address */ private function setFrom(): self - { - - if(Ninja::isHosted() && $this->email_object->settings->email_sending_method == 'default'){ + { + if (Ninja::isHosted() && $this->email_object->settings->email_sending_method == 'default') { $this->email_object->from = new Address(config('mail.from.address'), $this->email_service->company->owner()->name()); return $this; } - if($this->email_object->from) + if ($this->email_object->from) { return $this; + } $this->email_object->from = new Address($this->email_service->company->owner()->email, $this->email_service->company->owner()->name()); return $this; - } - /** + /** * Sets the body of the email */ private function setBody(): self { - - if($this->email_object->body){ + if ($this->email_object->body) { $this->email_object->body = $this->email_object->body; - } - elseif(strlen($this->email_object->settings->{$this->email_object->email_template_body}) > 3){ + } elseif (strlen($this->email_object->settings->{$this->email_object->email_template_body}) > 3) { $this->email_object->body = $this->email_object->settings->{$this->email_object->email_template_body}; - } - else{ + } else { $this->email_object->body = EmailTemplateDefaults::getDefaultTemplate($this->email_object->email_template_body, $this->locale); } - if($this->template == 'email.template.custom'){ - $this->email_object->body = (str_replace('$body', $this->email_object->body, $this->email_object->settings->email_style_custom)); + if ($this->template == 'email.template.custom') { + $this->email_object->body = (str_replace('$body', $this->email_object->body, $this->email_object->settings->email_style_custom)); } return $this; - } /** @@ -180,16 +170,15 @@ class EmailDefaults */ private function setSubject(): self { - - if ($this->email_object->subject) //where the user updates the subject from the UI + if ($this->email_object->subject) { //where the user updates the subject from the UI return $this; - elseif(strlen($this->email_object->settings->{$this->email_object->email_template_subject}) > 3) + } elseif (strlen($this->email_object->settings->{$this->email_object->email_template_subject}) > 3) { $this->email_object->subject = $this->email_object->settings->{$this->email_object->email_template_subject}; - else + } else { $this->email_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->email_object->email_template_subject, $this->locale); + } return $this; - } /** @@ -197,7 +186,6 @@ class EmailDefaults */ private function setReplyTo(): self { - $reply_to_email = str_contains($this->email_object->settings->reply_to_email, "@") ? $this->email_object->settings->reply_to_email : $this->email_service->company->owner()->email; $reply_to_name = strlen($this->email_object->settings->reply_to_name) > 3 ? $this->email_object->settings->reply_to_name : $this->email_service->company->owner()->present()->name(); @@ -208,18 +196,18 @@ class EmailDefaults } /** - * Replaces the template placeholders + * Replaces the template placeholders * with variable values. */ public function setVariables(): self { - $this->email_object->body = strtr($this->email_object->body, $this->email_object->variables); $this->email_object->subject = strtr($this->email_object->subject, $this->email_object->variables); - if($this->template != 'custom') + if ($this->template != 'custom') { $this->email_object->body = $this->parseMarkdownToHtml($this->email_object->body); + } return $this; } @@ -233,16 +221,14 @@ class EmailDefaults $bcc_array = []; if (strlen($this->email_object->settings->bcc_email) > 1) { - if (Ninja::isHosted() && $this->email_service->company->account->isPaid()) { $bccs = array_slice(explode(',', str_replace(' ', '', $this->email_object->settings->bcc_email)), 0, 2); - } elseif(Ninja::isSelfHost()) { + } elseif (Ninja::isSelfHost()) { $bccs = (explode(',', str_replace(' ', '', $this->email_object->settings->bcc_email))); } } - foreach($bccs as $bcc) - { + foreach ($bccs as $bcc) { $bcc_array[] = new Address($bcc); } @@ -262,10 +248,10 @@ class EmailDefaults ]; } - /** + /** * Sets the attachments for the email * - * Note that we base64 encode these, as they + * Note that we base64 encode these, as they * sometimes may not survive serialization. * * We decode these in the Mailable later @@ -275,19 +261,14 @@ class EmailDefaults $attachments = []; if ($this->email_object->settings->document_email_attachment && $this->email_service->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - foreach ($this->email_service->company->documents as $document) { - $attachments[] = ['file' => base64_encode($document->getFile()), 'name' => $document->name]; - } - } $this->email_object->attachments = array_merge($this->email_object->attachments, $attachments); return $this; - } /** @@ -295,15 +276,16 @@ class EmailDefaults */ private function setHeaders(): self { - if($this->email_object->invitation_key) + if ($this->email_object->invitation_key) { $this->email_object->headers = array_merge($this->email_object->headers, ['x-invitation-key' => $this->email_object->invitation_key]); + } return $this; } /** * Converts any markdown to HTML in the email - * + * * @param string $markdown The body to convert * @return string The parsed markdown response */ @@ -315,5 +297,4 @@ class EmailDefaults return $converter->convert($markdown); } - -} \ No newline at end of file +} diff --git a/app/Services/Email/EmailMailable.php b/app/Services/Email/EmailMailable.php index fef31ca3ab30..116317e80e53 100644 --- a/app/Services/Email/EmailMailable.php +++ b/app/Services/Email/EmailMailable.php @@ -11,25 +11,22 @@ namespace App\Services\Email; -use App\Services\Email\EmailObject; -use Illuminate\Bus\Queueable; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Attachment; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; -use Illuminate\Queue\SerializesModels; use Illuminate\Mail\Mailables\Headers; class EmailMailable extends Mailable { - /** * Create a new message instance. * * @return void */ - public function __construct(public EmailObject $email_object){} + public function __construct(public EmailObject $email_object) + { + } /** * Get the message envelope. @@ -78,16 +75,13 @@ class EmailMailable extends Mailable */ public function attachments() { - $attachments = []; - foreach($this->email_object->attachments as $file) - { + foreach ($this->email_object->attachments as $file) { $attachments[] = Attachment::fromData(fn () => base64_decode($file['file']), $file['name']); } return $attachments; - } /** @@ -97,13 +91,10 @@ class EmailMailable extends Mailable */ public function headers() { - return new Headers( messageId: null, references: [], text: $this->email_object->headers, ); - } - } diff --git a/app/Services/Email/EmailMailer.php b/app/Services/Email/EmailMailer.php index 55fac55979ad..265b4f574c61 100644 --- a/app/Services/Email/EmailMailer.php +++ b/app/Services/Email/EmailMailer.php @@ -55,7 +55,9 @@ class EmailMailer implements ShouldQueue protected $client_mailgun_domain = false; - public function __construct(public EmailService $email_service, public Mailable $email_mailable){} + public function __construct(public EmailService $email_service, public Mailable $email_mailable) + { + } public function backoff() { @@ -64,40 +66,39 @@ class EmailMailer implements ShouldQueue public function handle(): void { - - MultiDB::setDb($this->email_service->company->db); + MultiDB::setDb($this->email_service->company->db); /* Perform final checks */ - if($this->email_service->preFlightChecksFail()) + if ($this->email_service->preFlightChecksFail()) { return; + } /* Boot the required driver*/ - $this->setMailDriver(); + $this->setMailDriver(); /* Init the mailer*/ - $mailer = Mail::mailer($this->mailer); + $mailer = Mail::mailer($this->mailer); /* Additional configuration if using a client third party mailer */ - if($this->client_postmark_secret) + if ($this->client_postmark_secret) { $mailer->postmark_config($this->client_postmark_secret); + } - if($this->client_mailgun_secret) + if ($this->client_mailgun_secret) { $mailer->mailgun_config($this->client_mailgun_secret, $this->client_mailgun_domain); + } /* Attempt the send! */ try { + nlog("Using mailer => ". $this->mailer. " ". now()->toDateTimeString()); - nlog("Using mailer => ". $this->mailer. " ". now()->toDateTimeString()); - - $mailer->send($this->email_mailable); + $mailer->send($this->email_mailable); - Cache::increment($this->email_service->company->account->key); - - LightLogs::create(new EmailSuccess($this->email_service->company->company_key)) - ->send(); + Cache::increment($this->email_service->company->account->key); + LightLogs::create(new EmailSuccess($this->email_service->company->company_key)) + ->send(); } catch (\Exception | \RuntimeException | \Google\Service\Exception $e) { - nlog("Mailer failed with {$e->getMessage()}"); $message = $e->getMessage(); @@ -107,12 +108,11 @@ class EmailMailer implements ShouldQueue * this merges a text string with a json object * need to harvest the ->Message property using the following */ - if($e instanceof ClientException) { //postmark specific failure - + if ($e instanceof ClientException) { //postmark specific failure $response = $e->getResponse(); $message_body = json_decode($response->getBody()->getContents()); - if($message_body && property_exists($message_body, 'Message')){ + if ($message_body && property_exists($message_body, 'Message')) { $message = $message_body->Message; nlog($message); } @@ -120,20 +120,17 @@ class EmailMailer implements ShouldQueue $this->fail(); $this->cleanUpMailers(); return; - } //only report once, not on all tries - if($this->attempts() == $this->tries) - { - + if ($this->attempts() == $this->tries) { /* If the is an entity attached to the message send a failure mailer */ $this->entityEmailFailed($message); /* Don't send postmark failures to Sentry */ - if(Ninja::isHosted() && (!$e instanceof ClientException)) + if (Ninja::isHosted() && (!$e instanceof ClientException)) { app('sentry')->captureException($e); - + } } @@ -141,12 +138,9 @@ class EmailMailer implements ShouldQueue $this->release($this->backoff()[$this->attempts()-1]); $message = null; - - } $this->cleanUpMailers(); - } /** @@ -158,38 +152,39 @@ class EmailMailer implements ShouldQueue */ private function entityEmailFailed($message) { - - if(!$this->email_service->email_object->entity_id) + if (!$this->email_service->email_object->entity_id) { return; + } switch ($this->email_service->email_object->entity_class) { case Invoice::class: - $invitation = InvoiceInvitation::withTrashed()->find($this->email_service->email_object->entity_id); - if($invitation) - event(new InvoiceWasEmailedAndFailed($invitation, $this->email_service->company, $message, $this->email_service->email_object->reminder_template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); + $invitation = InvoiceInvitation::withTrashed()->find($this->email_service->email_object->entity_id); + if ($invitation) { + event(new InvoiceWasEmailedAndFailed($invitation, $this->email_service->company, $message, $this->email_service->email_object->reminder_template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); + } break; case Payment::class: - $payment = Payment::withTrashed()->find($this->email_service->email_object->entity_id); - if($payment) - event(new PaymentWasEmailedAndFailed($payment, $this->email_service->company, $message, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); + $payment = Payment::withTrashed()->find($this->email_service->email_object->entity_id); + if ($payment) { + event(new PaymentWasEmailedAndFailed($payment, $this->email_service->company, $message, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); + } break; default: # code... break; } - if ($this->email_service->email_object->client_contact instanceof ClientContact) + if ($this->email_service->email_object->client_contact instanceof ClientContact) { $this->logMailError($message, $this->email_service->email_object->client_contact); - + } } - /** - * Sets the mail driver to use and applies any specific configuration + /** + * Sets the mail driver to use and applies any specific configuration * the the mailable */ - private function setMailDriver(): self + private function setMailDriver(): self { - switch ($this->email_service->email_object->settings->email_sending_method) { case 'default': $this->mailer = config('mail.default'); @@ -215,11 +210,11 @@ class EmailMailer implements ShouldQueue break; } - if(Ninja::isSelfHost()) + if (Ninja::isSelfHost()) { $this->setSelfHostMultiMailer(); + } return $this; - } /** @@ -228,10 +223,7 @@ class EmailMailer implements ShouldQueue */ private function setSelfHostMultiMailer(): void { - - if (env($this->email_service->company->id . '_MAIL_HOST')) - { - + if (env($this->email_service->company->id . '_MAIL_HOST')) { config([ 'mail.mailers.smtp' => [ 'transport' => 'smtp', @@ -242,20 +234,17 @@ class EmailMailer implements ShouldQueue ], ]); - if(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS')) - { - $this->email_mailable - ->from(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->email_service->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME'))); + if (env($this->email_service->company->id . '_MAIL_FROM_ADDRESS')) { + $this->email_mailable + ->from(env($this->email_service->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->email_service->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME'))); } - } - } /** * Ensure we discard any data that is not required - * + * * @return void */ private function cleanUpMailers(): void @@ -266,21 +255,20 @@ class EmailMailer implements ShouldQueue $this->client_mailgun_domain = false; - //always dump the drivers to prevent reuse + //always dump the drivers to prevent reuse app('mail.manager')->forgetMailers(); } - /** + /** * Check to ensure no cross account * emails can be sent. - * + * * @param User $user */ private function checkValidSendingUser($user) { /* Always ensure the user is set on the correct account */ - if($user->account_id != $this->email_service->company->account_id) - { + if ($user->account_id != $this->email_service->company->account_id) { $this->email_service->email_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -291,17 +279,18 @@ class EmailMailer implements ShouldQueue * Resolves the sending user * when configuring the Mailer * on behalf of the client - * + * * @return User $user */ private function resolveSendingUser(): ?User { $sending_user = $this->email_service->email_object->settings->gmail_sending_user_id; - if($sending_user == "0") + if ($sending_user == "0") { $user = $this->email_service->company->owner(); - else + } else { $user = User::find($this->decodePrimaryKey($sending_user)); + } return $user; } @@ -311,11 +300,10 @@ class EmailMailer implements ShouldQueue */ private function setMailgunMailer() { - if(strlen($this->email_service->email_object->settings->mailgun_secret) > 2 && strlen($this->email_service->email_object->settings->mailgun_domain) > 2){ + if (strlen($this->email_service->email_object->settings->mailgun_secret) > 2 && strlen($this->email_service->email_object->settings->mailgun_domain) > 2) { $this->client_mailgun_secret = $this->email_service->email_object->settings->mailgun_secret; $this->client_mailgun_domain = $this->email_service->email_object->settings->mailgun_domain; - } - else{ + } else { $this->email_service->email_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); } @@ -325,8 +313,8 @@ class EmailMailer implements ShouldQueue $sending_email = (isset($this->email_service->email_object->settings->custom_sending_email) && stripos($this->email_service->email_object->settings->custom_sending_email, "@")) ? $this->email_service->email_object->settings->custom_sending_email : $user->email; $sending_user = (isset($this->email_service->email_object->settings->email_from_name) && strlen($this->email_service->email_object->settings->email_from_name) > 2) ? $this->email_service->email_object->settings->email_from_name : $user->name(); - $this->email_mailable - ->from($sending_email, $sending_user); + $this->email_mailable + ->from($sending_email, $sending_user); } /** @@ -335,10 +323,9 @@ class EmailMailer implements ShouldQueue */ private function setPostmarkMailer() { - if(strlen($this->email_service->email_object->settings->postmark_secret) > 2){ + if (strlen($this->email_service->email_object->settings->postmark_secret) > 2) { $this->client_postmark_secret = $this->email_service->email_object->settings->postmark_secret; - } - else{ + } else { $this->email_service->email_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); } @@ -348,8 +335,8 @@ class EmailMailer implements ShouldQueue $sending_email = (isset($this->email_service->email_object->settings->custom_sending_email) && stripos($this->email_service->email_object->settings->custom_sending_email, "@")) ? $this->email_service->email_object->settings->custom_sending_email : $user->email; $sending_user = (isset($this->email_service->email_object->settings->email_from_name) && strlen($this->email_service->email_object->settings->email_from_name) > 2) ? $this->email_service->email_object->settings->email_from_name : $user->name(); - $this->email_mailable - ->from($sending_email, $sending_user); + $this->email_mailable + ->from($sending_email, $sending_user); } /** @@ -366,25 +353,19 @@ class EmailMailer implements ShouldQueue $token = $this->refreshOfficeToken($user); - if($token) - { + if ($token) { $user->oauth_user_token = $token; $user->save(); - - } - else { - + } else { $this->email_service->email_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); - } $this->email_mailable ->from($user->email, $user->name()) - ->withSymfonyMessage(function ($message) use($token) { - $message->getHeaders()->addTextHeader('gmailtoken', $token); + ->withSymfonyMessage(function ($message) use ($token) { + $message->getHeaders()->addTextHeader('gmailtoken', $token); }); - } /** @@ -393,7 +374,6 @@ class EmailMailer implements ShouldQueue */ private function setGmailMailer() { - $user = $this->resolveSendingUser(); $this->checkValidSendingUser($user); @@ -402,17 +382,14 @@ class EmailMailer implements ShouldQueue $google = (new Google())->init(); - try{ - + try { if ($google->getClient()->isAccessTokenExpired()) { $google->refreshToken($user); $user = $user->fresh(); } $google->getClient()->setAccessToken(json_encode($user->oauth_user_token)); - - } - catch(\Exception $e) { + } catch(\Exception $e) { $this->logMailError('Gmail Token Invalid', $this->email_service->company->clients()->first()); $this->email_service->email_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -422,7 +399,7 @@ class EmailMailer implements ShouldQueue * If the user doesn't have a valid token, notify them */ - if(!$user->oauth_user_token) { + if (!$user->oauth_user_token) { $this->email_service->company->account->gmailCredentialNotification(); $this->email_service->email_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -436,7 +413,7 @@ class EmailMailer implements ShouldQueue $token = $user->oauth_user_token->access_token; - if(!$token) { + if (!$token) { $this->email_service->company->account->gmailCredentialNotification(); $this->email_service->email_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -444,22 +421,20 @@ class EmailMailer implements ShouldQueue $this->email_mailable ->from($user->email, $user->name()) - ->withSymfonyMessage(function ($message) use($token) { - $message->getHeaders()->addTextHeader('gmailtoken', $token); + ->withSymfonyMessage(function ($message) use ($token) { + $message->getHeaders()->addTextHeader('gmailtoken', $token); }); - } /** * Logs any errors to the SystemLog - * + * * @param string $errors * @param App\Models\User | App\Models\Client $recipient_object * @return void */ private function logMailError($errors, $recipient_object) :void { - (new SystemLogger( $errors, SystemLog::CATEGORY_MAIL, @@ -477,12 +452,11 @@ class EmailMailer implements ShouldQueue ->send(); $job_failure = null; - } /** * Attempts to refresh the Microsoft refreshToken - * + * * @param App\Models\User * @return mixed */ @@ -490,10 +464,9 @@ class EmailMailer implements ShouldQueue { $expiry = $user->oauth_user_token_expiry ?: now()->subDay(); - if($expiry->lt(now())) - { - $guzzle = new \GuzzleHttp\Client(); - $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'; + if ($expiry->lt(now())) { + $guzzle = new \GuzzleHttp\Client(); + $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'; $token = json_decode($guzzle->post($url, [ 'form_params' => [ @@ -505,8 +478,7 @@ class EmailMailer implements ShouldQueue ], ])->getBody()->getContents()); - if($token){ - + if ($token) { $user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token; $user->oauth_user_token = $token->access_token; $user->oauth_user_token_expiry = now()->addSeconds($token->expires_in); @@ -519,12 +491,9 @@ class EmailMailer implements ShouldQueue } return $user->oauth_user_token; - } public function failed($exception = null) { - } - } diff --git a/app/Services/Email/EmailObject.php b/app/Services/Email/EmailObject.php index 30edec78ccde..a7da351727b6 100644 --- a/app/Services/Email/EmailObject.php +++ b/app/Services/Email/EmailObject.php @@ -13,7 +13,6 @@ namespace App\Services\Email; use App\Models\Client; use App\Models\ClientContact; -use App\Models\Company; use App\Models\User; use App\Models\Vendor; use App\Models\VendorContact; @@ -24,61 +23,59 @@ use Illuminate\Mail\Mailables\Address; */ class EmailObject { + public array $to = []; - public array $to = []; + public ?Address $from = null; - public ?Address $from = null; + public array $reply_to = []; - public array $reply_to = []; + public array $cc = []; - public array $cc = []; + public array $bcc = []; - public array $bcc = []; + public ?string $subject = null; - public ?string $subject = null; + public ?string $body = null; - public ?string $body = null; + public array $attachments = []; - public array $attachments = []; + public string $company_key; - public string $company_key; + public ?object $settings = null; - public ?object $settings = null; + public bool $whitelabel = false; - public bool $whitelabel = false; + public ?string $logo = null; - public ?string $logo = null; + public ?string $signature = null; - public ?string $signature = null; + public ?string $greeting = null; - public ?string $greeting = null; + public ?Client $client = null; - public ?Client $client = null; + public ?Vendor $vendor = null; - public ?Vendor $vendor = null; + public ?User $user = null; - public ?User $user = null; + public ?ClientContact $client_contact = null; - public ?ClientContact $client_contact = null; + public ?VendorContact $vendor_contact = null; - public ?VendorContact $vendor_contact = null; + public ?string $email_template_body = null; - public ?string $email_template_body = null; + public ?string $email_template_subject = null; - public ?string $email_template_subject = null; + public ?string $html_template = null; - public ?string $html_template = null; + public ?string $text_template = 'email.template.text'; - public ?string $text_template = 'email.template.text'; + public array $headers = []; - public array $headers = []; + public ?string $invitation_key = null; + + public ?int $entity_id = null; - public ?string $invitation_key = null; - - public ?int $entity_id = null; + public ?string $entity_class = null; - public ?string $entity_class = null; - - public array $variables = []; - -} \ No newline at end of file + public array $variables = []; +} diff --git a/app/Services/Email/EmailService.php b/app/Services/Email/EmailService.php index 5d2ddcc37da3..731815deaefc 100644 --- a/app/Services/Email/EmailService.php +++ b/app/Services/Email/EmailService.php @@ -12,23 +12,23 @@ namespace App\Services\Email; use App\Models\Company; -use App\Services\Email\EmailObject; use App\Utils\Ninja; use Illuminate\Mail\Mailable; class EmailService { - /** * Used to flag whether we force send the email regardless - * + * * @var bool $override; */ protected bool $override; public Mailable $mailable; - public function __construct(public EmailObject $email_object, public Company $company){} + public function __construct(public EmailObject $email_object, public Company $company) + { + } /** * Sends the email via a dispatched job @@ -53,11 +53,11 @@ class EmailService private function email($force = false): void { - if($force) + if ($force) { (new EmailMailer($this, $this->mailable))->handle(); - else + } else { EmailMailer::dispatch($this, $this->mailable)->delay(2); - + } } private function setDefaults(): self @@ -76,41 +76,45 @@ class EmailService } /** - * On the hosted platform we scan all outbound email for + * On the hosted platform we scan all outbound email for * spam. This sequence processes the filters we use on all * emails. - * + * * @return bool */ public function preFlightChecksFail(): bool { - /* If we are migrating data we don't want to fire any emails */ - if($this->company->is_disabled && !$this->override) + if ($this->company->is_disabled && !$this->override) { return true; + } - if(Ninja::isSelfHost()) + if (Ninja::isSelfHost()) { return false; + } /* To handle spam users we drop all emails from flagged accounts */ - if($this->company->account && $this->company->account->is_flagged) + if ($this->company->account && $this->company->account->is_flagged) { return true; + } /* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */ - if($this->hasInValidEmails()) + if ($this->hasInValidEmails()) { return true; + } /* GMail users are uncapped */ - if(in_array($this->email_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun'])) + if (in_array($this->email_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun'])) { return false; + } /* On the hosted platform, if the user is over the email quotas, we do not send the email. */ - if($this->company->account && $this->company->account->emailQuotaExceeded()) + if ($this->company->account && $this->company->account->emailQuotaExceeded()) { return true; + } /* If the account is verified, we allow emails to flow */ - if($this->company->account && $this->company->account->is_verified_account) { - + if ($this->company->account && $this->company->account->is_verified_account) { //11-01-2022 /* Continue to analyse verified accounts in case they later start sending poor quality emails*/ @@ -121,40 +125,39 @@ class EmailService } /* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */ - if($this->company->account && !$this->company->account->account_sms_verified){ - - if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) + if ($this->company->account && !$this->company->account->account_sms_verified) { + if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) { return (new \Modules\Admin\Jobs\Account\EmailFilter($this->email_object, $this->company))->run(); + } return true; } /* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */ - if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) + if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) { return (new \Modules\Admin\Jobs\Account\EmailFilter($this->email_object, $this->company))->run(); + } return false; } private function hasInValidEmails(): bool { - - foreach($this->email_object->to as $address_object) - { - - if(strpos($address_object->address, '@example.com') !== false) + foreach ($this->email_object->to as $address_object) { + if (strpos($address_object->address, '@example.com') !== false) { return true; + } - if(!str_contains($address_object->address, "@")) + if (!str_contains($address_object->address, "@")) { return true; + } - if($address_object->address == " ") + if ($address_object->address == " ") { return true; + } } return false; } - - -} \ No newline at end of file +} diff --git a/app/Services/Email/MailBuild.php b/app/Services/Email/MailBuild.php index 4117a9b72ff7..51ac2a89e452 100644 --- a/app/Services/Email/MailBuild.php +++ b/app/Services/Email/MailBuild.php @@ -11,36 +11,35 @@ namespace App\Services\Email; -use App\Models\Task; -use App\Utils\Ninja; -use App\Models\Quote; -use App\Models\Client; -use App\Models\Credit; -use App\Models\Vendor; +use App\DataMapper\EmailTemplateDefaults; +use App\Jobs\Entity\CreateRawPdf; +use App\Jobs\Vendor\CreatePurchaseOrderPdf; use App\Models\Account; +use App\Models\Client; +use App\Models\ClientContact; +use App\Models\Credit; use App\Models\Expense; use App\Models\Invoice; -use App\Utils\HtmlEngine; -use App\Models\ClientContact; use App\Models\PurchaseOrder; +use App\Models\Quote; +use App\Models\Task; +use App\Models\Vendor; use App\Models\VendorContact; +use App\Utils\HtmlEngine; +use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use App\Utils\VendorHtmlEngine; -use App\Jobs\Entity\CreateRawPdf; +use Illuminate\Contracts\Mail\Mailable; +use Illuminate\Mail\Mailables\Address; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\URL; -use App\Services\Email\MailMailable; -use Illuminate\Mail\Mailables\Address; -use Illuminate\Contracts\Mail\Mailable; -use App\DataMapper\EmailTemplateDefaults; use League\CommonMark\CommonMarkConverter; -use App\Jobs\Vendor\CreatePurchaseOrderPdf; class MailBuild { use MakesHash; - /** @var mixed $settings */ + /** @var mixed $settings */ protected $settings; /** @var string $template */ @@ -70,7 +69,9 @@ class MailBuild * @param MailEntity $mail_entity * @return void */ - public function __construct(public MailEntity $mail_entity){} + public function __construct(public MailEntity $mail_entity) + { + } /** * Builds the mailable @@ -113,7 +114,6 @@ class MailBuild */ private function resolveEntities(): self { - $client_contact = $this->mail_entity?->invitation?->client_contact_id ? ClientContact::withTrashed()->find($this->mail_entity->invitation->client_contact_id) : null; $this->client = $client_contact?->client; @@ -122,26 +122,24 @@ class MailBuild $this->vendor = $vendor_contact?->vendor; - if($this->mail_entity?->invitation){ - - - if($this->mail_entity->invitation?->invoice){ + if ($this->mail_entity?->invitation) { + if ($this->mail_entity->invitation?->invoice) { $this->mail_entity->mail_object->entity_string = 'invoice'; $this->mail_entity->mail_object->entity_class = Invoice::class; } - if($this->mail_entity->invitation?->quote){ - $this->mail_entity->mail_object->entity_string = 'quote'; + if ($this->mail_entity->invitation?->quote) { + $this->mail_entity->mail_object->entity_string = 'quote'; $this->mail_entity->mail_object->entity_class = Quote::class; } - if($this->mail_entity->invitation?->credit){ - $this->mail_entity->mail_object->entity_string = 'credit'; + if ($this->mail_entity->invitation?->credit) { + $this->mail_entity->mail_object->entity_string = 'credit'; $this->mail_entity->mail_object->entity_class = Credit::class; } - if($this->mail_entity->invitation?->puchase_order){ - $this->mail_entity->mail_object->entity_string = 'purchase_order'; + if ($this->mail_entity->invitation?->puchase_order) { + $this->mail_entity->mail_object->entity_string = 'purchase_order'; $this->mail_entity->mail_object->entity_class = PurchaseOrder::class; } } @@ -158,31 +156,23 @@ class MailBuild */ private function setLocale(): self { - - if($this->client){ - + if ($this->client) { $this->locale = $this->client->locale(); $this->settings = $this->client->getMergedSettings(); - if($this->mail_entity->invitation) + if ($this->mail_entity->invitation) { $this->variables = (new HtmlEngine($this->mail_entity->invitation))->makeValues(); - - } - elseif($this->vendor){ - + } + } elseif ($this->vendor) { $this->locale = $this->vendor->locale(); $this->settings = $this->mail_entity->company->settings; - if($this->mail_entity->invitation) + if ($this->mail_entity->invitation) { $this->variables = (new VendorHtmlEngine($this->mail_entity->invitation))->makeValues(); - - - } - else{ - + } + } else { $this->locale = $this->mail_entity->company->locale(); $this->settings = $this->mail_entity->company->settings; - } $this->mail_entity->mail_object->settings = $this->settings; @@ -202,7 +192,6 @@ class MailBuild */ private function setMetaData(): self { - $this->mail_entity->mail_object->company_key = $this->mail_entity->company->company_key; $this->mail_entity->mail_object->logo = $this->mail_entity->company->present()->logo(); @@ -214,7 +203,6 @@ class MailBuild $this->mail_entity->mail_object->company = $this->mail_entity->company; return $this; - } /** @@ -226,14 +214,14 @@ class MailBuild { $this->template = $this->settings->email_style; - match($this->settings->email_style){ + match ($this->settings->email_style) { 'light' => $this->template = 'email.template.client', 'dark' => $this->template = 'email.template.client', 'custom' => $this->template = 'email.template.custom', default => $this->template = 'email.template.client', - }; + }; - $this->mail_entity->mail_object->html_template = $this->template; + $this->mail_entity->mail_object->html_template = $this->template; return $this; } @@ -245,11 +233,10 @@ class MailBuild */ private function setTo(): self { - $this->mail_entity->mail_object->to = array_merge( - $this->mail_entity->mail_object->to , - [new Address($this->mail_entity->invitation->contact->email, $this->mail_entity->invitation->contact->present()->name())] - ); + $this->mail_entity->mail_object->to, + [new Address($this->mail_entity->invitation->contact->email, $this->mail_entity->invitation->contact->present()->name())] + ); return $this; } @@ -260,20 +247,19 @@ class MailBuild * @return self */ private function setFrom(): self - { - - if(Ninja::isHosted() && $this->settings->email_sending_method == 'default'){ + { + if (Ninja::isHosted() && $this->settings->email_sending_method == 'default') { $this->mail_entity->mail_object->from = new Address(config('mail.from.address'), $this->mail_entity->company->owner()->name()); return $this; } - if($this->mail_entity->mail_object->from) + if ($this->mail_entity->mail_object->from) { return $this; + } $this->mail_entity->mail_object->from = new Address($this->mail_entity->company->owner()->email, $this->mail_entity->company->owner()->name()); return $this; - } /** @@ -283,16 +269,15 @@ class MailBuild */ private function setSubject(): self { - - if ($this->mail_entity->mail_object->subject) //where the user updates the subject from the UI + if ($this->mail_entity->mail_object->subject) { //where the user updates the subject from the UI return $this; - elseif(is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate()}) > 3) + } elseif (is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate()}) > 3) { $this->mail_entity->mail_object->subject = $this->settings->{$this->resolveBaseEntityTemplate()}; - else + } else { $this->mail_entity->mail_object->subject = EmailTemplateDefaults::getDefaultTemplate($this->resolveBaseEntityTemplate(), $this->locale); + } return $this; - } /** @@ -302,27 +287,23 @@ class MailBuild */ private function setBody(): self { - - if($this->mail_entity->mail_object->body){ + if ($this->mail_entity->mail_object->body) { $this->mail_entity->mail_object->body = $this->mail_entity->mail_object->body; - } - elseif(is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate('body')}) > 3){ + } elseif (is_string($this->mail_entity->mail_object->email_template) && strlen($this->settings->{$this->resolveBaseEntityTemplate('body')}) > 3) { $this->mail_entity->mail_object->body = $this->settings->{$this->resolveBaseEntityTemplate('body')}; - } - else{ + } else { $this->mail_entity->mail_object->body = EmailTemplateDefaults::getDefaultTemplate($this->resolveBaseEntityTemplate('body'), $this->locale); } - if($this->template == 'email.template.custom'){ - $this->mail_entity->mail_object->body = (str_replace('$body', $this->mail_entity->mail_object->body, $this->settings->email_style_custom)); + if ($this->template == 'email.template.custom') { + $this->mail_entity->mail_object->body = (str_replace('$body', $this->mail_entity->mail_object->body, $this->settings->email_style_custom)); } return $this; - } /** - * Where no template is explicitly passed, we need to infer by the entity type - + * Where no template is explicitly passed, we need to infer by the entity type - * which is hopefully resolvable. * * @param string $type @@ -330,9 +311,8 @@ class MailBuild */ private function resolveBaseEntityTemplate(string $type = 'subject'): string { - if($this->mail_entity->mail_object->email_template){ - - match($type){ + if ($this->mail_entity->mail_object->email_template) { + match ($type) { 'subject' => $template = "email_subject_{$this->mail_entity->mail_object->email_template}", 'body' => $template = "email_template_{$this->mail_entity->mail_object->email_template}", default => $template = "email_template_invoice", @@ -343,52 +323,48 @@ class MailBuild //handle statements being emailed //handle custom templates these types won't have a resolvable entity_string - if(!$this->mail_entity->mail_object->entity_string) + if (!$this->mail_entity->mail_object->entity_string) { return 'email_template_invoice'; + } - match($type){ + match ($type) { 'subject' => $template = "email_subject_{$this->mail_entity->mail_object->entity_string}", 'body' => $template = "email_template_{$this->mail_entity->mail_object->entity_string}", default => $template = "email_template_invoice", - }; + }; - return $template; + return $template; } - /** + /** * Sets the attachments for the email * - * Note that we base64 encode these, as they + * Note that we base64 encode these, as they * sometimes may not survive serialization. * * We decode these in the Mailable later - * + * * @return self - */ + */ private function setAttachments(): self { $this->setContextAttachments(); if ($this->settings->document_email_attachment && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - $this->attachDocuments($this->mail_entity->company->documents); - } return $this; - } private function attachDocuments($documents): self { - foreach ($documents as $document) { - - if($document->size > $this->max_attachment_size) + if ($document->size > $this->max_attachment_size) { $this->mail_entity->mail_object->attachment_links = array_merge($this->mail_entity->mail_object->attachment_links, [[" $document->hash]) ."'>". $document->name .""]]); - else - $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments,[['file' => base64_encode($document->getFile()), 'name' => $document->name]]); - + } else { + $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($document->getFile()), 'name' => $document->name]]); + } } return $this; @@ -397,7 +373,7 @@ class MailBuild /** * Depending on context we may need to resolve the * attachment dependencies. - * + * * ie. Resolve the entity. * ie. Resolve if we should attach the Entity PDF * ie. Create the Entity PDF @@ -407,52 +383,43 @@ class MailBuild */ private function setContextAttachments(): self { - - if(!$this->settings->pdf_email_attachment || !$this->mail_entity->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) + if (!$this->settings->pdf_email_attachment || !$this->mail_entity->company->account->hasFeature(Account::FEATURE_PDF_ATTACHMENT)) { return $this; + } - if($this->mail_entity->invitation?->purchase_order){ - + if ($this->mail_entity->invitation?->purchase_order) { $pdf = (new CreatePurchaseOrderPdf($this->mail_entity->invitation))->rawPdf(); $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->purchase_order->numberFormatter().'.pdf']]); if ($this->vendor->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - $this->attachDocuments($this->mail_entity->invitation->purchase_order->documents); - } return $this; - } - if(!$this->mail_entity->mail_object->entity_string) + if (!$this->mail_entity->mail_object->entity_string) { return $this; + } $pdf = ((new CreateRawPdf($this->mail_entity->invitation, $this->mail_entity->invitation->company->db))->handle()); $this->mail_entity->mail_object->attachments = array_merge($this->mail_entity->mail_object->attachments, [['file' => base64_encode($pdf), 'name' => $this->mail_entity->invitation->{$this->mail_entity->mail_object->entity_string}->numberFormatter().'.pdf']]); if ($this->client->getSetting('document_email_attachment') !== false && $this->mail_entity->company->account->hasFeature(Account::FEATURE_DOCUMENTS)) { - $this->attachDocuments($this->mail_entity->invitation->{$this->mail_entity->mail_object->entity_string}->documents); - } - return $this; + return $this; - if($this->settings->ubl_email_attachment && $this->mail_entity->mail_object->entity_string == 'invoice') - { - - } + if ($this->settings->ubl_email_attachment && $this->mail_entity->mail_object->entity_string == 'invoice') { + } - if($this->mail_entity->mail_object->entity_string == 'invoice') - { - + if ($this->mail_entity->mail_object->entity_string == 'invoice') { $line_items = $this->mail_entity->invitation->invoice->line_items; foreach ($line_items as $item) { @@ -467,9 +434,7 @@ class MailBuild ->where('invoice_documents', 1) ->cursor() ->each(function ($expense) { - - $this->attachDocuments($expense->documents); - + $this->attachDocuments($expense->documents); }); } @@ -483,28 +448,24 @@ class MailBuild $tasks = Task::whereIn('id', $this->transformKeys($task_ids)) ->cursor() ->each(function ($task) { - - $this->attachDocuments($task->documents); - + $this->attachDocuments($task->documents); }); } } } - return $this; - + return $this; } /** * Sets the reply to of the email - * + * * @return self */ private function setReplyTo(): self { - $reply_to_email = str_contains($this->settings->reply_to_email, "@") ? $this->settings->reply_to_email : $this->mail_entity->company->owner()->email; $reply_to_name = strlen($this->settings->reply_to_name) > 3 ? $this->settings->reply_to_name : $this->mail_entity->company->owner()->present()->name(); @@ -515,15 +476,14 @@ class MailBuild } /** - * Replaces the template placeholders + * Replaces the template placeholders * with variable values. - * + * * @return self */ public function setVariables(): self { - - if($this->mail_entity->mail_object->variables){ + if ($this->mail_entity->mail_object->variables) { $this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $this->mail_entity->mail_object->variables); $this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $this->mail_entity->mail_object->variables); } @@ -531,16 +491,16 @@ class MailBuild $this->mail_entity->mail_object->subject = strtr($this->mail_entity->mail_object->subject, $this->variables); $this->mail_entity->mail_object->body = strtr($this->mail_entity->mail_object->body, $this->variables); - if($this->template != 'custom') + if ($this->template != 'custom') { $this->mail_entity->mail_object->body = $this->parseMarkdownToHtml($this->mail_entity->mail_object->body); + } return $this; - } /** * Sets the BCC of the email - * + * * @return self */ private function setBcc(): self @@ -549,16 +509,14 @@ class MailBuild $bcc_array = []; if (strlen($this->settings->bcc_email) > 1) { - if (Ninja::isHosted() && $this->mail_entity->company->account->isPaid()) { $bccs = array_slice(explode(',', str_replace(' ', '', $this->settings->bcc_email)), 0, 2); - } elseif(Ninja::isSelfHost()) { + } elseif (Ninja::isSelfHost()) { $bccs = (explode(',', str_replace(' ', '', $this->settings->bcc_email))); } } - foreach($bccs as $bcc) - { + foreach ($bccs as $bcc) { $bcc_array[] = new Address($bcc); } @@ -581,22 +539,23 @@ class MailBuild /** * Sets the headers for the email - * + * * @return self */ private function setHeaders(): self { - if($this->mail_entity->mail_object->invitation_key) + if ($this->mail_entity->mail_object->invitation_key) { $this->mail_entity->mail_object->headers = array_merge($this->mail_entity->mail_object->headers, ['x-invitation-key' => $this->mail_entity->mail_object->invitation_key]); - elseif($this->mail_entity->invitation) + } elseif ($this->mail_entity->invitation) { $this->mail_entity->mail_object->headers = array_merge($this->mail_entity->mail_object->headers, ['x-invitation-key' => $this->mail_entity->invitation->key]); + } return $this; } /** * Converts any markdown to HTML in the email - * + * * @param string $markdown The body to convert * @return string The parsed markdown response */ @@ -608,8 +567,4 @@ class MailBuild return $converter->convert($markdown); } - - - - } diff --git a/app/Services/Email/MailEntity.php b/app/Services/Email/MailEntity.php index 3ba13719f267..14e6b2a7b392 100644 --- a/app/Services/Email/MailEntity.php +++ b/app/Services/Email/MailEntity.php @@ -11,24 +11,23 @@ namespace App\Services\Email; +use App\DataMapper\Analytics\EmailSuccess; +use App\Libraries\Google\Google; +use App\Libraries\MultiDB; +use App\Models\Company; use App\Models\User; use App\Utils\Ninja; -use App\Models\Company; -use App\Libraries\MultiDB; -use Illuminate\Bus\Queueable; -use Illuminate\Mail\Mailable; use App\Utils\Traits\MakesHash; -use App\Libraries\Google\Google; -use App\Services\Email\MailBuild; -use Illuminate\Support\Facades\Mail; -use Illuminate\Support\Facades\Cache; -use Illuminate\Queue\SerializesModels; -use Turbo124\Beacon\Facades\LightLogs; -use Illuminate\Queue\InteractsWithQueue; use GuzzleHttp\Exception\ClientException; -use App\DataMapper\Analytics\EmailSuccess; +use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; +use Illuminate\Mail\Mailable; +use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Queue\SerializesModels; +use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Mail; +use Turbo124\Beacon\Facades\LightLogs; class MailEntity implements ShouldQueue { @@ -62,7 +61,9 @@ class MailEntity implements ShouldQueue * @param mixed $mail_object * @return void */ - public function __construct(public mixed $invitation, private ?string $db, public MailObject $mail_object){} + public function __construct(public mixed $invitation, private ?string $db, public MailObject $mail_object) + { + } /** * Handle the job @@ -71,7 +72,6 @@ class MailEntity implements ShouldQueue */ public function handle(): void { - MultiDB::setDb($this->db); /* Where there are no invitations, we need to harvest the company and also use the correct context to build the mailable*/ @@ -81,19 +81,19 @@ class MailEntity implements ShouldQueue $builder = new MailBuild($this); - /* Construct Mailable */ + /* Construct Mailable */ $builder->run($this); $this->mailable = $builder->getMailable(); /* Email quality checks */ - if($this->preFlightChecksFail()) + if ($this->preFlightChecksFail()) { return; + } /* Try sending email */ $this->setMailDriver() ->trySending(); - } public function configureMailer(): self @@ -106,13 +106,12 @@ class MailEntity implements ShouldQueue } - /** - * Sets the mail driver to use and applies any specific configuration + /** + * Sets the mail driver to use and applies any specific configuration * the the mailable */ - private function setMailDriver(): self + private function setMailDriver(): self { - switch ($this->mail_object->settings->email_sending_method) { case 'default': $this->mailer = config('mail.default'); @@ -138,11 +137,11 @@ class MailEntity implements ShouldQueue break; } - if(Ninja::isSelfHost()) + if (Ninja::isSelfHost()) { $this->setSelfHostMultiMailer(); + } return $this; - } /** @@ -151,10 +150,7 @@ class MailEntity implements ShouldQueue */ private function setSelfHostMultiMailer(): void { - - if (env($this->company->id . '_MAIL_HOST')) - { - + if (env($this->company->id . '_MAIL_HOST')) { config([ 'mail.mailers.smtp' => [ 'transport' => 'smtp', @@ -165,20 +161,17 @@ class MailEntity implements ShouldQueue ], ]); - if(env($this->company->id . '_MAIL_FROM_ADDRESS')) - { - $this->mailable - ->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME'))); + if (env($this->company->id . '_MAIL_FROM_ADDRESS')) { + $this->mailable + ->from(env($this->company->id . '_MAIL_FROM_ADDRESS', env('MAIL_FROM_ADDRESS')), env($this->company->id . '_MAIL_FROM_NAME', env('MAIL_FROM_NAME'))); } - } - } /** * Ensure we discard any data that is not required - * + * * @return void */ private function cleanUpMailers(): void @@ -201,7 +194,6 @@ class MailEntity implements ShouldQueue public function trySending(): void { try { - $mail = Mail::mailer($this->mailer); $mail->send($this->mailable); @@ -210,24 +202,19 @@ class MailEntity implements ShouldQueue LightLogs::create(new EmailSuccess($this->company->company_key)) ->send(); - - } - catch(\Symfony\Component\Mime\Exception\RfcComplianceException $e) { - nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); - $this->fail(); - $this->cleanUpMailers(); - // $this->logMailError($e->getMessage(), $this->company->clients()->first()); - return; - } - catch(\Symfony\Component\Mime\Exception\LogicException $e){ - nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); - $this->fail(); - $this->cleanUpMailers(); - // $this->logMailError($e->getMessage(), $this->company->clients()->first()); - return; - } - catch (\Exception | \Google\Service\Exception $e) { - + } catch(\Symfony\Component\Mime\Exception\RfcComplianceException $e) { + nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); + $this->fail(); + $this->cleanUpMailers(); + // $this->logMailError($e->getMessage(), $this->company->clients()->first()); + return; + } catch(\Symfony\Component\Mime\Exception\LogicException $e) { + nlog("Mailer failed with a Logic Exception {$e->getMessage()}"); + $this->fail(); + $this->cleanUpMailers(); + // $this->logMailError($e->getMessage(), $this->company->clients()->first()); + return; + } catch (\Exception | \Google\Service\Exception $e) { nlog("Mailer failed with {$e->getMessage()}"); $message = $e->getMessage(); @@ -236,9 +223,7 @@ class MailEntity implements ShouldQueue * this merges a text string with a json object * need to harvest the ->Message property using the following */ - if(stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) - { - + if (stripos($e->getMessage(), 'code 406') || stripos($e->getMessage(), 'code 300') || stripos($e->getMessage(), 'code 413')) { $message = "Either Attachment too large, or recipient has been suppressed."; $this->fail(); @@ -246,63 +231,65 @@ class MailEntity implements ShouldQueue $this->cleanUpMailers(); return; - } //only report once, not on all tries - if($this->attempts() == $this->tries) - { - + if ($this->attempts() == $this->tries) { /* If the is an entity attached to the message send a failure mailer */ - if($this->mail_object->entity_id) + if ($this->mail_object->entity_id) { // $this->entityEmailFailed($message); - /* Don't send postmark failures to Sentry */ - if(Ninja::isHosted() && (!$e instanceof ClientException)) - app('sentry')->captureException($e); - + /* Don't send postmark failures to Sentry */ + if (Ninja::isHosted() && (!$e instanceof ClientException)) { + app('sentry')->captureException($e); + } + } } /* Releasing immediately does not add in the backoff */ $this->release($this->backoff()[$this->attempts()-1]); - } } /** - * On the hosted platform we scan all outbound email for + * On the hosted platform we scan all outbound email for * spam. This sequence processes the filters we use on all * emails. */ public function preFlightChecksFail(): bool { /* Handle bad state */ - if(!$this->company) + if (!$this->company) { return true; + } /* Handle deactivated company */ - if($this->company->is_disabled && !$this->override) + if ($this->company->is_disabled && !$this->override) { return true; + } /* To handle spam users we drop all emails from flagged accounts */ - if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) + if (Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged) { return true; + } /* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */ - if($this->hasInValidEmails()) + if ($this->hasInValidEmails()) { return true; + } /* GMail users are uncapped */ - if(in_array($this->mail_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun'])) + if (in_array($this->mail_object->settings->email_sending_method, ['gmail', 'office365', 'client_postmark', 'client_mailgun'])) { return false; + } /* On the hosted platform, if the user is over the email quotas, we do not send the email. */ - if(Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded()) + if (Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded()) { return true; + } /* If the account is verified, we allow emails to flow */ - if(Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) { - + if (Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) { //11-01-2022 /* Continue to analyse verified accounts in case they later start sending poor quality emails*/ @@ -314,21 +301,20 @@ class MailEntity implements ShouldQueue /* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */ - if($this->company->account && !$this->company->account->account_sms_verified){ - - if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) + if ($this->company->account && !$this->company->account->account_sms_verified) { + if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) { (new \Modules\Admin\Jobs\Account\EmailFilter($this->mail_object, $this->company))->run(); + } return true; - } /* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */ - if(class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) + if (class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) { (new \Modules\Admin\Jobs\Account\EmailFilter($this->mail_object, $this->company))->run(); + } return false; - } @@ -339,20 +325,22 @@ class MailEntity implements ShouldQueue */ private function hasInValidEmails(): bool { - if(Ninja::isSelfHost()) + if (Ninja::isSelfHost()) { return false; + } - foreach($this->mail_object->to as $address_object) - { - - if(strpos($address_object->address, '@example.com') !== false) + foreach ($this->mail_object->to as $address_object) { + if (strpos($address_object->address, '@example.com') !== false) { return true; + } - if(!str_contains($address_object->address, "@")) + if (!str_contains($address_object->address, "@")) { return true; + } - if($address_object->address == " ") + if ($address_object->address == " ") { return true; + } } @@ -360,17 +348,16 @@ class MailEntity implements ShouldQueue } - /** + /** * Check to ensure no cross account * emails can be sent. - * + * * @param User $user */ private function checkValidSendingUser($user) { /* Always ensure the user is set on the correct account */ - if($user->account_id != $this->company->account_id){ - + if ($user->account_id != $this->company->account_id) { $this->mail_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); } @@ -380,17 +367,18 @@ class MailEntity implements ShouldQueue * Resolves the sending user * when configuring the Mailer * on behalf of the client - * + * * @return User $user */ private function resolveSendingUser(): ?User { $sending_user = $this->mail_object->settings->gmail_sending_user_id; - if($sending_user == "0") + if ($sending_user == "0") { $user = $this->company->owner(); - else + } else { $user = User::find($this->decodePrimaryKey($sending_user)); + } return $user; } @@ -401,11 +389,10 @@ class MailEntity implements ShouldQueue */ private function setMailgunMailer() { - if(strlen($this->mail_object->settings->mailgun_secret) > 2 && strlen($this->mail_object->settings->mailgun_domain) > 2){ + if (strlen($this->mail_object->settings->mailgun_secret) > 2 && strlen($this->mail_object->settings->mailgun_domain) > 2) { $this->client_mailgun_secret = $this->mail_object->settings->mailgun_secret; $this->client_mailgun_domain = $this->mail_object->settings->mailgun_domain; - } - else{ + } else { $this->mail_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); } @@ -415,8 +402,8 @@ class MailEntity implements ShouldQueue $sending_email = (isset($this->mail_object->settings->custom_sending_email) && stripos($this->mail_object->settings->custom_sending_email, "@")) ? $this->mail_object->settings->custom_sending_email : $user->email; $sending_user = (isset($this->mail_object->settings->email_from_name) && strlen($this->mail_object->settings->email_from_name) > 2) ? $this->mail_object->settings->email_from_name : $user->name(); - $this->mailable - ->from($sending_email, $sending_user); + $this->mailable + ->from($sending_email, $sending_user); } /** @@ -425,10 +412,9 @@ class MailEntity implements ShouldQueue */ private function setPostmarkMailer() { - if(strlen($this->mail_object->settings->postmark_secret) > 2){ + if (strlen($this->mail_object->settings->postmark_secret) > 2) { $this->client_postmark_secret = $this->mail_object->settings->postmark_secret; - } - else{ + } else { $this->mail_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); } @@ -438,8 +424,8 @@ class MailEntity implements ShouldQueue $sending_email = (isset($this->mail_object->settings->custom_sending_email) && stripos($this->mail_object->settings->custom_sending_email, "@")) ? $this->mail_object->settings->custom_sending_email : $user->email; $sending_user = (isset($this->mail_object->settings->email_from_name) && strlen($this->mail_object->settings->email_from_name) > 2) ? $this->mail_object->settings->email_from_name : $user->name(); - $this->mailable - ->from($sending_email, $sending_user); + $this->mailable + ->from($sending_email, $sending_user); } /** @@ -456,25 +442,19 @@ class MailEntity implements ShouldQueue $token = $this->refreshOfficeToken($user); - if($token) - { + if ($token) { $user->oauth_user_token = $token; $user->save(); - - } - else { - + } else { $this->mail_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); - } $this->mailable ->from($user->email, $user->name()) - ->withSymfonyMessage(function ($message) use($token) { - $message->getHeaders()->addTextHeader('gmailtoken', $token); + ->withSymfonyMessage(function ($message) use ($token) { + $message->getHeaders()->addTextHeader('gmailtoken', $token); }); - } /** @@ -483,7 +463,6 @@ class MailEntity implements ShouldQueue */ private function setGmailMailer() { - $user = $this->resolveSendingUser(); $this->checkValidSendingUser($user); @@ -492,17 +471,14 @@ class MailEntity implements ShouldQueue $google = (new Google())->init(); - try{ - + try { if ($google->getClient()->isAccessTokenExpired()) { $google->refreshToken($user); $user = $user->fresh(); } $google->getClient()->setAccessToken(json_encode($user->oauth_user_token)); - - } - catch(\Exception $e) { + } catch(\Exception $e) { // $this->logMailError('Gmail Token Invalid', $this->company->clients()->first()); $this->mail_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -512,7 +488,7 @@ class MailEntity implements ShouldQueue * If the user doesn't have a valid token, notify them */ - if(!$user->oauth_user_token) { + if (!$user->oauth_user_token) { $this->company->account->gmailCredentialNotification(); $this->mail_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -526,7 +502,7 @@ class MailEntity implements ShouldQueue $token = $user->oauth_user_token->access_token; - if(!$token) { + if (!$token) { $this->company->account->gmailCredentialNotification(); $this->mail_object->settings->email_sending_method = 'default'; return $this->setMailDriver(); @@ -534,15 +510,14 @@ class MailEntity implements ShouldQueue $this->mailable ->from($user->email, $user->name()) - ->withSymfonyMessage(function ($message) use($token) { - $message->getHeaders()->addTextHeader('gmailtoken', $token); + ->withSymfonyMessage(function ($message) use ($token) { + $message->getHeaders()->addTextHeader('gmailtoken', $token); }); - } /** * Attempts to refresh the Microsoft refreshToken - * + * * @param App\Models\User * @return string | boool */ @@ -550,10 +525,9 @@ class MailEntity implements ShouldQueue { $expiry = $user->oauth_user_token_expiry ?: now()->subDay(); - if($expiry->lt(now())) - { - $guzzle = new \GuzzleHttp\Client(); - $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'; + if ($expiry->lt(now())) { + $guzzle = new \GuzzleHttp\Client(); + $url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'; $token = json_decode($guzzle->post($url, [ 'form_params' => [ @@ -565,8 +539,7 @@ class MailEntity implements ShouldQueue ], ])->getBody()->getContents()); - if($token){ - + if ($token) { $user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token; $user->oauth_user_token = $token->access_token; $user->oauth_user_token_expiry = now()->addSeconds($token->expires_in); @@ -579,7 +552,6 @@ class MailEntity implements ShouldQueue } return $user->oauth_user_token; - } /** diff --git a/app/Services/Email/MailMailable.php b/app/Services/Email/MailMailable.php index 4d0dd5008e66..31fb9e3b238c 100644 --- a/app/Services/Email/MailMailable.php +++ b/app/Services/Email/MailMailable.php @@ -11,8 +11,6 @@ namespace App\Services\Email; -use App\Services\Email\MailObject; - use Illuminate\Mail\Attachment; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; @@ -21,13 +19,14 @@ use Illuminate\Mail\Mailables\Headers; class MailMailable extends Mailable { - /** * Create a new message instance. * * @return void */ - public function __construct(public MailObject $mail_object){} + public function __construct(public MailObject $mail_object) + { + } /** * Get the message envelope. @@ -57,7 +56,7 @@ class MailMailable extends Mailable view: $this->mail_object->html_template, text: $this->mail_object->text_template, with: [ - 'text_body' => str_replace("
","\n", strip_tags($this->mail_object->body,"
")), //@todo this is a bit hacky here. + 'text_body' => str_replace("
", "\n", strip_tags($this->mail_object->body, "
")), //@todo this is a bit hacky here. 'body' => $this->mail_object->body, 'settings' => $this->mail_object->settings, 'whitelabel' => $this->mail_object->whitelabel, @@ -76,16 +75,13 @@ class MailMailable extends Mailable */ public function attachments() { - $attachments = []; - foreach($this->mail_object->attachments as $file) - { + foreach ($this->mail_object->attachments as $file) { $attachments[] = Attachment::fromData(fn () => base64_decode($file['file']), $file['name']); } return $attachments; - } /** @@ -95,13 +91,10 @@ class MailMailable extends Mailable */ public function headers() { - return new Headers( messageId: null, references: [], text: $this->mail_object->headers, ); - } - } diff --git a/app/Services/Email/MailObject.php b/app/Services/Email/MailObject.php index d5788ce00c42..d42a71a12ccb 100644 --- a/app/Services/Email/MailObject.php +++ b/app/Services/Email/MailObject.php @@ -19,73 +19,71 @@ use Illuminate\Mail\Mailables\Address; */ class MailObject { + public ?string $db = null; - public ?string $db = null; + public array $to = []; - public array $to = []; + public ?Address $from = null; - public ?Address $from = null; + public array $reply_to = []; - public array $reply_to = []; + public array $cc = []; - public array $cc = []; + public array $bcc = []; - public array $bcc = []; + public ?string $subject = null; - public ?string $subject = null; + public ?string $body = null; - public ?string $body = null; + public array $attachments = []; - public array $attachments = []; + public array $attachment_links = []; - public array $attachment_links = []; + public string $company_key; - public string $company_key; + public ?object $settings = null; - public ?object $settings = null; + public bool $whitelabel = false; - public bool $whitelabel = false; + public ?string $logo = null; - public ?string $logo = null; + public ?string $signature = null; - public ?string $signature = null; + public ?string $greeting = null; - public ?string $greeting = null; + public ?int $client_id = null; - public ?int $client_id = null; + public ?int $vendor_id = null; - public ?int $vendor_id = null; + public ?int $user_id = null; - public ?int $user_id = null; + public ?int $client_contact_id = null; - public ?int $client_contact_id = null; + public ?int $vendor_contact_id = null; - public ?int $vendor_contact_id = null; + public ?string $email_template = null; //this defines the template in short notation WITH the email_template prefix - public ?string $email_template = null; //this defines the template in short notation WITH the email_template prefix + public ?string $html_template = null; - public ?string $html_template = null; + public ?string $text_template = 'email.template.text'; - public ?string $text_template = 'email.template.text'; + public array $headers = []; - public array $headers = []; + public ?string $invitation_key = null; + + public ?int $entity_id = null; - public ?string $invitation_key = null; - - public ?int $entity_id = null; + public ?string $entity_class = null; - public ?string $entity_class = null; + public ?string $entity_string = null; - public ?string $entity_string = null; + public array $variables = []; + + public ?string $template = null; - public array $variables = []; - - public ?string $template = null; + public ?string $template_data = null; - public ?string $template_data = null; + public bool $override = false; - public bool $override = false; - - public ?Company $company = null; - -} \ No newline at end of file + public ?Company $company = null; +} diff --git a/app/Services/Invoice/AddGatewayFee.php b/app/Services/Invoice/AddGatewayFee.php index 437791edbe86..341da8789444 100644 --- a/app/Services/Invoice/AddGatewayFee.php +++ b/app/Services/Invoice/AddGatewayFee.php @@ -12,10 +12,8 @@ namespace App\Services\Invoice; use App\DataMapper\InvoiceItem; -use App\Models\Client; use App\Models\CompanyGateway; use App\Models\Invoice; -use App\Models\Payment; use App\Services\AbstractService; use App\Utils\Ninja; use Illuminate\Support\Facades\App; diff --git a/app/Services/Invoice/ApplyNumber.php b/app/Services/Invoice/ApplyNumber.php index 7bb10ec8e887..ee4368f557b3 100644 --- a/app/Services/Invoice/ApplyNumber.php +++ b/app/Services/Invoice/ApplyNumber.php @@ -36,7 +36,6 @@ class ApplyNumber extends AbstractService public function run() { - if ($this->invoice->number != '') { return $this->invoice; } @@ -60,32 +59,24 @@ class ApplyNumber extends AbstractService private function trySaving() { - $x=1; - do{ - - try{ - + do { + try { $this->invoice->number = $this->getNextInvoiceNumber($this->client, $this->invoice, $this->invoice->recurring_id); $this->invoice->saveQuietly(); $this->completed = false; - - } - catch(QueryException $e){ - + } catch(QueryException $e) { $x++; - if($x>50) + if ($x>50) { $this->completed = false; + } } - - } - while($this->completed); + } while ($this->completed); return $this; } - } diff --git a/app/Services/Invoice/ApplyPayment.php b/app/Services/Invoice/ApplyPayment.php index 84e87b0a2586..a18746f0fdfd 100644 --- a/app/Services/Invoice/ApplyPayment.php +++ b/app/Services/Invoice/ApplyPayment.php @@ -41,7 +41,6 @@ class ApplyPayment extends AbstractService if ($this->invoice->hasPartial()) { if ($this->invoice->partial == $this->payment_amount) { - //is partial and amount is exactly the partial amount $amount_paid = $this->payment_amount * -1; diff --git a/app/Services/Invoice/ApplyPaymentAmount.php b/app/Services/Invoice/ApplyPaymentAmount.php index ef7524e807d8..690d54f86146 100644 --- a/app/Services/Invoice/ApplyPaymentAmount.php +++ b/app/Services/Invoice/ApplyPaymentAmount.php @@ -26,7 +26,9 @@ class ApplyPaymentAmount extends AbstractService { use GeneratesCounter; - public function __construct(private Invoice $invoice, private float $amount, private ?string $reference){} + public function __construct(private Invoice $invoice, private float $amount, private ?string $reference) + { + } public function run() { diff --git a/app/Services/Invoice/AutoBillInvoice.php b/app/Services/Invoice/AutoBillInvoice.php index 5a0624b1d73c..e0070d981dee 100644 --- a/app/Services/Invoice/AutoBillInvoice.php +++ b/app/Services/Invoice/AutoBillInvoice.php @@ -23,7 +23,6 @@ use App\Models\PaymentType; use App\Services\AbstractService; use App\Utils\Ninja; use Illuminate\Support\Str; -use PDO; class AutoBillInvoice extends AbstractService { @@ -73,8 +72,9 @@ class AutoBillInvoice extends AbstractService } //If this returns true, it means a partial invoice amount was paid as a credit and there is no further balance payable - if($this->is_partial_amount && $this->invoice->partial == 0) + if ($this->is_partial_amount && $this->invoice->partial == 0) { return; + } $amount = 0; @@ -251,7 +251,6 @@ class AutoBillInvoice extends AbstractService foreach ($available_credits as $key => $credit) { if ($this->is_partial_amount) { - //more credit than needed if ($credit->balance > $this->invoice->partial) { $this->used_credit[$key]['credit_id'] = $credit->id; @@ -266,10 +265,8 @@ class AutoBillInvoice extends AbstractService $this->invoice->partial -= $credit->balance; $this->invoice->balance -= $credit->balance; $this->invoice->paid_to_date += $credit->balance; - } } else { - //more credit than needed if ($credit->balance > $this->invoice->balance) { $this->used_credit[$key]['credit_id'] = $credit->id; @@ -283,7 +280,6 @@ class AutoBillInvoice extends AbstractService $this->used_credit[$key]['amount'] = $credit->balance; $this->invoice->balance -= $credit->balance; $this->invoice->paid_to_date += $credit->balance; - } } } @@ -322,7 +318,6 @@ class AutoBillInvoice extends AbstractService */ public function getGateway($amount) { - //get all client gateway tokens and set the is_default one to the first record $gateway_tokens = $this->client ->gateway_tokens() @@ -363,8 +358,7 @@ class AutoBillInvoice extends AbstractService */ private function addFeeToInvoice(float $fee) { - - //todo if we increase the invoice balance here, we will also need to adjust UP the client balance and ledger? + //todo if we increase the invoice balance here, we will also need to adjust UP the client balance and ledger? $starting_amount = $this->invoice->amount; $item = new InvoiceItem; diff --git a/app/Services/Invoice/GetInvoicePdf.php b/app/Services/Invoice/GetInvoicePdf.php index b4ad06f81f4a..518d59c5f608 100644 --- a/app/Services/Invoice/GetInvoicePdf.php +++ b/app/Services/Invoice/GetInvoicePdf.php @@ -15,7 +15,6 @@ use App\Jobs\Entity\CreateEntityPdf; use App\Models\ClientContact; use App\Models\Invoice; use App\Services\AbstractService; -use App\Utils\TempFile; use Illuminate\Support\Facades\Storage; class GetInvoicePdf extends AbstractService diff --git a/app/Services/Invoice/HandleRestore.php b/app/Services/Invoice/HandleRestore.php index a61f42dccfb2..b2878a38b56b 100644 --- a/app/Services/Invoice/HandleRestore.php +++ b/app/Services/Invoice/HandleRestore.php @@ -46,10 +46,9 @@ class HandleRestore extends AbstractService //cannot restore an invoice with a deleted payment foreach ($this->invoice->payments as $payment) { - - if(($this->invoice->paid_to_date == 0) && $payment->is_deleted) + if (($this->invoice->paid_to_date == 0) && $payment->is_deleted) { return $this->invoice; - + } } //adjust ledger balance @@ -57,7 +56,7 @@ class HandleRestore extends AbstractService $this->invoice->client ->service() - ->updateBalanceAndPaidToDate($this->invoice->balance,$this->invoice->paid_to_date) + ->updateBalanceAndPaidToDate($this->invoice->balance, $this->invoice->paid_to_date) ->save(); $this->windBackInvoiceNumber(); @@ -81,14 +80,12 @@ class HandleRestore extends AbstractService private function restorePaymentables() { $this->invoice->payments->each(function ($payment) { - Paymentable::query() ->withTrashed() ->where('payment_id', $payment->id) ->where('paymentable_type', '=', 'invoices') ->where('paymentable_id', $this->invoice->id) ->update(['deleted_at' => null]); - }); return $this; @@ -112,7 +109,7 @@ class HandleRestore extends AbstractService $this->total_payments = $this->invoice->payments->sum('amount') - $this->invoice->payments->sum('refunded'); return $this; - } + } private function adjustPayments() { @@ -120,27 +117,27 @@ class HandleRestore extends AbstractService if ($this->adjustment_amount == $this->total_payments) { $this->invoice->payments()->update(['payments.deleted_at' => null, 'payments.is_deleted' => false]); - } + } - //adjust payments down by the amount applied to the invoice payment. + //adjust payments down by the amount applied to the invoice payment. - $this->invoice->payments->fresh()->each(function ($payment) { - $payment_adjustment = $payment->paymentables - ->where('paymentable_type', '=', 'invoices') - ->where('paymentable_id', $this->invoice->id) - ->sum(DB::raw('amount')); + $this->invoice->payments->fresh()->each(function ($payment) { + $payment_adjustment = $payment->paymentables + ->where('paymentable_type', '=', 'invoices') + ->where('paymentable_id', $this->invoice->id) + ->sum(DB::raw('amount')); - $payment_adjustment -= $payment->paymentables - ->where('paymentable_type', '=', 'invoices') - ->where('paymentable_id', $this->invoice->id) - ->sum(DB::raw('refunded')); + $payment_adjustment -= $payment->paymentables + ->where('paymentable_type', '=', 'invoices') + ->where('paymentable_id', $this->invoice->id) + ->sum(DB::raw('refunded')); - $payment->amount += $payment_adjustment; - $payment->applied += $payment_adjustment; - $payment->is_deleted = false; - $payment->restore(); - $payment->saveQuietly(); - }); + $payment->amount += $payment_adjustment; + $payment->applied += $payment_adjustment; + $payment->is_deleted = false; + $payment->restore(); + $payment->saveQuietly(); + }); return $this; } diff --git a/app/Services/Invoice/HandleReversal.php b/app/Services/Invoice/HandleReversal.php index dafce85bc5d2..8000ecf4caee 100644 --- a/app/Services/Invoice/HandleReversal.php +++ b/app/Services/Invoice/HandleReversal.php @@ -59,7 +59,6 @@ class HandleReversal extends AbstractService ->get(); $paymentables->each(function ($paymentable) use ($total_paid) { - //new concept - when reversing, we unwind the payments $payment = Payment::withTrashed()->find($paymentable->payment_id); diff --git a/app/Services/Invoice/InvoiceService.php b/app/Services/Invoice/InvoiceService.php index fa1149d281eb..34919ad37ad8 100644 --- a/app/Services/Invoice/InvoiceService.php +++ b/app/Services/Invoice/InvoiceService.php @@ -14,18 +14,12 @@ namespace App\Services\Invoice; use App\Events\Invoice\InvoiceWasArchived; use App\Jobs\Entity\CreateEntityPdf; use App\Jobs\Inventory\AdjustProductInventory; -use App\Jobs\Invoice\InvoiceWorkflowSettings; -use App\Jobs\Util\UnlinkFile; use App\Libraries\Currency\Conversion\CurrencyApi; use App\Models\CompanyGateway; use App\Models\Expense; use App\Models\Invoice; use App\Models\Payment; use App\Models\Task; -use App\Repositories\BaseRepository; -use App\Services\Client\ClientService; -use App\Services\Invoice\ApplyPaymentAmount; -use App\Services\Invoice\UpdateReminder; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use Illuminate\Support\Carbon; @@ -35,7 +29,9 @@ class InvoiceService { use MakesHash; - public function __construct(public Invoice $invoice){} + public function __construct(public Invoice $invoice) + { + } /** * Marks as invoice as paid @@ -266,10 +262,11 @@ class InvoiceService } //12-10-2022 - if($this->invoice->partial > 0 && !$this->invoice->partial_due_date) + if ($this->invoice->partial > 0 && !$this->invoice->partial_due_date) { $this->invoice->partial_due_date = Carbon::parse($this->invoice->date)->addDays($this->invoice->client->getSetting('payment_terms')); - else + } else { $this->invoice->due_date = Carbon::parse($this->invoice->date)->addDays($this->invoice->client->getSetting('payment_terms')); + } return $this; } @@ -294,8 +291,7 @@ class InvoiceService $this->setStatus(Invoice::STATUS_PAID); } elseif ($this->invoice->balance > 0 && $this->invoice->balance < $this->invoice->amount) { $this->setStatus(Invoice::STATUS_PARTIAL); - } - elseif ($this->invoice->balance < 0 || $this->invoice->balance > 0) { + } elseif ($this->invoice->balance < 0 || $this->invoice->balance > 0) { $this->invoice->status_id = Invoice::STATUS_SENT; } @@ -312,8 +308,7 @@ class InvoiceService $this->invoice->status_id = Invoice::STATUS_PAID; } elseif ($this->invoice->balance > 0 && $this->invoice->balance < $this->invoice->amount) { $this->invoice->status_id = Invoice::STATUS_PARTIAL; - } - elseif ($this->invoice->balance < 0 || $this->invoice->balance > 0) { + } elseif ($this->invoice->balance < 0 || $this->invoice->balance > 0) { $this->invoice->status_id = Invoice::STATUS_SENT; } diff --git a/app/Services/Invoice/MarkInvoiceDeleted.php b/app/Services/Invoice/MarkInvoiceDeleted.php index 145af4ea543b..d3ed85a2808e 100644 --- a/app/Services/Invoice/MarkInvoiceDeleted.php +++ b/app/Services/Invoice/MarkInvoiceDeleted.php @@ -12,9 +12,7 @@ namespace App\Services\Invoice; use App\Jobs\Inventory\AdjustProductInventory; -use App\Jobs\Ninja\TransactionLog; use App\Models\Invoice; -use App\Models\TransactionEvent; use App\Services\AbstractService; use App\Utils\Traits\GeneratesCounter; use Illuminate\Support\Facades\DB; @@ -66,7 +64,6 @@ class MarkInvoiceDeleted extends AbstractService private function adjustPaidToDateAndBalance() { - // 06-09-2022 $this->invoice ->client @@ -82,27 +79,28 @@ class MarkInvoiceDeleted extends AbstractService { //if total payments = adjustment amount - that means we need to delete the payments as well. - if ($this->adjustment_amount == $this->total_payments) + if ($this->adjustment_amount == $this->total_payments) { $this->invoice->payments()->update(['payments.deleted_at' => now(), 'payments.is_deleted' => true]); + } - //adjust payments down by the amount applied to the invoice payment. + //adjust payments down by the amount applied to the invoice payment. - $this->invoice->payments->each(function ($payment) { - $payment_adjustment = $payment->paymentables - ->where('paymentable_type', '=', 'invoices') - ->where('paymentable_id', $this->invoice->id) - ->sum(DB::raw('amount')); + $this->invoice->payments->each(function ($payment) { + $payment_adjustment = $payment->paymentables + ->where('paymentable_type', '=', 'invoices') + ->where('paymentable_id', $this->invoice->id) + ->sum(DB::raw('amount')); - $payment_adjustment -= $payment->paymentables - ->where('paymentable_type', '=', 'invoices') - ->where('paymentable_id', $this->invoice->id) - ->sum(DB::raw('refunded')); + $payment_adjustment -= $payment->paymentables + ->where('paymentable_type', '=', 'invoices') + ->where('paymentable_id', $this->invoice->id) + ->sum(DB::raw('refunded')); - $payment->amount -= $payment_adjustment; - $payment->applied -= $payment_adjustment; - $payment->save(); - }); + $payment->amount -= $payment_adjustment; + $payment->applied -= $payment_adjustment; + $payment->save(); + }); return $this; diff --git a/app/Services/Invoice/MarkPaid.php b/app/Services/Invoice/MarkPaid.php index b4f69a6f3e30..a056da4b6038 100644 --- a/app/Services/Invoice/MarkPaid.php +++ b/app/Services/Invoice/MarkPaid.php @@ -28,11 +28,12 @@ class MarkPaid extends AbstractService private $payable_balance; - public function __construct(private Invoice $invoice, private ?string $reference){} + public function __construct(private Invoice $invoice, private ?string $reference) + { + } public function run() { - /*Don't double pay*/ if ($this->invoice->status_id == Invoice::STATUS_PAID) { return $this->invoice; @@ -43,11 +44,9 @@ class MarkPaid extends AbstractService } \DB::connection(config('database.default'))->transaction(function () { - $this->invoice = Invoice::withTrashed()->where('id', $this->invoice->id)->lockForUpdate()->first(); - if($this->invoice) - { + if ($this->invoice) { $this->payable_balance = $this->invoice->balance; $this->invoice @@ -58,7 +57,6 @@ class MarkPaid extends AbstractService ->setStatus(Invoice::STATUS_PAID) ->save(); } - }, 1); /* Create Payment */ @@ -91,8 +89,9 @@ class MarkPaid extends AbstractService 'amount' => $this->payable_balance, ]); - if($payment->company->getSetting('send_email_on_mark_paid')) + if ($payment->company->getSetting('send_email_on_mark_paid')) { $payment->service()->sendEmail(); + } $this->setExchangeRate($payment); diff --git a/app/Services/Invoice/MarkSent.php b/app/Services/Invoice/MarkSent.php index f9e3519f3b00..557fb37ec55e 100644 --- a/app/Services/Invoice/MarkSent.php +++ b/app/Services/Invoice/MarkSent.php @@ -12,7 +12,6 @@ namespace App\Services\Invoice; use App\Events\Invoice\InvoiceWasUpdated; -use App\Jobs\Util\WebhookHandler; use App\Models\Client; use App\Models\Invoice; use App\Models\Webhook; @@ -34,7 +33,6 @@ class MarkSent extends AbstractService public function run($fire_webhook = false) { - /* Return immediately if status is not draft or invoice has been deleted */ if ($this->invoice && ($this->invoice->fresh()->status_id != Invoice::STATUS_DRAFT || $this->invoice->is_deleted)) { return $this->invoice; @@ -70,8 +68,9 @@ class MarkSent extends AbstractService event(new InvoiceWasUpdated($this->invoice, $this->invoice->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); - if($fire_webhook) + if ($fire_webhook) { event('eloquent.updated: App\Models\Invoice', $this->invoice); + } $this->invoice->sendEvent(Webhook::EVENT_SENT_INVOICE, "client"); diff --git a/app/Services/Invoice/TriggeredActions.php b/app/Services/Invoice/TriggeredActions.php index 82f5b580af95..d607de6d140b 100644 --- a/app/Services/Invoice/TriggeredActions.php +++ b/app/Services/Invoice/TriggeredActions.php @@ -67,7 +67,7 @@ class TriggeredActions extends AbstractService $this->updated = false; } - if($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') { + if ($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') { $company = $this->invoice->company; $settings = $company->settings; $settings->invoice_footer = $this->invoice->footer; @@ -75,7 +75,7 @@ class TriggeredActions extends AbstractService $company->save(); } - if($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') { + if ($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') { $company = $this->invoice->company; $settings = $company->settings; $settings->invoice_terms = $this->invoice->terms; @@ -83,8 +83,9 @@ class TriggeredActions extends AbstractService $company->save(); } - if($this->updated) + if ($this->updated) { event('eloquent.updated: App\Models\Invoice', $this->invoice); + } return $this->invoice; diff --git a/app/Services/Invoice/UpdateReminder.php b/app/Services/Invoice/UpdateReminder.php index c86021242237..6109eb54c400 100644 --- a/app/Services/Invoice/UpdateReminder.php +++ b/app/Services/Invoice/UpdateReminder.php @@ -182,7 +182,7 @@ class UpdateReminder extends AbstractService switch ($endless_reminder_frequency_id) { case RecurringInvoice::FREQUENCY_DAILY: return Carbon::parse($date)->addDay()->startOfDay(); - case RecurringInvoice::FREQUENCY_WEEKLY: + case RecurringInvoice::FREQUENCY_WEEKLY: return Carbon::parse($date)->addWeek()->startOfDay(); case RecurringInvoice::FREQUENCY_TWO_WEEKS: return Carbon::parse($date)->addWeeks(2)->startOfDay(); diff --git a/app/Services/Ledger/LedgerService.php b/app/Services/Ledger/LedgerService.php index 219aa04bd96d..9d9935fc5e02 100644 --- a/app/Services/Ledger/LedgerService.php +++ b/app/Services/Ledger/LedgerService.php @@ -14,7 +14,6 @@ namespace App\Services\Ledger; use App\Factory\CompanyLedgerFactory; use App\Jobs\Ledger\ClientLedgerBalanceUpdate; use App\Models\Activity; -use App\Models\CompanyLedger; class LedgerService { @@ -36,7 +35,7 @@ class LedgerService $this->entity->company_ledger()->save($company_ledger); - ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30,300))); + ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30, 300))); return $this; } @@ -52,7 +51,7 @@ class LedgerService $this->entity->company_ledger()->save($company_ledger); - ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30,300))); + ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30, 300))); return $this; } @@ -68,7 +67,7 @@ class LedgerService $this->entity->company_ledger()->save($company_ledger); - ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30,300))); + ClientLedgerBalanceUpdate::dispatch($this->entity->company, $this->entity->client)->delay(now()->addSeconds(rand(30, 300))); return $this; } diff --git a/app/Services/Payment/DeletePayment.php b/app/Services/Payment/DeletePayment.php index bd41bcd8af0e..b327287fcb60 100644 --- a/app/Services/Payment/DeletePayment.php +++ b/app/Services/Payment/DeletePayment.php @@ -11,12 +11,9 @@ namespace App\Services\Payment; -use App\Jobs\Ninja\TransactionLog; use App\Models\Credit; use App\Models\Invoice; use App\Models\Payment; -use App\Models\TransactionEvent; -use App\Repositories\ActivityRepository; use Illuminate\Contracts\Container\BindingResolutionException; class DeletePayment @@ -24,37 +21,33 @@ class DeletePayment private float $_paid_to_date_deleted = 0; /** - * @param mixed $payment - * @return void + * @param mixed $payment + * @return void */ - public function __construct(public Payment $payment, private bool $update_client_paid_to_date) {} + public function __construct(public Payment $payment, private bool $update_client_paid_to_date) + { + } /** - * @return mixed - * @throws BindingResolutionException + * @return mixed + * @throws BindingResolutionException */ public function run() { - \DB::connection(config('database.default'))->transaction(function () { - $this->payment = Payment::withTrashed()->where('id', $this->payment->id)->lockForUpdate()->first(); if ($this->payment && !$this->payment->is_deleted) { - $this->setStatus(Payment::STATUS_CANCELLED) //sets status of payment ->updateCreditables() //return the credits first ->adjustInvoices() ->deletePaymentables() ->cleanupPayment() ->save(); - } - }, 2); return $this->payment; - } /** @return $this */ @@ -111,19 +104,16 @@ class DeletePayment $paymentable_invoice->service()->setStatus(Invoice::STATUS_PARTIAL)->save(); } } else { - $paymentable_invoice->restore(); $paymentable_invoice->service() ->updatePaidToDate($net_deletable * -1) ->save(); } - }); } //sometimes the payment is NOT created properly, this catches the payment and prevents the paid to date reducing inappropriately. - if($this->update_client_paid_to_date) - { + if ($this->update_client_paid_to_date) { $this->payment ->client ->service() @@ -138,7 +128,7 @@ class DeletePayment private function updateCreditables() { if ($this->payment->credits()->exists()) { - $this->payment->credits()->where('is_deleted',0)->each(function ($paymentable_credit) { + $this->payment->credits()->where('is_deleted', 0)->each(function ($paymentable_credit) { $multiplier = 1; if ($paymentable_credit->pivot->amount < 0) { @@ -165,8 +155,8 @@ class DeletePayment } /** - * @param mixed $status - * @return $this + * @param mixed $status + * @return $this */ private function setStatus($status) { diff --git a/app/Services/Payment/PaymentService.php b/app/Services/Payment/PaymentService.php index f521ff52a973..9dc72e088258 100644 --- a/app/Services/Payment/PaymentService.php +++ b/app/Services/Payment/PaymentService.php @@ -142,31 +142,30 @@ class PaymentService public function applyCreditsToInvoice($invoice) { + $amount = $invoice->amount; - $amount = $invoice->amount; + $credits = $invoice->client + ->service() + ->getCredits(); - $credits = $invoice->client - ->service() - ->getCredits(); + foreach ($credits as $credit) { + //starting invoice balance + $invoice_balance = $invoice->balance; - foreach ($credits as $credit) { - //starting invoice balance - $invoice_balance = $invoice->balance; + //credit payment applied + $credit->service()->applyPayment($invoice, $amount, $this->payment); - //credit payment applied - $credit->service()->applyPayment($invoice, $amount, $this->payment); + //amount paid from invoice calculated + $remaining_balance = ($invoice_balance - $invoice->fresh()->balance); - //amount paid from invoice calculated - $remaining_balance = ($invoice_balance - $invoice->fresh()->balance); + //reduce the amount to be paid on the invoice from the NEXT credit + $amount -= $remaining_balance; - //reduce the amount to be paid on the invoice from the NEXT credit - $amount -= $remaining_balance; - - //break if the invoice is no longer PAYABLE OR there is no more amount to be applied - if (! $invoice->isPayable() || (int) $amount == 0) { - break; - } + //break if the invoice is no longer PAYABLE OR there is no more amount to be applied + if (! $invoice->isPayable() || (int) $amount == 0) { + break; } + } return $this; diff --git a/app/Services/Payment/RefundPayment.php b/app/Services/Payment/RefundPayment.php index c288736eecc3..99747a392a2b 100644 --- a/app/Services/Payment/RefundPayment.php +++ b/app/Services/Payment/RefundPayment.php @@ -12,17 +12,11 @@ namespace App\Services\Payment; use App\Exceptions\PaymentRefundFailed; -use App\Factory\CreditFactory; -use App\Factory\InvoiceItemFactory; -use App\Jobs\Ninja\TransactionLog; use App\Jobs\Payment\EmailRefundPayment; -use App\Jobs\Util\SystemLogger; use App\Models\Activity; use App\Models\Credit; use App\Models\Invoice; use App\Models\Payment; -use App\Models\SystemLog; -use App\Models\TransactionEvent; use App\Repositories\ActivityRepository; use App\Utils\Ninja; use stdClass; @@ -200,7 +194,6 @@ class RefundPayment if ($this->payment->credits()->exists()) { //Adjust credits first!!! foreach ($this->payment->credits as $paymentable_credit) { - $available_credit = $paymentable_credit->pivot->amount - $paymentable_credit->pivot->refunded; if ($available_credit > $this->total_refund) { @@ -244,7 +237,6 @@ 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) { $invoice = Invoice::withTrashed()->find($refunded_invoice['invoice_id']); @@ -291,7 +283,6 @@ class RefundPayment } $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. @@ -302,7 +293,6 @@ class RefundPayment } $client->service()->updatePaidToDate(-1 * $this->total_refund)->save(); - } return $this; @@ -319,5 +309,4 @@ class RefundPayment return $this->payment; } - } diff --git a/app/Services/Payment/SendEmail.php b/app/Services/Payment/SendEmail.php index 2846b4ef5736..770b54de7248 100644 --- a/app/Services/Payment/SendEmail.php +++ b/app/Services/Payment/SendEmail.php @@ -32,7 +32,7 @@ class SendEmail */ public function run() { - $this->payment->load('company', 'client.contacts','invoices'); + $this->payment->load('company', 'client.contacts', 'invoices'); $contact = $this->payment->client->contacts()->first(); @@ -40,19 +40,12 @@ class SendEmail // EmailPayment::dispatch($this->payment, $this->payment->company, $contact)->delay(now()->addSeconds(2)); - $this->payment->invoices->sortByDesc('id')->first(function ($invoice){ - + $this->payment->invoices->sortByDesc('id')->first(function ($invoice) { $invoice->invitations->each(function ($invitation) { - - if(!$invitation->contact->trashed() && $invitation->contact->email) { - + if (!$invitation->contact->trashed() && $invitation->contact->email) { EmailPayment::dispatch($this->payment, $this->payment->company, $invitation->contact)->delay(now()->addSeconds(2)); - } - }); - }); - } } diff --git a/app/Services/Payment/UpdateInvoicePayment.php b/app/Services/Payment/UpdateInvoicePayment.php index 5035b4cb2a71..9ffdbe5b02d2 100644 --- a/app/Services/Payment/UpdateInvoicePayment.php +++ b/app/Services/Payment/UpdateInvoicePayment.php @@ -12,13 +12,9 @@ namespace App\Services\Payment; use App\Events\Invoice\InvoiceWasUpdated; -use App\Jobs\Invoice\InvoiceWorkflowSettings; -use App\Jobs\Ninja\TransactionLog; -use App\Models\Client; use App\Models\Invoice; use App\Models\Payment; use App\Models\PaymentHash; -use App\Models\TransactionEvent; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; @@ -44,17 +40,18 @@ class UpdateInvoicePayment $client = $this->payment->client; - if($client->trashed()) + if ($client->trashed()) { $client->restore(); + } collect($paid_invoices)->each(function ($paid_invoice) use ($invoices, $client) { - $invoice = $invoices->first(function ($inv) use ($paid_invoice) { return $paid_invoice->invoice_id == $inv->hashed_id; }); - if($invoice->trashed()) + if ($invoice->trashed()) { $invoice->restore(); + } if ($invoice->id == $this->payment_hash->fee_invoice_id) { $paid_amount = $paid_invoice->amount + $this->payment_hash->fee_total; @@ -65,8 +62,9 @@ class UpdateInvoicePayment $client->service()->updatePaidToDate($paid_amount); //always use the payment->amount /* Need to determine here is we have an OVER payment - if YES only apply the max invoice amount */ - if($paid_amount > $invoice->partial && $paid_amount > $invoice->balance) + if ($paid_amount > $invoice->partial && $paid_amount > $invoice->balance) { $paid_amount = $invoice->balance; + } $client->service()->updateBalance($paid_amount*-1); //only ever use the amount applied to the invoice @@ -76,18 +74,17 @@ class UpdateInvoicePayment $invoice->paid_to_date += $paid_amount; $invoice->save(); - $invoice = $invoice->service() + $invoice = $invoice->service() ->clearPartial() ->updateStatus() ->touchPdf() ->workFlow() ->save(); - if($invoice->is_proforma) - { - - if(strlen($invoice->number) > 1 && str_starts_with($invoice->number,"####")) - $invoice->number = ''; + if ($invoice->is_proforma) { + if (strlen($invoice->number) > 1 && str_starts_with($invoice->number, "####")) { + $invoice->number = ''; + } $invoice->is_proforma = false; @@ -112,7 +109,6 @@ class UpdateInvoicePayment $pivot_invoice->pivot->save(); $this->payment->applied += $paid_amount; - }); /* Remove the event updater from within the loop to prevent race conditions */ @@ -120,9 +116,7 @@ class UpdateInvoicePayment $this->payment->saveQuietly(); $invoices->each(function ($invoice) { - event(new InvoiceWasUpdated($invoice, $invoice->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); - }); return $this->payment->fresh(); diff --git a/app/Services/PdfMaker/Design.php b/app/Services/PdfMaker/Design.php index 1b275c2dff90..095146bba08f 100644 --- a/app/Services/PdfMaker/Design.php +++ b/app/Services/PdfMaker/Design.php @@ -13,9 +13,7 @@ namespace App\Services\PdfMaker; use App\Models\Credit; -use App\Models\GatewayType; use App\Models\Invoice; -use App\Models\Payment; use App\Models\Quote; use App\Services\PdfMaker\Designs\Utilities\BaseDesign; use App\Services\PdfMaker\Designs\Utilities\DesignHelpers; @@ -85,7 +83,6 @@ class Design extends BaseDesign Str::endsWith('.html', $design) ? $this->design = $design : $this->design = "{$design}.html"; $this->options = $options; - } public function html(): ?string @@ -184,15 +181,17 @@ class Design extends BaseDesign public function swissQrCodeElement() :array { - if($this->type == self::DELIVERY_NOTE) + if ($this->type == self::DELIVERY_NOTE) { return []; + } $elements = []; - if(strlen($this->company->getSetting('qr_iban')) > 5 && strlen($this->company->getSetting('besr_id')) > 1) + if (strlen($this->company->getSetting('qr_iban')) > 5 && strlen($this->company->getSetting('besr_id')) > 1) { $elements[] = ['element' => 'qr_code', 'content' => '$swiss_qr', 'show_empty' => false, 'properties' => ['data-ref' => 'swiss-qr-code']]; + } - return $elements; + return $elements; } public function companyDetails(): array @@ -225,8 +224,9 @@ class Design extends BaseDesign { $elements = []; - if(!$this->vendor) + if (!$this->vendor) { return $elements; + } $variables = $this->context['pdf_variables']['vendor_details']; @@ -241,8 +241,9 @@ class Design extends BaseDesign { $elements = []; - if(!$this->client) + if (!$this->client) { return $elements; + } if ($this->type == self::DELIVERY_NOTE) { $elements = [ @@ -276,10 +277,7 @@ class Design extends BaseDesign public function entityDetails(): array { - - if ($this->type === 'statement') { - // $s_date = $this->translateDate(now(), $this->client->date_format(), $this->client->locale()); $s_date = $this->translateDate($this->options['start_date'], $this->client->date_format(), $this->client->locale()) . " - " . $this->translateDate($this->options['end_date'], $this->client->date_format(), $this->client->locale()); @@ -314,10 +312,8 @@ class Design extends BaseDesign $variables = $this->context['pdf_variables']['credit_details']; } - if($this->vendor){ - + if ($this->vendor) { $variables = $this->context['pdf_variables']['purchase_order_details']; - } $elements = []; @@ -503,9 +499,9 @@ class Design extends BaseDesign //24-03-2022 show payments per invoice foreach ($this->invoices as $invoice) { foreach ($invoice->payments as $payment) { - - if($payment->is_deleted) + if ($payment->is_deleted) { continue; + } $element = ['element' => 'tr', 'elements' => []]; @@ -706,7 +702,7 @@ class Design extends BaseDesign $element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => 'product_table-product.tax2-td']]; } elseif ($cell == '$product.tax_rate3') { $element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => 'product_table-product.tax3-td']]; - } else if ($cell == '$product.unit_cost' || $cell == '$task.rate') { + } elseif ($cell == '$product.unit_cost' || $cell == '$task.rate') { $element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['style' => 'white-space: nowrap;', 'data-ref' => "{$_type}_table-" . substr($cell, 1) . '-td']]; } else { $element['elements'][] = ['element' => 'td', 'content' => $row[$cell], 'properties' => ['data-ref' => "{$_type}_table-" . substr($cell, 1) . '-td']]; @@ -777,7 +773,6 @@ class Design extends BaseDesign if (in_array('$paid_to_date', $variables)) { $variables = \array_diff($variables, ['$paid_to_date']); } - } foreach (['discount'] as $property) { diff --git a/app/Services/PdfMaker/PdfMerge.php b/app/Services/PdfMaker/PdfMerge.php index d0c8f7bdc8bd..8f515f63146e 100644 --- a/app/Services/PdfMaker/PdfMerge.php +++ b/app/Services/PdfMaker/PdfMerge.php @@ -12,18 +12,18 @@ namespace App\Services\PdfMaker; -use Illuminate\Support\Facades\Storage; use \setasign\Fpdi\Fpdi; +use Illuminate\Support\Facades\Storage; use setasign\Fpdi\PdfParser\StreamReader; class PdfMerge { - - public function __construct(private array $file_paths) {} + public function __construct(private array $file_paths) + { + } public function run() { - $pdf = new FPDI(); foreach ($this->file_paths as $file) { @@ -36,7 +36,5 @@ class PdfMerge } return $pdf->Output('S'); - } - } diff --git a/app/Services/PurchaseOrder/GetPurchaseOrderPdf.php b/app/Services/PurchaseOrder/GetPurchaseOrderPdf.php index 4f263597983e..dde550a269c7 100644 --- a/app/Services/PurchaseOrder/GetPurchaseOrderPdf.php +++ b/app/Services/PurchaseOrder/GetPurchaseOrderPdf.php @@ -15,7 +15,6 @@ use App\Jobs\Vendor\CreatePurchaseOrderPdf; use App\Models\PurchaseOrder; use App\Models\VendorContact; use App\Services\AbstractService; -use App\Utils\TempFile; use Illuminate\Support\Facades\Storage; class GetPurchaseOrderPdf extends AbstractService diff --git a/app/Services/PurchaseOrder/MarkSent.php b/app/Services/PurchaseOrder/MarkSent.php index a81d91b45433..f458bb8a8216 100644 --- a/app/Services/PurchaseOrder/MarkSent.php +++ b/app/Services/PurchaseOrder/MarkSent.php @@ -11,10 +11,8 @@ namespace App\Services\PurchaseOrder; -use App\Jobs\Util\WebhookHandler; use App\Models\PurchaseOrder; use App\Models\Webhook; -use App\Utils\Ninja; class MarkSent { @@ -30,7 +28,6 @@ class MarkSent public function run() { - /* Return immediately if status is not draft */ if ($this->purchase_order->status_id != PurchaseOrder::STATUS_DRAFT) { return $this->purchase_order; diff --git a/app/Services/PurchaseOrder/PurchaseOrderExpense.php b/app/Services/PurchaseOrder/PurchaseOrderExpense.php index bb65fffe3fff..d206efbb28fb 100644 --- a/app/Services/PurchaseOrder/PurchaseOrderExpense.php +++ b/app/Services/PurchaseOrder/PurchaseOrderExpense.php @@ -28,7 +28,6 @@ class PurchaseOrderExpense public function run() { - $expense = ExpenseFactory::create($this->purchase_order->company_id, $this->purchase_order->user_id); $expense->amount = $this->purchase_order->uses_inclusive_taxes ? $this->purchase_order->amount : ($this->purchase_order->amount - $this->purchase_order->total_taxes); @@ -45,19 +44,18 @@ class PurchaseOrderExpense $expense->public_notes = ''; - foreach($line_items as $line_item){ + foreach ($line_items as $line_item) { $expense->public_notes .= $line_item->quantity . " x " . $line_item->product_key. " [ " .$line_item->notes . " ]\n"; } $tax_map = $this->purchase_order->calc()->getTaxMap(); - if($this->purchase_order->total_taxes > 0) - { + if ($this->purchase_order->total_taxes > 0) { $expense->tax_amount1 = $this->purchase_order->total_taxes; $expense->tax_name1 = ctrans("texts.tax"); } - $expense->number = empty($expense->number) ? $this->getNextExpenseNumber($expense) : $expense->number; + $expense->number = empty($expense->number) ? $this->getNextExpenseNumber($expense) : $expense->number; $expense->save(); event('eloquent.created: App\Models\Expense', $expense); @@ -66,6 +64,5 @@ class PurchaseOrderExpense $this->purchase_order->saveQuietly(); return $expense; - } } diff --git a/app/Services/PurchaseOrder/PurchaseOrderInventory.php b/app/Services/PurchaseOrder/PurchaseOrderInventory.php index 2c7b58d71c76..298c5718f617 100644 --- a/app/Services/PurchaseOrder/PurchaseOrderInventory.php +++ b/app/Services/PurchaseOrder/PurchaseOrderInventory.php @@ -11,17 +11,11 @@ namespace App\Services\PurchaseOrder; -use App\Factory\ExpenseFactory; -use App\Jobs\Mail\NinjaMailer; -use App\Jobs\Mail\NinjaMailerJob; -use App\Jobs\Mail\NinjaMailerObject; -use App\Mail\Admin\InventoryNotificationObject; use App\Models\Product; use App\Models\PurchaseOrder; class PurchaseOrderInventory { - private PurchaseOrder $purchase_order; public function __construct(PurchaseOrder $purchase_order) @@ -31,27 +25,22 @@ class PurchaseOrderInventory public function run() { - $line_items = $this->purchase_order->line_items; - foreach($line_items as $item) - { - + foreach ($line_items as $item) { $p = Product::where('product_key', $item->product_key)->where('company_id', $this->purchase_order->company_id)->first(); - if(!$p) + if (!$p) { continue; + } $p->in_stock_quantity += $item->quantity; $p->saveQuietly(); - } $this->purchase_order->status_id = PurchaseOrder::STATUS_RECEIVED; $this->purchase_order->save(); return $this->purchase_order; - } - } diff --git a/app/Services/PurchaseOrder/PurchaseOrderService.php b/app/Services/PurchaseOrder/PurchaseOrderService.php index 80bfb889e4ba..d1ab465d262c 100644 --- a/app/Services/PurchaseOrder/PurchaseOrderService.php +++ b/app/Services/PurchaseOrder/PurchaseOrderService.php @@ -13,11 +13,6 @@ namespace App\Services\PurchaseOrder; use App\Jobs\Vendor\CreatePurchaseOrderPdf; use App\Models\PurchaseOrder; -use App\Services\PurchaseOrder\ApplyNumber; -use App\Services\PurchaseOrder\CreateInvitations; -use App\Services\PurchaseOrder\GetPurchaseOrderPdf; -use App\Services\PurchaseOrder\PurchaseOrderExpense; -use App\Services\PurchaseOrder\TriggeredActions; use App\Utils\Traits\MakesHash; class PurchaseOrderService @@ -33,7 +28,6 @@ class PurchaseOrderService public function createInvitations() { - $this->purchase_order = (new CreateInvitations($this->purchase_order))->run(); return $this; @@ -48,27 +42,29 @@ class PurchaseOrderService public function fillDefaults() { - $settings = $this->purchase_order->company->settings; - if (! $this->purchase_order->design_id) + if (! $this->purchase_order->design_id) { $this->purchase_order->design_id = $this->decodePrimaryKey($settings->purchase_order_design_id); + } - if (!isset($this->purchase_order->footer) || empty($this->purchase_order->footer)) + if (!isset($this->purchase_order->footer) || empty($this->purchase_order->footer)) { $this->purchase_order->footer = $settings->purchase_order_footer; + } - if (!isset($this->purchase_order->terms) || empty($this->purchase_order->terms)) + if (!isset($this->purchase_order->terms) || empty($this->purchase_order->terms)) { $this->purchase_order->terms = $settings->purchase_order_terms; + } - if (!isset($this->purchase_order->public_notes) || empty($this->purchase_order->public_notes)) + if (!isset($this->purchase_order->public_notes) || empty($this->purchase_order->public_notes)) { $this->purchase_order->public_notes = $this->purchase_order->vendor->public_notes; + } - if($settings->counter_number_applied == 'when_saved'){ + if ($settings->counter_number_applied == 'when_saved') { $this->applyNumber()->save(); } return $this; - } public function triggeredActions($request) @@ -107,9 +103,7 @@ class PurchaseOrderService public function touchPdf($force = false) { try { - - if($force){ - + if ($force) { $this->purchase_order->invitations->each(function ($invitation) { (new CreatePurchaseOrderPdf($invitation))->handle(); }); @@ -120,12 +114,8 @@ class PurchaseOrderService $this->purchase_order->invitations->each(function ($invitation) { CreatePurchaseOrderPdf::dispatch($invitation); }); - - } - catch(\Exception $e){ - + } catch(\Exception $e) { nlog("failed creating purchase orders in Touch PDF"); - } return $this; @@ -133,8 +123,9 @@ class PurchaseOrderService public function add_to_inventory() { - if($this->purchase_order->status_id >= PurchaseOrder::STATUS_RECEIVED) + if ($this->purchase_order->status_id >= PurchaseOrder::STATUS_RECEIVED) { return $this->purchase_order; + } $this->purchase_order = (new PurchaseOrderInventory($this->purchase_order))->run(); @@ -145,8 +136,9 @@ class PurchaseOrderService { $this->markSent(); - if($this->purchase_order->expense()->exists()) + if ($this->purchase_order->expense()->exists()) { return $this; + } $expense = (new PurchaseOrderExpense($this->purchase_order))->run(); @@ -163,5 +155,4 @@ class PurchaseOrderService return $this->purchase_order; } - } diff --git a/app/Services/PurchaseOrder/TriggeredActions.php b/app/Services/PurchaseOrder/TriggeredActions.php index 8e2ef3f3ea33..02e9e0bdc871 100644 --- a/app/Services/PurchaseOrder/TriggeredActions.php +++ b/app/Services/PurchaseOrder/TriggeredActions.php @@ -11,14 +11,9 @@ namespace App\Services\PurchaseOrder; -use App\Events\Invoice\InvoiceWasEmailed; -use App\Events\PurchaseOrder\PurchaseOrderWasEmailed; -use App\Jobs\Entity\EmailEntity; use App\Jobs\PurchaseOrder\PurchaseOrderEmail; -use App\Models\Invoice; use App\Models\PurchaseOrder; use App\Services\AbstractService; -use App\Utils\Ninja; use App\Utils\Traits\GeneratesCounter; use Illuminate\Http\Request; @@ -52,7 +47,7 @@ class TriggeredActions extends AbstractService // $this->purchase_order = $this->purchase_order->service()->handleCancellation()->save(); // } - if($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') { + if ($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') { $company = $this->purchase_order->company; $settings = $company->settings; $settings->purchase_order_footer = $this->purchase_order->footer; @@ -60,7 +55,7 @@ class TriggeredActions extends AbstractService $company->save(); } - if($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') { + if ($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') { $company = $this->purchase_order->company; $settings = $company->settings; $settings->purchase_order_terms = $this->purchase_order->terms; diff --git a/app/Services/Quote/GetQuotePdf.php b/app/Services/Quote/GetQuotePdf.php index 88a4f55b0db4..09249ec9ff95 100644 --- a/app/Services/Quote/GetQuotePdf.php +++ b/app/Services/Quote/GetQuotePdf.php @@ -15,7 +15,6 @@ use App\Jobs\Entity\CreateEntityPdf; use App\Models\ClientContact; use App\Models\Quote; use App\Services\AbstractService; -use App\Utils\TempFile; use Illuminate\Support\Facades\Storage; class GetQuotePdf extends AbstractService diff --git a/app/Services/Quote/MarkSent.php b/app/Services/Quote/MarkSent.php index 76a4687db885..fa9c75a565b9 100644 --- a/app/Services/Quote/MarkSent.php +++ b/app/Services/Quote/MarkSent.php @@ -12,7 +12,6 @@ namespace App\Services\Quote; use App\Events\Quote\QuoteWasMarkedSent; -use App\Jobs\Util\WebhookHandler; use App\Models\Quote; use App\Models\Webhook; use App\Utils\Ninja; @@ -32,7 +31,6 @@ class MarkSent public function run() { - /* Return immediately if status is not draft */ if ($this->quote->status_id != Quote::STATUS_DRAFT) { return $this->quote; diff --git a/app/Services/Quote/QuoteService.php b/app/Services/Quote/QuoteService.php index 72fb91374d53..56ab95d8eb38 100644 --- a/app/Services/Quote/QuoteService.php +++ b/app/Services/Quote/QuoteService.php @@ -12,13 +12,11 @@ namespace App\Services\Quote; use App\Events\Quote\QuoteWasApproved; -use App\Factory\InvoiceInvitationFactory; use App\Jobs\Entity\CreateEntityPdf; use App\Jobs\Util\UnlinkFile; use App\Models\Invoice; use App\Models\Quote; use App\Repositories\QuoteRepository; -use App\Services\Quote\TriggeredActions; use App\Utils\Ninja; use App\Utils\Traits\MakesHash; @@ -129,7 +127,7 @@ class QuoteService /** * Sometimes we need to refresh the * PDF when it is updated etc. - * + * * @return QuoteService */ public function touchPdf($force = false) diff --git a/app/Services/Quote/SendEmail.php b/app/Services/Quote/SendEmail.php index 9e05fbb74f2c..1d40bc51835f 100644 --- a/app/Services/Quote/SendEmail.php +++ b/app/Services/Quote/SendEmail.php @@ -50,13 +50,12 @@ class SendEmail $this->quote->service()->markSent()->save(); - $this->quote->invitations->each(function ($invitation) use ($mo){ + $this->quote->invitations->each(function ($invitation) use ($mo) { if (! $invitation->contact->trashed() && $invitation->contact->email) { EmailEntity::dispatch($invitation, $invitation->company, $this->reminder_template); // MailEntity::dispatch($invitation, $invitation->company->db, $mo); } }); - } } diff --git a/app/Services/Quote/TriggeredActions.php b/app/Services/Quote/TriggeredActions.php index ba44a3d34fb9..0d59dc672b31 100644 --- a/app/Services/Quote/TriggeredActions.php +++ b/app/Services/Quote/TriggeredActions.php @@ -53,7 +53,7 @@ class TriggeredActions extends AbstractService $this->quote = $this->quote->service()->approveWithNoCoversion()->save(); } - if($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') { + if ($this->request->has('save_default_footer') && $this->request->input('save_default_footer') == 'true') { $company = $this->quote->company; $settings = $company->settings; $settings->quote_footer = $this->quote->footer; @@ -61,7 +61,7 @@ class TriggeredActions extends AbstractService $company->save(); } - if($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') { + if ($this->request->has('save_default_terms') && $this->request->input('save_default_terms') == 'true') { $company = $this->quote->company; $settings = $company->settings; $settings->quote_terms = $this->quote->terms; diff --git a/app/Services/Recurring/CreateRecurringInvitations.php b/app/Services/Recurring/CreateRecurringInvitations.php index 6fed3f7e5dee..128c3bab1934 100644 --- a/app/Services/Recurring/CreateRecurringInvitations.php +++ b/app/Services/Recurring/CreateRecurringInvitations.php @@ -64,15 +64,14 @@ class CreateRecurringInvitations extends AbstractService } if ($this->entity->invitations()->count() == 0) { - $invitation = $this->invitation_class::where('company_id', $this->entity->company_id) ->where($this->entity_id_name, $this->entity->id) ->withTrashed() ->first(); - if ($invitation) + if ($invitation) { $invitation->restore(); - + } } diff --git a/app/Services/Recurring/GetInvoicePdf.php b/app/Services/Recurring/GetInvoicePdf.php index 54776e4c57ad..448663f8e0cc 100644 --- a/app/Services/Recurring/GetInvoicePdf.php +++ b/app/Services/Recurring/GetInvoicePdf.php @@ -13,9 +13,7 @@ namespace App\Services\Recurring; use App\Jobs\Entity\CreateEntityPdf; use App\Models\ClientContact; -use App\Models\Invoice; use App\Services\AbstractService; -use App\Utils\TempFile; use Illuminate\Support\Facades\Storage; class GetInvoicePdf extends AbstractService diff --git a/app/Services/Recurring/RecurringService.php b/app/Services/Recurring/RecurringService.php index 057a5b939a7d..06595f6d2aa3 100644 --- a/app/Services/Recurring/RecurringService.php +++ b/app/Services/Recurring/RecurringService.php @@ -14,7 +14,6 @@ namespace App\Services\Recurring; use App\Jobs\RecurringInvoice\SendRecurring; use App\Jobs\Util\UnlinkFile; use App\Models\RecurringInvoice; -use App\Services\Recurring\GetInvoicePdf; use Illuminate\Support\Carbon; class RecurringService @@ -35,8 +34,9 @@ class RecurringService */ public function stop() { - if($this->recurring_entity->status_id < RecurringInvoice::STATUS_PAUSED) + if ($this->recurring_entity->status_id < RecurringInvoice::STATUS_PAUSED) { $this->recurring_entity->status_id = RecurringInvoice::STATUS_PAUSED; + } return $this; } @@ -50,7 +50,6 @@ class RecurringService public function start() { - if ($this->recurring_entity->remaining_cycles == 0) { return $this; } @@ -85,11 +84,8 @@ class RecurringService public function deletePdf() { - - $this->recurring_entity->invitations->each(function ($invitation){ - - (new UnlinkFile(config('filesystems.default'), $this->recurring_entity->client->recurring_invoice_filepath($invitation) . $this->recurring_entity->numberFormatter().'.pdf'))->handle(); - + $this->recurring_entity->invitations->each(function ($invitation) { + (new UnlinkFile(config('filesystems.default'), $this->recurring_entity->client->recurring_invoice_filepath($invitation) . $this->recurring_entity->numberFormatter().'.pdf'))->handle(); }); @@ -98,7 +94,6 @@ class RecurringService public function triggeredActions($request) { - if ($request->has('start') && $request->input('start') == 'true') { $this->start(); } @@ -113,8 +108,7 @@ class RecurringService return $this; } - if(isset($this->recurring_entity->client)) - { + if (isset($this->recurring_entity->client)) { $offset = $this->recurring_entity->client->timezone_offset(); $this->recurring_entity->next_send_date = Carbon::parse($this->recurring_entity->next_send_date_client)->startOfDay()->addSeconds($offset); } @@ -124,21 +118,18 @@ class RecurringService public function sendNow() { - - if($this->recurring_entity instanceof RecurringInvoice && $this->recurring_entity->status_id == RecurringInvoice::STATUS_DRAFT){ + if ($this->recurring_entity instanceof RecurringInvoice && $this->recurring_entity->status_id == RecurringInvoice::STATUS_DRAFT) { $this->start()->save(); - (new SendRecurring($this->recurring_entity, $this->recurring_entity->company->db))->handle(); + (new SendRecurring($this->recurring_entity, $this->recurring_entity->company->db))->handle(); } $this->recurring_entity = $this->recurring_entity->fresh(); return $this; - } public function fillDefaults() { - return $this; } diff --git a/app/Services/Report/ProfitLoss.php b/app/Services/Report/ProfitLoss.php index 7e07fa57a0fb..2415a9b02444 100644 --- a/app/Services/Report/ProfitLoss.php +++ b/app/Services/Report/ProfitLoss.php @@ -104,10 +104,8 @@ class ProfitLoss MultiDB::setDb($this->company->db); if ($this->is_income_billed) { //get invoiced amounts - $this->filterIncome(); } else { - //$this->filterPaymentIncome(); $this->filterInvoicePaymentIncome(); } @@ -592,48 +590,55 @@ class ProfitLoss } switch ($date_range) { - case 'all': $this->start_date = now()->subYears(50); $this->end_date = now(); // return $query; + // no break case 'last7': $this->start_date = now()->subDays(7); $this->end_date = now(); // return $query->whereBetween($this->date_key, [now()->subDays(7), now()])->orderBy($this->date_key, 'ASC'); + // no break case 'last30': $this->start_date = now()->subDays(30); $this->end_date = now(); // return $query->whereBetween($this->date_key, [now()->subDays(30), now()])->orderBy($this->date_key, 'ASC'); + // no break case 'this_month': $this->start_date = now()->startOfMonth(); $this->end_date = now(); //return $query->whereBetween($this->date_key, [now()->startOfMonth(), now()])->orderBy($this->date_key, 'ASC'); + // no break case 'last_month': $this->start_date = now()->startOfMonth()->subMonth(); $this->end_date = now()->startOfMonth()->subMonth()->endOfMonth(); //return $query->whereBetween($this->date_key, [now()->startOfMonth()->subMonth(), now()->startOfMonth()->subMonth()->endOfMonth()])->orderBy($this->date_key, 'ASC'); + // no break case 'this_quarter': $this->start_date = (new \Carbon\Carbon('-3 months'))->firstOfQuarter(); $this->end_date = (new \Carbon\Carbon('-3 months'))->lastOfQuarter(); //return $query->whereBetween($this->date_key, [(new \Carbon\Carbon('-3 months'))->firstOfQuarter(), (new \Carbon\Carbon('-3 months'))->lastOfQuarter()])->orderBy($this->date_key, 'ASC'); + // no break case 'last_quarter': $this->start_date = (new \Carbon\Carbon('-6 months'))->firstOfQuarter(); $this->end_date = (new \Carbon\Carbon('-6 months'))->lastOfQuarter(); //return $query->whereBetween($this->date_key, [(new \Carbon\Carbon('-6 months'))->firstOfQuarter(), (new \Carbon\Carbon('-6 months'))->lastOfQuarter()])->orderBy($this->date_key, 'ASC'); + // no break case 'this_year': $this->start_date = now()->startOfYear(); $this->end_date = now(); //return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC'); + // no break case 'custom': $this->start_date = $custom_start_date; $this->end_date = $custom_end_date; //return $query->whereBetween($this->date_key, [$custom_start_date, $custom_end_date])->orderBy($this->date_key, 'ASC'); + // no break default: $this->start_date = now()->startOfYear(); $this->end_date = now(); // return $query->whereBetween($this->date_key, [now()->startOfYear(), now()])->orderBy($this->date_key, 'ASC'); - } return $this; diff --git a/app/Services/Scheduler/SchedulerService.php b/app/Services/Scheduler/SchedulerService.php index 413bbdc78f12..854ff8efce4c 100644 --- a/app/Services/Scheduler/SchedulerService.php +++ b/app/Services/Scheduler/SchedulerService.php @@ -16,7 +16,6 @@ use App\Models\RecurringInvoice; use App\Models\Scheduler; use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; -use Carbon\Carbon; class SchedulerService { @@ -27,12 +26,14 @@ class SchedulerService private Client $client; - public function __construct(public Scheduler $scheduler) {} + public function __construct(public Scheduler $scheduler) + { + } /** * Called from the TaskScheduler Cron - * - * @return void + * + * @return void */ public function runTask(): void { @@ -40,35 +41,33 @@ class SchedulerService } private function client_statement() - { + { $query = Client::query() ->where('company_id', $this->scheduler->company_id) - ->where('is_deleted',0); + ->where('is_deleted', 0); //Email only the selected clients - if(count($this->scheduler->parameters['clients']) >= 1) + if (count($this->scheduler->parameters['clients']) >= 1) { $query->whereIn('id', $this->transformKeys($this->scheduler->parameters['clients'])); + } $query->cursor() - ->each(function ($_client){ + ->each(function ($_client) { + $this->client = $_client; - $this->client = $_client; + //work out the date range + $statement_properties = $this->calculateStatementProperties(); - //work out the date range - $statement_properties = $this->calculateStatementProperties(); - - $_client->service()->statement($statement_properties,true); - - }); + $_client->service()->statement($statement_properties, true); + }); //calculate next run dates; $this->calculateNextRun(); - } /** * Hydrates the array needed to generate the statement - * + * * @return array The statement options array */ private function calculateStatementProperties(): array @@ -76,18 +75,17 @@ class SchedulerService $start_end = $this->calculateStartAndEndDates(); return [ - 'start_date' =>$start_end[0], - 'end_date' =>$start_end[1], - 'show_payments_table' => $this->scheduler->parameters['show_payments_table'], - 'show_aging_table' => $this->scheduler->parameters['show_aging_table'], + 'start_date' =>$start_end[0], + 'end_date' =>$start_end[1], + 'show_payments_table' => $this->scheduler->parameters['show_payments_table'], + 'show_aging_table' => $this->scheduler->parameters['show_aging_table'], 'status' => $this->scheduler->parameters['status'] ]; - } /** * Start and end date of the statement - * + * * @return array [$start_date, $end_date]; */ private function calculateStartAndEndDates(): array @@ -100,14 +98,14 @@ class SchedulerService 'previous_quarter' => [now()->startOfDay()->subQuarterNoOverflow()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->subQuarterNoOverflow()->lastOfQuarter()->format('Y-m-d')], 'previous_year' => [now()->startOfDay()->subYearNoOverflow()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->subYearNoOverflow()->lastOfYear()->format('Y-m-d')], 'custom_range' => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']], - default => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], + default => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], }; } /** * Sets the next run date of the scheduled task - * + * */ private function calculateNextRun() { @@ -159,13 +157,10 @@ class SchedulerService } - $this->scheduler->next_run_client = $next_run ?: null; + $this->scheduler->next_run_client = $next_run ?: null; $this->scheduler->next_run = $next_run ? $next_run->copy()->addSeconds($offset) : null; $this->scheduler->save(); - } //handle when the scheduler has been paused. - - -} \ No newline at end of file +} diff --git a/app/Services/Subscription/SubscriptionService.php b/app/Services/Subscription/SubscriptionService.php index e2c0e9f56383..08d803d52ef5 100644 --- a/app/Services/Subscription/SubscriptionService.php +++ b/app/Services/Subscription/SubscriptionService.php @@ -14,13 +14,11 @@ namespace App\Services\Subscription; use App\DataMapper\InvoiceItem; use App\Factory\CreditFactory; use App\Factory\InvoiceFactory; -use App\Factory\InvoiceToRecurringInvoiceFactory; use App\Factory\PaymentFactory; use App\Factory\RecurringInvoiceFactory; use App\Jobs\Mail\NinjaMailer; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; -use App\Jobs\Util\SubscriptionWebhookHandler; use App\Jobs\Util\SystemLogger; use App\Libraries\MultiDB; use App\Mail\RecurringInvoice\ClientContactRequestCancellationObject; @@ -39,14 +37,11 @@ use App\Repositories\InvoiceRepository; use App\Repositories\PaymentRepository; use App\Repositories\RecurringInvoiceRepository; use App\Repositories\SubscriptionRepository; -use App\Services\Subscription\ZeroCostProduct; -use App\Utils\Ninja; use App\Utils\Traits\CleanLineItems; use App\Utils\Traits\MakesHash; use App\Utils\Traits\Notifications\UserNotifies; use App\Utils\Traits\SubscriptionHooker; use Carbon\Carbon; -use GuzzleHttp\RequestOptions; use Illuminate\Contracts\Container\BindingResolutionException; class SubscriptionService @@ -72,22 +67,21 @@ class SubscriptionService */ public function completePurchase(PaymentHash $payment_hash) { - if (!property_exists($payment_hash->data, 'billing_context')) { throw new \Exception("Illegal entrypoint into method, payload must contain billing context"); } - if($payment_hash->data->billing_context->context == 'change_plan') { + if ($payment_hash->data->billing_context->context == 'change_plan') { return $this->handlePlanChange($payment_hash); } // if we have a recurring product - then generate a recurring invoice - if(strlen($this->subscription->recurring_product_ids) >=1){ - - if(isset($payment_hash->data->billing_context->bundle)) + if (strlen($this->subscription->recurring_product_ids) >=1) { + if (isset($payment_hash->data->billing_context->bundle)) { $recurring_invoice = $this->convertInvoiceToRecurringBundle($payment_hash->payment->client_id, $payment_hash->data->billing_context->bundle); - else + } else { $recurring_invoice = $this->convertInvoiceToRecurring($payment_hash->payment->client_id); + } $recurring_invoice_repo = new RecurringInvoiceRepository(); @@ -120,10 +114,7 @@ class SubscriptionService $response = $this->triggerWebhook($context); $this->handleRedirect('/client/recurring_invoices/'.$recurring_invoice->hashed_id); - - } - else - { + } else { $invoice = Invoice::withTrashed()->find($payment_hash->fee_invoice_id); $context = [ @@ -139,9 +130,9 @@ class SubscriptionService /* 06-04-2022 */ /* We may not be in a state where the user is present */ - if(auth()->guard('contact')) + if (auth()->guard('contact')) { $this->handleRedirect('/client/invoices/'.$this->encodePrimaryKey($payment_hash->fee_invoice_id)); - + } } } @@ -172,27 +163,29 @@ class SubscriptionService // Redirects from here work just fine. Livewire will respect it. $client_contact = ClientContact::find($this->decodePrimaryKey($data['contact_id'])); - if(!$this->subscription->trial_enabled) + if (!$this->subscription->trial_enabled) { return new \Exception("Trials are disabled for this product"); + } //create recurring invoice with start date = trial_duration + 1 day $recurring_invoice_repo = new RecurringInvoiceRepository(); - if(isset($data['bundle'])) - $recurring_invoice = $this->convertInvoiceToRecurringBundle($client_contact->client_id, $data['bundle']->map(function ($bundle){ return (object) $bundle;})); - else + if (isset($data['bundle'])) { + $recurring_invoice = $this->convertInvoiceToRecurringBundle($client_contact->client_id, $data['bundle']->map(function ($bundle) { + return (object) $bundle; + })); + } else { $recurring_invoice = $this->convertInvoiceToRecurring($client_contact->client_id); + } $recurring_invoice->next_send_date = now()->addSeconds($this->subscription->trial_duration); $recurring_invoice->next_send_date_client = now()->addSeconds($this->subscription->trial_duration); $recurring_invoice->backup = 'is_trial'; - if(array_key_exists('coupon', $data) && ($data['coupon'] == $this->subscription->promo_code) && $this->subscription->promo_discount > 0) - { + if (array_key_exists('coupon', $data) && ($data['coupon'] == $this->subscription->promo_code) && $this->subscription->promo_discount > 0) { $recurring_invoice->discount = $this->subscription->promo_discount; $recurring_invoice->is_amount_discount = $this->subscription->is_amount_discount; - } - elseif(strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) { + } elseif (strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) { $recurring_invoice->discount = $this->subscription->promo_discount; $recurring_invoice->is_amount_discount = $this->subscription->is_amount_discount; } @@ -204,13 +197,13 @@ class SubscriptionService ->start() ->save(); - $context = [ - 'context' => 'trial', - 'recurring_invoice' => $recurring_invoice->hashed_id, - 'client' => $recurring_invoice->client->hashed_id, - 'subscription' => $this->subscription->hashed_id, - 'account_key' => $recurring_invoice->client->custom_value2, - ]; + $context = [ + 'context' => 'trial', + 'recurring_invoice' => $recurring_invoice->hashed_id, + 'client' => $recurring_invoice->client->hashed_id, + 'subscription' => $this->subscription->hashed_id, + 'account_key' => $recurring_invoice->client->custom_value2, + ]; //execute any webhooks $response = $this->triggerWebhook($context); @@ -231,7 +224,6 @@ class SubscriptionService */ public function calculateUpgradePriceV2(RecurringInvoice $recurring_invoice, Subscription $target) :?float { - $outstanding_credit = 0; $use_credit_setting = $recurring_invoice->client->getSetting('use_credits_payment'); @@ -244,22 +236,18 @@ class SubscriptionService $refund = $this->calculateProRataRefundForSubscription($last_invoice); - if($use_credit_setting != 'off') - { - + if ($use_credit_setting != 'off') { $outstanding_credit = Credit::query() ->where('client_id', $recurring_invoice->client_id) ->whereIn('status_id', [Credit::STATUS_SENT,Credit::STATUS_PARTIAL]) ->where('is_deleted', 0) ->where('balance', '>', 0) ->sum('balance'); - } nlog("{$target->price} - {$refund} - {$outstanding_credit}"); return $target->price - $refund - $outstanding_credit; - } /** @@ -275,7 +263,6 @@ class SubscriptionService */ public function calculateUpgradePrice(RecurringInvoice $recurring_invoice, Subscription $target) :?float { - //calculate based on daily prices $current_amount = $recurring_invoice->amount; $currency_frequency = $recurring_invoice->frequency_id; @@ -283,7 +270,7 @@ class SubscriptionService $outstanding = Invoice::query() ->where('recurring_id', $recurring_invoice->id) ->where('is_deleted', 0) - ->where('is_proforma',0) + ->where('is_proforma', 0) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL]) ->where('balance', '>', 0); @@ -291,67 +278,60 @@ class SubscriptionService $outstanding_invoice = Invoice::where('client_id', $recurring_invoice->client_id) ->where('is_deleted', 0) - ->where('is_proforma',0) + ->where('is_proforma', 0) ->where('subscription_id', $this->subscription->id) ->orderBy('id', 'desc') ->first(); - //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) - ->where('client_id', $recurring_invoice->client_id) - ->where('is_proforma',0) - ->where('is_deleted', 0) - ->orderBy('id', 'desc') - ->first(); + //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) + ->where('client_id', $recurring_invoice->client_id) + ->where('is_proforma', 0) + ->where('is_deleted', 0) + ->orderBy('id', 'desc') + ->first(); } //need to ensure at this point that a refund is appropriate!! //28-02-2022 - if($recurring_invoice->invoices()->count() == 0){ + if ($recurring_invoice->invoices()->count() == 0) { return $target->price; - } - elseif ($outstanding->count() == 0){ + } elseif ($outstanding->count() == 0) { //nothing outstanding return $target->price - $this->calculateProRataRefundForSubscription($outstanding_invoice); - } - elseif ($outstanding->count() == 1){ + } elseif ($outstanding->count() == 1) { //user has multiple amounts outstanding return $target->price - $this->calculateProRataRefundForSubscription($outstanding_invoice); - } - elseif ($outstanding->count() > 1) { + } elseif ($outstanding->count() > 1) { //user is changing plan mid frequency cycle //we cannot handle this if there are more than one invoice outstanding. return $target->price; } return $target->price; - } /** * We refund unused days left. * * @param Invoice $invoice - * + * * @return float */ private function calculateProRataRefundForSubscription($invoice) :float { - if(!$invoice || !$invoice->date || $invoice->status_id != Invoice::STATUS_PAID) + if (!$invoice || !$invoice->date || $invoice->status_id != Invoice::STATUS_PAID) { return 0; + } /*Remove previous refunds from the calculation of the amount*/ - $invoice->line_items = collect($invoice->line_items)->filter(function($item){ - - if($item->product_key == ctrans("texts.refund")) - { + $invoice->line_items = collect($invoice->line_items)->filter(function ($item) { + if ($item->product_key == ctrans("texts.refund")) { return false; } return true; - })->toArray(); $amount = $invoice->calc()->getTotal(); @@ -364,11 +344,10 @@ class SubscriptionService $days_in_frequency = $this->getDaysInFrequency(); - $pro_rata_refund = round((($days_in_frequency - $days_of_subscription_used)/$days_in_frequency) * $amount ,2); + $pro_rata_refund = round((($days_in_frequency - $days_of_subscription_used)/$days_in_frequency) * $amount, 2); return max(0, $pro_rata_refund); - - } + } /** * We refund unused days left. @@ -378,8 +357,9 @@ class SubscriptionService */ private function calculateProRataRefund($invoice) :float { - if(!$invoice || !$invoice->date) + if (!$invoice || !$invoice->date) { return 0; + } $start_date = Carbon::parse($invoice->date); @@ -389,13 +369,13 @@ class SubscriptionService $days_in_frequency = $this->getDaysInFrequency(); - if($days_of_subscription_used >= $days_in_frequency) + if ($days_of_subscription_used >= $days_in_frequency) { return 0; + } - $pro_rata_refund = round((($days_in_frequency - $days_of_subscription_used)/$days_in_frequency) * $invoice->amount ,2); + $pro_rata_refund = round((($days_in_frequency - $days_of_subscription_used)/$days_in_frequency) * $invoice->amount, 2); return $pro_rata_refund; - } /** @@ -408,8 +388,9 @@ class SubscriptionService */ private function calculateProRataRefundItems($invoice, $is_credit = false) :array { - if(!$invoice) + if (!$invoice) { return []; + } $handle_discount = false; @@ -430,32 +411,28 @@ class SubscriptionService //Handle when we are refunding a discounted invoice. Need to consider the //total discount and also the line item discount. - if($invoice->discount > 0) + if ($invoice->discount > 0) { $handle_discount = true; + } - foreach($invoice->line_items as $item) - { - - if($item->product_key != ctrans('texts.refund') && ($item->type_id == "1" || $item->type_id == "2")) - { - + foreach ($invoice->line_items as $item) { + if ($item->product_key != ctrans('texts.refund') && ($item->type_id == "1" || $item->type_id == "2")) { $discount_ratio = 1; - if($handle_discount) + if ($handle_discount) { $discount_ratio = $this->calculateDiscountRatio($invoice); + } $item->cost = ($item->cost*$ratio*$multiplier*$discount_ratio); $item->product_key = ctrans('texts.refund'); $item->notes = ctrans('texts.refund') . ": ". $item->notes; $line_items[] = $item; - } } return $line_items; - } @@ -467,12 +444,11 @@ class SubscriptionService */ public function calculateDiscountRatio($invoice) : float { - - if($invoice->is_amount_discount) + if ($invoice->is_amount_discount) { return $invoice->discount / ($invoice->amount + $invoice->discount); - else + } else { return $invoice->discount / 100; - + } } /** @@ -483,7 +459,6 @@ class SubscriptionService */ private function calculateProRataCharge($invoice) :float { - $start_date = Carbon::parse($invoice->date); $current_date = now(); @@ -494,7 +469,7 @@ class SubscriptionService nlog("days to charge = {$days_to_charge} days in frequency = {$days_in_frequency}"); - $pro_rata_charge = round(($days_to_charge/$days_in_frequency) * $invoice->amount ,2); + $pro_rata_charge = round(($days_to_charge/$days_in_frequency) * $invoice->amount, 2); nlog("pro rata charge = {$pro_rata_charge}"); @@ -504,10 +479,10 @@ class SubscriptionService /** * This entry point assumes the user does not have to make a * payment for the service. - * + * * In this case, we generate a credit note for the old service * Generate a new invoice for the new service - * Apply credits to the invoice + * Apply credits to the invoice * * @param array $data */ @@ -526,7 +501,7 @@ class SubscriptionService /* Get last invoice */ $last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id) ->where('client_id', $recurring_invoice->client_id) - ->where('is_proforma',0) + ->where('is_proforma', 0) ->where('is_deleted', 0) ->whereIn('status_id', [Invoice::STATUS_SENT, Invoice::STATUS_PARTIAL, Invoice::STATUS_PAID]) ->withTrashed() @@ -535,18 +510,11 @@ class SubscriptionService //if last payment was created from a credit, do not generate a new credit, refund the old one. - if($last_invoice) { - - - $last_invoice->payments->each(function ($payment){ - - $payment->credits()->where('is_deleted', 0)->each(function ($credit){ - - $this->credit_payments += $credit->pivot->sum('amount'); - + if ($last_invoice) { + $last_invoice->payments->each(function ($payment) { + $payment->credits()->where('is_deleted', 0)->each(function ($credit) { + $this->credit_payments += $credit->pivot->sum('amount'); }); - - }); $invoice_repo = new InvoiceRepository(); @@ -555,15 +523,15 @@ class SubscriptionService $payment_repo = new PaymentRepository(new CreditRepository()); - $last_invoice->payments->each(function ($payment) use ($payment_repo){ - $payment_repo->delete($payment); - }); - + $last_invoice->payments->each(function ($payment) use ($payment_repo) { + $payment_repo->delete($payment); + }); } //if there are existing credit payments, then we refund directly to the credit. - if($this->calculateProRataRefundForSubscription($last_invoice) > 0 && $this->credit_payments == 0) + if ($this->calculateProRataRefundForSubscription($last_invoice) > 0 && $this->credit_payments == 0) { $credit = $this->createCredit($last_invoice, $target_subscription, false); + } $new_recurring_invoice = $this->createNewRecurringInvoice($recurring_invoice); @@ -580,20 +548,19 @@ class SubscriptionService $payment->service()->applyNumber()->applyCreditsToInvoice($invoice); - $context = [ - 'context' => 'change_plan', - 'recurring_invoice' => $new_recurring_invoice->hashed_id, - 'credit' => $credit ? $credit->hashed_id : null, - 'client' => $new_recurring_invoice->client->hashed_id, - 'subscription' => $target_subscription->hashed_id, - 'contact' => auth()->guard('contact')->user()->hashed_id, - 'account_key' => $new_recurring_invoice->client->custom_value2, - ]; + $context = [ + 'context' => 'change_plan', + 'recurring_invoice' => $new_recurring_invoice->hashed_id, + 'credit' => $credit ? $credit->hashed_id : null, + 'client' => $new_recurring_invoice->client->hashed_id, + 'subscription' => $target_subscription->hashed_id, + 'contact' => auth()->guard('contact')->user()->hashed_id, + 'account_key' => $new_recurring_invoice->client->custom_value2, + ]; - $response = $this->triggerWebhook($context); - - return '/client/recurring_invoices/'.$new_recurring_invoice->hashed_id; + $response = $this->triggerWebhook($context); + return '/client/recurring_invoices/'.$new_recurring_invoice->hashed_id; } /** @@ -620,11 +587,9 @@ class SubscriptionService ->orderBy('id', 'desc') ->first(); - if($recurring_invoice->invoices()->count() == 0){ + if ($recurring_invoice->invoices()->count() == 0) { $pro_rata_refund_amount = 0; - } - elseif(!$last_invoice){ - + } elseif (!$last_invoice) { $is_credit = true; $last_invoice = Credit::where('subscription_id', $recurring_invoice->subscription_id) @@ -632,19 +597,13 @@ class SubscriptionService ->where('is_deleted', 0) ->withTrashed() ->orderBy('id', 'desc') - ->first(); + ->first(); $pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription); - - } - - elseif($last_invoice->balance > 0) - { + } elseif ($last_invoice->balance > 0) { $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription); nlog("pro rata charge = {$pro_rata_charge_amount}"); - } - else - { + } else { $pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription) * -1; nlog("pro rata refund = {$pro_rata_refund_amount}"); } @@ -656,39 +615,37 @@ class SubscriptionService $credit = false; /* Only generate a credit if the previous invoice was paid in full. */ - if($last_invoice && $last_invoice->balance == 0) + if ($last_invoice && $last_invoice->balance == 0) { $credit = $this->createCredit($last_invoice, $target_subscription, $is_credit); + } $new_recurring_invoice = $this->createNewRecurringInvoice($recurring_invoice); - $context = [ - 'context' => 'change_plan', - 'recurring_invoice' => $new_recurring_invoice->hashed_id, - 'credit' => $credit ? $credit->hashed_id : null, - 'client' => $new_recurring_invoice->client->hashed_id, - 'subscription' => $target_subscription->hashed_id, - 'contact' => auth()->guard('contact')->user()->hashed_id, - 'account_key' => $new_recurring_invoice->client->custom_value2, - ]; + $context = [ + 'context' => 'change_plan', + 'recurring_invoice' => $new_recurring_invoice->hashed_id, + 'credit' => $credit ? $credit->hashed_id : null, + 'client' => $new_recurring_invoice->client->hashed_id, + 'subscription' => $target_subscription->hashed_id, + 'contact' => auth()->guard('contact')->user()->hashed_id, + 'account_key' => $new_recurring_invoice->client->custom_value2, + ]; - $response = $this->triggerWebhook($context); + $response = $this->triggerWebhook($context); - nlog($response); - - if($credit){ - // return $this->handleRedirect('/client/credits/'.$credit->hashed_id); - return '/client/credits/'.$credit->hashed_id; - } - else{ - // return $this->handleRedirect('/client/credits'); - return '/client/credits'; - } + nlog($response); + if ($credit) { + // return $this->handleRedirect('/client/credits/'.$credit->hashed_id); + return '/client/credits/'.$credit->hashed_id; + } else { + // return $this->handleRedirect('/client/credits'); + return '/client/credits'; + } } public function changePlanPaymentCheck($data) { - $recurring_invoice = $data['recurring_invoice']; $old_subscription = $data['subscription']; $target_subscription = $data['target']; @@ -698,22 +655,19 @@ class SubscriptionService $last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id) ->where('client_id', $recurring_invoice->client_id) - ->where('is_proforma',0) + ->where('is_proforma', 0) ->where('is_deleted', 0) ->withTrashed() ->orderBy('id', 'desc') ->first(); - if(!$last_invoice) + if (!$last_invoice) { return true; + } - if($last_invoice->balance > 0) - { + if ($last_invoice->balance > 0) { $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription); nlog("pro rata charge = {$pro_rata_charge_amount}"); - - } - else - { + } else { $pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription) * -1; nlog("pro rata refund = {$pro_rata_refund_amount}"); } @@ -722,11 +676,11 @@ class SubscriptionService $total_payable = $pro_rata_refund_amount + $pro_rata_charge_amount + $this->subscription->price; - if($total_payable > 0) + if ($total_payable > 0) { return true; + } return false; - } /** @@ -737,7 +691,6 @@ class SubscriptionService */ public function createChangePlanInvoice($data) { - $recurring_invoice = $data['recurring_invoice']; $old_subscription = $data['subscription']; $target_subscription = $data['target']; @@ -748,22 +701,18 @@ class SubscriptionService $last_invoice = Invoice::where('subscription_id', $recurring_invoice->subscription_id) ->where('client_id', $recurring_invoice->client_id) ->where('is_deleted', 0) - ->where('is_proforma',0) + ->where('is_proforma', 0) ->withTrashed() ->orderBy('id', 'desc') ->first(); - if(!$last_invoice){ + if (!$last_invoice) { //do nothing - } - else if($last_invoice->balance > 0) - { + } elseif ($last_invoice->balance > 0) { $last_invoice = null; - // $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription); - // nlog("pro rata charge = {$pro_rata_charge_amount}"); - } - else - { + // $pro_rata_charge_amount = $this->calculateProRataCharge($last_invoice, $old_subscription); + // nlog("pro rata charge = {$pro_rata_charge_amount}"); + } else { $pro_rata_refund_amount = $this->calculateProRataRefund($last_invoice, $old_subscription) * -1; nlog("pro rata refund = {$pro_rata_refund_amount}"); } @@ -771,7 +720,6 @@ class SubscriptionService $total_payable = $pro_rata_refund_amount + $pro_rata_charge_amount + $this->subscription->price; return $this->proRataInvoice($last_invoice, $target_subscription, $recurring_invoice->client_id); - } /** @@ -786,8 +734,9 @@ class SubscriptionService $old_recurring_invoice = RecurringInvoice::find($this->decodePrimaryKey($payment_hash->data->billing_context->recurring_invoice)); - if(!$old_recurring_invoice) + if (!$old_recurring_invoice) { return $this->handleRedirect('/client/recurring_invoices/'); + } $recurring_invoice = $this->createNewRecurringInvoice($old_recurring_invoice); @@ -813,7 +762,6 @@ class SubscriptionService nlog($response); return $this->handleRedirect('/client/recurring_invoices/'.$recurring_invoice->hashed_id); - } /** @@ -825,26 +773,24 @@ class SubscriptionService */ public function createNewRecurringInvoice($old_recurring_invoice) :RecurringInvoice { - $old_recurring_invoice->service()->stop()->save(); $recurring_invoice_repo = new RecurringInvoiceRepository(); $recurring_invoice_repo->delete($old_recurring_invoice); - $recurring_invoice = $this->convertInvoiceToRecurring($old_recurring_invoice->client_id); - $recurring_invoice = $recurring_invoice_repo->save([], $recurring_invoice); - $recurring_invoice->next_send_date = now()->format('Y-m-d'); - $recurring_invoice->next_send_date_client = now()->format('Y-m-d'); - $recurring_invoice->next_send_date = $recurring_invoice->nextSendDate(); - $recurring_invoice->next_send_date_client = $recurring_invoice->nextSendDateClient(); + $recurring_invoice = $this->convertInvoiceToRecurring($old_recurring_invoice->client_id); + $recurring_invoice = $recurring_invoice_repo->save([], $recurring_invoice); + $recurring_invoice->next_send_date = now()->format('Y-m-d'); + $recurring_invoice->next_send_date_client = now()->format('Y-m-d'); + $recurring_invoice->next_send_date = $recurring_invoice->nextSendDate(); + $recurring_invoice->next_send_date_client = $recurring_invoice->nextSendDateClient(); - /* Start the recurring service */ - $recurring_invoice->service() - ->start() - ->save(); - - return $recurring_invoice; + /* Start the recurring service */ + $recurring_invoice->service() + ->start() + ->save(); + return $recurring_invoice; } /** @@ -856,7 +802,6 @@ class SubscriptionService */ private function createCredit($last_invoice, $target, $is_credit = false) { - $last_invoice_is_credit = $is_credit ? false : true; $subscription_repo = new SubscriptionRepository(); @@ -877,7 +822,6 @@ class SubscriptionService ]; return $credit_repo->save($data, $credit)->service()->markSent()->fillDefaults()->save(); - } /** @@ -911,7 +855,6 @@ class SubscriptionService ->markSent() ->fillDefaults() ->save(); - } /** @@ -944,13 +887,11 @@ class SubscriptionService ->markSent() ->fillDefaults() ->save(); - } public function createInvoiceV2($bundle, $client_id, $valid_coupon = false) { - $invoice_repo = new InvoiceRepository(); $subscription_repo = new SubscriptionRepository(); @@ -958,9 +899,8 @@ class SubscriptionService $invoice->subscription_id = $this->subscription->id; $invoice->client_id = $client_id; $invoice->is_proforma = true; - $invoice->number = "####" . ctrans('texts.subscription') . "_" . now()->format('Y-m-d') . "_" . rand(0,100000); - $line_items = $bundle->map(function ($item){ - + $invoice->number = "####" . ctrans('texts.subscription') . "_" . now()->format('Y-m-d') . "_" . rand(0, 100000); + $line_items = $bundle->map(function ($item) { $line_item = new InvoiceItem; $line_item->product_key = $item['product_key']; $line_item->quantity = (float)$item['qty']; @@ -968,18 +908,16 @@ class SubscriptionService $line_item->notes = $item['description']; return $line_item; - })->toArray(); $invoice->line_items = $line_items; - if($valid_coupon){ + if ($valid_coupon) { $invoice->discount = $this->subscription->promo_discount; $invoice->is_amount_discount = $this->subscription->is_amount_discount; } return $invoice_repo->save([], $invoice); - } /** @@ -990,7 +928,6 @@ class SubscriptionService */ public function createInvoice($data, $quantity = 1): ?\App\Models\Invoice { - $invoice_repo = new InvoiceRepository(); $subscription_repo = new SubscriptionRepository(); $subscription_repo->quantity = $quantity; @@ -1000,18 +937,15 @@ class SubscriptionService $invoice->subscription_id = $this->subscription->id; $invoice->is_proforma = true; - if(strlen($data['coupon']) >=1 && ($data['coupon'] == $this->subscription->promo_code) && $this->subscription->promo_discount > 0) - { + if (strlen($data['coupon']) >=1 && ($data['coupon'] == $this->subscription->promo_code) && $this->subscription->promo_discount > 0) { $invoice->discount = $this->subscription->promo_discount; $invoice->is_amount_discount = $this->subscription->is_amount_discount; - } - elseif(strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) { + } elseif (strlen($this->subscription->promo_code) == 0 && $this->subscription->promo_discount > 0) { $invoice->discount = $this->subscription->promo_discount; $invoice->is_amount_discount = $this->subscription->is_amount_discount; } return $invoice_repo->save($data, $invoice); - } /** @@ -1088,7 +1022,6 @@ class SubscriptionService } return false; - } /** @@ -1098,7 +1031,6 @@ class SubscriptionService */ public function triggerWebhook($context) { - if (empty($this->subscription->webhook_configuration['post_purchase_url']) || is_null($this->subscription->webhook_configuration['post_purchase_url']) || strlen($this->subscription->webhook_configuration['post_purchase_url']) < 1) { return ["message" => "Success", "status_code" => 200]; } @@ -1112,35 +1044,30 @@ class SubscriptionService $response = $this->sendLoad($this->subscription, $body); /* Append the response to the system logger body */ - if(is_array($response)){ - + if (is_array($response)) { $body = $response; - - } - else { - + } else { $body = $response->getStatusCode(); - } $client = Client::where('id', $this->decodePrimaryKey($body['client']))->withTrashed()->first(); - SystemLogger::dispatch( - $body, - SystemLog::CATEGORY_WEBHOOK, - SystemLog::EVENT_WEBHOOK_RESPONSE, - SystemLog::TYPE_WEBHOOK_RESPONSE, - $client, - $client->company, - ); + SystemLogger::dispatch( + $body, + SystemLog::CATEGORY_WEBHOOK, + SystemLog::EVENT_WEBHOOK_RESPONSE, + SystemLog::TYPE_WEBHOOK_RESPONSE, + $client, + $client->company, + ); nlog("ready to fire back"); - if(is_array($body)) - return $response; - else - return ['message' => 'There was a problem encountered with the webhook', 'status_code' => 500]; - + if (is_array($body)) { + return $response; + } else { + return ['message' => 'There was a problem encountered with the webhook', 'status_code' => 500]; + } } public function fireNotifications() @@ -1155,15 +1082,17 @@ class SubscriptionService */ public function products() { - if(!$this->subscription->product_ids) + if (!$this->subscription->product_ids) { return collect(); + } $keys = $this->transformKeys(explode(",", $this->subscription->product_ids)); - if(is_array($keys)) + if (is_array($keys)) { return Product::whereIn('id', $keys)->get(); - else + } else { return Product::where('id', $keys)->get(); + } } /** @@ -1173,18 +1102,17 @@ class SubscriptionService */ public function recurring_products() { - if(!$this->subscription->recurring_product_ids) + if (!$this->subscription->recurring_product_ids) { return collect(); + } $keys = $this->transformKeys(explode(",", $this->subscription->recurring_product_ids)); - if(is_array($keys)){ + if (is_array($keys)) { return Product::whereIn('id', $keys)->get(); - } - else{ + } else { return Product::where('id', $keys)->get(); } - } /* OPTIONAL PRODUCTS*/ @@ -1195,15 +1123,17 @@ class SubscriptionService */ public function optional_products() { - if(!$this->subscription->optional_product_ids) + if (!$this->subscription->optional_product_ids) { return collect(); + } $keys = $this->transformKeys(explode(",", $this->subscription->optional_product_ids)); - if(is_array($keys)) + if (is_array($keys)) { return Product::whereIn('id', $keys)->get(); - else + } else { return Product::where('id', $keys)->get(); + } } /** @@ -1213,18 +1143,17 @@ class SubscriptionService */ public function optional_recurring_products() { - if(!$this->subscription->optional_recurring_product_ids) + if (!$this->subscription->optional_recurring_product_ids) { return collect(); + } $keys = $this->transformKeys(explode(",", $this->subscription->optional_recurring_product_ids)); - if(is_array($keys)){ + if (is_array($keys)) { return Product::whereIn('id', $keys)->get(); - } - else{ + } else { return Product::where('id', $keys)->get(); } - } @@ -1265,13 +1194,12 @@ class SubscriptionService ->where('client_id', $recurring_invoice->client_id) ->where('status_id', Invoice::STATUS_PAID) ->where('is_deleted', 0) - ->where('is_proforma',0) - ->where('balance',0) + ->where('is_proforma', 0) + ->where('balance', 0) ->orderBy('id', 'desc') ->first(); - if($outstanding_invoice) - { + if ($outstanding_invoice) { $invoice_start_date = Carbon::parse($outstanding_invoice->date); $refund_end_date = $invoice_start_date->addSeconds($this->subscription->refund_period); } @@ -1282,11 +1210,8 @@ class SubscriptionService $recurring_invoice_repo->archive($recurring_invoice); /* Refund only if we are in the window - and there is nothing outstanding on the invoice */ - if($refund_end_date && $refund_end_date->greaterThan(now())) - { - - if($outstanding_invoice->payments()->exists()) - { + if ($refund_end_date && $refund_end_date->greaterThan(now())) { + if ($outstanding_invoice->payments()->exists()) { $payment = $outstanding_invoice->payments()->first(); $data = [ @@ -1305,50 +1230,44 @@ class SubscriptionService } } - $context = [ - 'context' => 'cancellation', - 'subscription' => $this->subscription->hashed_id, - 'recurring_invoice' => $recurring_invoice->hashed_id, - 'client' => $recurring_invoice->client->hashed_id, - 'contact' => auth()->guard('contact')->user()->hashed_id, - 'account_key' => $recurring_invoice->client->custom_value2, - ]; + $context = [ + 'context' => 'cancellation', + 'subscription' => $this->subscription->hashed_id, + 'recurring_invoice' => $recurring_invoice->hashed_id, + 'client' => $recurring_invoice->client->hashed_id, + 'contact' => auth()->guard('contact')->user()->hashed_id, + 'account_key' => $recurring_invoice->client->custom_value2, + ]; - $this->triggerWebhook($context); + $this->triggerWebhook($context); - $nmo = new NinjaMailerObject; - $nmo->mailable = (new NinjaMailer((new ClientContactRequestCancellationObject($recurring_invoice, auth()->guard('contact')->user(), $gateway_refund_attempted))->build())); - $nmo->company = $recurring_invoice->company; - $nmo->settings = $recurring_invoice->company->settings; + $nmo = new NinjaMailerObject; + $nmo->mailable = (new NinjaMailer((new ClientContactRequestCancellationObject($recurring_invoice, auth()->guard('contact')->user(), $gateway_refund_attempted))->build())); + $nmo->company = $recurring_invoice->company; + $nmo->settings = $recurring_invoice->company->settings; - $recurring_invoice->company->company_users->each(function ($company_user) use ($nmo){ + $recurring_invoice->company->company_users->each(function ($company_user) use ($nmo) { + $methods = $this->findCompanyUserNotificationType($company_user, ['recurring_cancellation', 'all_notifications']); - $methods = $this->findCompanyUserNotificationType($company_user, ['recurring_cancellation', 'all_notifications']); + //if mail is a method type -fire mail!! + if (($key = array_search('mail', $methods)) !== false) { + unset($methods[$key]); - //if mail is a method type -fire mail!! - if (($key = array_search('mail', $methods)) !== false) { - unset($methods[$key]); - - $nmo->to_user = $company_user->user; - NinjaMailerJob::dispatch($nmo); - - } - - - }); - - return $this->handleRedirect('client/subscriptions'); + $nmo->to_user = $company_user->user; + NinjaMailerJob::dispatch($nmo); + } + }); + return $this->handleRedirect('client/subscriptions'); } /** * Get the number of days in the currency frequency - * + * * @return int Number of days */ private function getDaysInFrequency() :int { - switch ($this->subscription->frequency_id) { case RecurringInvoice::FREQUENCY_DAILY: return 1; @@ -1377,15 +1296,14 @@ class SubscriptionService default: return 0; } - } /** * Get the next date by frequency_id - * + * * @param Carbon $date The current carbon date * @param int $frequency The frequncy_id of the subscription - * + * * @return ?Carbon The next date carbon object */ public function getNextDateForFrequency($date, $frequency) :?Carbon @@ -1417,7 +1335,7 @@ class SubscriptionService return $date->addYears(3); default: return null; - } + } } @@ -1426,15 +1344,15 @@ class SubscriptionService * @param Invoice $invoice The Invoice * @param array $bundle The bundle array * @param ClientContact $contact The Client Contact - * + * * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse */ public function handleNoPaymentFlow(Invoice $invoice, $bundle, ClientContact $contact) { - if (strlen($this->subscription->recurring_product_ids) >= 1) { - - $recurring_invoice = $this->convertInvoiceToRecurringBundle($contact->client_id, collect($bundle)->map(function ($bund){ return (object) $bund;})); + $recurring_invoice = $this->convertInvoiceToRecurringBundle($contact->client_id, collect($bundle)->map(function ($bund) { + return (object) $bund; + })); /* Start the recurring service */ $recurring_invoice->service() @@ -1457,13 +1375,11 @@ class SubscriptionService $this->triggerWebhook($context); return $this->handleRedirect($context['redirect_url']); - } $redirect_url = "/client/invoices/{$invoice->hashed_id}"; return $this->handleRedirect($redirect_url); - } /** @@ -1473,16 +1389,15 @@ class SubscriptionService */ public function handleNoPaymentRequired(array $data) { - $context = (new ZeroCostProduct($this->subscription, $data))->run(); // Forward payload to webhook - if(array_key_exists('context', $context)) + if (array_key_exists('context', $context)) { $response = $this->triggerWebhook($context); + } // Hit the redirect return $this->handleRedirect($context['redirect_url']); - } /** @@ -1490,31 +1405,31 @@ class SubscriptionService */ private function handleRedirect($default_redirect) { - - if(array_key_exists('return_url', $this->subscription->webhook_configuration) && strlen($this->subscription->webhook_configuration['return_url']) >=1) + if (array_key_exists('return_url', $this->subscription->webhook_configuration) && strlen($this->subscription->webhook_configuration['return_url']) >=1) { return redirect($this->subscription->webhook_configuration['return_url']); + } return redirect($default_redirect); } /** - * @param Invoice $invoice - * @return true - * @throws BindingResolutionException + * @param Invoice $invoice + * @return true + * @throws BindingResolutionException */ public function planPaid(Invoice $invoice) { $recurring_invoice_hashed_id = $invoice->recurring_invoice()->exists() ? $invoice->recurring_invoice->hashed_id : null; - $context = [ - 'context' => 'plan_paid', - 'subscription' => $this->subscription->hashed_id, - 'recurring_invoice' => $recurring_invoice_hashed_id, - 'client' => $invoice->client->hashed_id, - 'contact' => $invoice->client->primary_contact()->first() ? $invoice->client->primary_contact()->first()->hashed_id: $invoice->client->contacts->first()->hashed_id, - 'invoice' => $invoice->hashed_id, - 'account_key' => $invoice->client->custom_value2, - ]; + $context = [ + 'context' => 'plan_paid', + 'subscription' => $this->subscription->hashed_id, + 'recurring_invoice' => $recurring_invoice_hashed_id, + 'client' => $invoice->client->hashed_id, + 'contact' => $invoice->client->primary_contact()->first() ? $invoice->client->primary_contact()->first()->hashed_id: $invoice->client->contacts->first()->hashed_id, + 'invoice' => $invoice->hashed_id, + 'account_key' => $invoice->client->custom_value2, + ]; $response = $this->triggerWebhook($context); diff --git a/app/Services/TaskScheduler/TaskSchedulerService.php b/app/Services/TaskScheduler/TaskSchedulerService.php index 8bdf5f57b938..b5533ca8d2ee 100644 --- a/app/Services/TaskScheduler/TaskSchedulerService.php +++ b/app/Services/TaskScheduler/TaskSchedulerService.php @@ -25,25 +25,20 @@ use App\Export\CSV\QuoteItemExport; use App\Export\CSV\RecurringInvoiceExport; use App\Export\CSV\TaskExport; use App\Http\Requests\Report\GenericReportRequest; -use App\Http\Requests\Report\ProfitLossRequest; use App\Http\Requests\TaskScheduler\CreateScheduledTaskRequest; use App\Http\Requests\TaskScheduler\UpdateScheduledJobRequest; use App\Http\Requests\TaskScheduler\UpdateScheduleRequest; use App\Jobs\Report\ProfitAndLoss; -use App\Models\Company; use App\Models\Scheduler; -use App\Utils\Ninja; use Carbon\Carbon; -use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Validator; -use Symfony\Component\HttpFoundation\Request; - //@deprecated - never used.... class TaskSchedulerService { - - public function __construct(public Scheduler $scheduler) {} + public function __construct(public Scheduler $scheduler) + { + } public function store(Scheduler $scheduler, CreateScheduledTaskRequest $request) { @@ -152,7 +147,6 @@ class TaskSchedulerService $scheduler->action_class = $this->getClassPath(TaskExport::class); $scheduler->parameters = $this->runValidation(GenericReportRequest::class, $request->all()); break; - } return $scheduler; diff --git a/app/Services/User/UserService.php b/app/Services/User/UserService.php index 326348d1cdfb..c6be461916de 100644 --- a/app/Services/User/UserService.php +++ b/app/Services/User/UserService.php @@ -15,7 +15,6 @@ use App\Jobs\Mail\NinjaMailer; use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Mail\Admin\VerifyUserObject; -use App\Models\Company; use App\Models\User; use App\Utils\Ninja; diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php index 638fb3a66542..032324a0a23e 100644 --- a/app/Transformers/AccountTransformer.php +++ b/app/Transformers/AccountTransformer.php @@ -112,6 +112,5 @@ class AccountTransformer extends EntityTransformer $transformer = new UserTransformer($this->serializer); return $this->includeItem(auth()->user(), $transformer, User::class); - } } diff --git a/app/Transformers/ActivityTransformer.php b/app/Transformers/ActivityTransformer.php index 3b467aa0a639..9bcf5b66dd63 100644 --- a/app/Transformers/ActivityTransformer.php +++ b/app/Transformers/ActivityTransformer.php @@ -20,9 +20,6 @@ use App\Models\Task; use App\Models\User; use App\Models\Vendor; use App\Models\VendorContact; -use App\Transformers\PurchaseOrderTransformer; -use App\Transformers\VendorContactTransformer; -use App\Transformers\VendorTransformer; use App\Utils\Traits\MakesHash; class ActivityTransformer extends EntityTransformer diff --git a/app/Transformers/BankIntegrationTransformer.php b/app/Transformers/BankIntegrationTransformer.php index ad5275107330..b5eeb0ebea3c 100644 --- a/app/Transformers/BankIntegrationTransformer.php +++ b/app/Transformers/BankIntegrationTransformer.php @@ -88,5 +88,4 @@ class BankIntegrationTransformer extends EntityTransformer return $this->includeCollection($bank_integration->transactions, $transformer, BankTransaction::class); } - } diff --git a/app/Transformers/BankTransactionRuleTransformer.php b/app/Transformers/BankTransactionRuleTransformer.php index ca5628abb32b..588a802b492e 100644 --- a/app/Transformers/BankTransactionRuleTransformer.php +++ b/app/Transformers/BankTransactionRuleTransformer.php @@ -17,9 +17,6 @@ use App\Models\Client; use App\Models\Company; use App\Models\ExpenseCategory; use App\Models\Vendor; -use App\Transformers\ExpenseCategoryTransformer; -use App\Transformers\ExpenseCateogryTransformer; -use App\Transformers\VendorTransformer; use App\Utils\Traits\MakesHash; /** @@ -77,9 +74,9 @@ class BankTransactionRuleTransformer extends EntityTransformer public function includeClient(BankTransactionRule $bank_transaction_rule) { - - if(!$bank_transaction_rule->client) + if (!$bank_transaction_rule->client) { return null; + } $transformer = new ClientTransformer($this->serializer); @@ -88,9 +85,9 @@ class BankTransactionRuleTransformer extends EntityTransformer public function includeVendor(BankTransactionRule $bank_transaction_rule) { - - if(!$bank_transaction_rule->vendor) + if (!$bank_transaction_rule->vendor) { return null; + } $transformer = new VendorTransformer($this->serializer); @@ -99,13 +96,12 @@ class BankTransactionRuleTransformer extends EntityTransformer public function includeExpenseCategory(BankTransactionRule $bank_transaction_rule) { - - if(!$bank_transaction_rule->expense_category) + if (!$bank_transaction_rule->expense_category) { return null; + } $transformer = new ExpenseCategoryTransformer($this->serializer); return $this->includeItem($bank_transaction_rule->expense_category, $transformer, ExpenseCategory::class); } - } diff --git a/app/Transformers/BankTransactionTransformer.php b/app/Transformers/BankTransactionTransformer.php index 3aa95d6bcceb..b99aac92a702 100644 --- a/app/Transformers/BankTransactionTransformer.php +++ b/app/Transformers/BankTransactionTransformer.php @@ -15,8 +15,6 @@ use App\Models\Account; use App\Models\BankTransaction; use App\Models\Company; use App\Models\Expense; -use App\Models\Invoice; -use App\Transformers\VendorTransformer; use App\Utils\Traits\MakesHash; /** @@ -111,5 +109,4 @@ class BankTransactionTransformer extends EntityTransformer return $this->includeItem($bank_transaction->payment, $transformer, Payment::class); } - } diff --git a/app/Transformers/CompanyGatewayTransformer.php b/app/Transformers/CompanyGatewayTransformer.php index 6ac1aed2aeab..d1f214086512 100644 --- a/app/Transformers/CompanyGatewayTransformer.php +++ b/app/Transformers/CompanyGatewayTransformer.php @@ -13,7 +13,6 @@ namespace App\Transformers; use App\Models\CompanyGateway; use App\Models\SystemLog; -use App\Transformers\SystemLogTransformer; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\SoftDeletes; use stdClass; diff --git a/app/Transformers/CompanyTransformer.php b/app/Transformers/CompanyTransformer.php index fee6318ce638..a167c6812fd7 100644 --- a/app/Transformers/CompanyTransformer.php +++ b/app/Transformers/CompanyTransformer.php @@ -43,11 +43,6 @@ use App\Models\TaskStatus; use App\Models\TaxRate; use App\Models\User; use App\Models\Webhook; -use App\Transformers\BankIntegrationTransformer; -use App\Transformers\BankTransactionRuleTransformer; -use App\Transformers\BankTransactionTransformer; -use App\Transformers\PurchaseOrderTransformer; -use App\Transformers\RecurringExpenseTransformer; use App\Utils\Traits\MakesHash; use stdClass; diff --git a/app/Transformers/CreditTransformer.php b/app/Transformers/CreditTransformer.php index 7050003bfd98..4846b56a336e 100644 --- a/app/Transformers/CreditTransformer.php +++ b/app/Transformers/CreditTransformer.php @@ -16,7 +16,6 @@ use App\Models\Backup; use App\Models\Credit; use App\Models\CreditInvitation; use App\Models\Document; -use App\Transformers\ActivityTransformer; use App\Utils\Traits\MakesHash; use League\Fractal\Resource\Item; diff --git a/app/Transformers/GroupSettingTransformer.php b/app/Transformers/GroupSettingTransformer.php index 5bea9f734d74..3a7695ccee8a 100644 --- a/app/Transformers/GroupSettingTransformer.php +++ b/app/Transformers/GroupSettingTransformer.php @@ -13,7 +13,6 @@ namespace App\Transformers; use App\Models\Document; use App\Models\GroupSetting; -use App\Transformers\DocumentTransformer; use App\Utils\Traits\MakesHash; use stdClass; diff --git a/app/Transformers/InvoiceTransformer.php b/app/Transformers/InvoiceTransformer.php index 7da68ad9aa64..a35e1d4c2082 100644 --- a/app/Transformers/InvoiceTransformer.php +++ b/app/Transformers/InvoiceTransformer.php @@ -18,7 +18,6 @@ use App\Models\Document; use App\Models\Invoice; use App\Models\InvoiceInvitation; use App\Models\Payment; -use App\Transformers\ActivityTransformer; use App\Utils\Traits\MakesHash; class InvoiceTransformer extends EntityTransformer diff --git a/app/Transformers/PurchaseOrderTransformer.php b/app/Transformers/PurchaseOrderTransformer.php index 14ad85b57fa7..360e1edcf922 100644 --- a/app/Transformers/PurchaseOrderTransformer.php +++ b/app/Transformers/PurchaseOrderTransformer.php @@ -11,11 +11,9 @@ namespace App\Transformers; - use App\Models\PurchaseOrder; use App\Models\PurchaseOrderInvitation; use App\Models\Vendor; -use App\Transformers\DocumentTransformer; use App\Utils\Traits\MakesHash; class PurchaseOrderTransformer extends EntityTransformer @@ -135,5 +133,4 @@ class PurchaseOrderTransformer extends EntityTransformer 'currency_id' => $purchase_order->currency_id ? (string) $purchase_order->currency_id : '', ]; } - } diff --git a/app/Transformers/QuoteTransformer.php b/app/Transformers/QuoteTransformer.php index 60b08c1aa18e..ca2d092057fd 100644 --- a/app/Transformers/QuoteTransformer.php +++ b/app/Transformers/QuoteTransformer.php @@ -16,7 +16,6 @@ use App\Models\Backup; use App\Models\Document; use App\Models\Quote; use App\Models\QuoteInvitation; -use App\Transformers\ActivityTransformer; use App\Utils\Traits\MakesHash; use League\Fractal\Resource\Item; diff --git a/app/Transformers/RecurringInvoiceTransformer.php b/app/Transformers/RecurringInvoiceTransformer.php index ba3b81ad6d0d..5fcd576d89fe 100644 --- a/app/Transformers/RecurringInvoiceTransformer.php +++ b/app/Transformers/RecurringInvoiceTransformer.php @@ -15,12 +15,8 @@ use App\Models\Activity; use App\Models\Backup; use App\Models\Client; use App\Models\Document; -use App\Models\Invoice; use App\Models\RecurringInvoice; use App\Models\RecurringInvoiceInvitation; -use App\Transformers\ActivityTransformer; -use App\Transformers\ClientTransformer; -use App\Transformers\InvoiceHistoryTransformer; use App\Utils\Traits\MakesHash; class RecurringInvoiceTransformer extends EntityTransformer diff --git a/app/Transformers/RecurringQuoteTransformer.php b/app/Transformers/RecurringQuoteTransformer.php index 8cd884f805d5..905329c2282e 100644 --- a/app/Transformers/RecurringQuoteTransformer.php +++ b/app/Transformers/RecurringQuoteTransformer.php @@ -14,11 +14,8 @@ namespace App\Transformers; use App\Models\Activity; use App\Models\Backup; use App\Models\Document; -use App\Models\Quote; use App\Models\RecurringQuote; use App\Models\RecurringQuoteInvitation; -use App\Transformers\ActivityTransformer; -use App\Transformers\QuoteHistoryTransformer; use App\Utils\Traits\MakesHash; class RecurringQuoteTransformer extends EntityTransformer diff --git a/app/Transformers/TaskTransformer.php b/app/Transformers/TaskTransformer.php index 4f18d54fdeb4..71b6d7c3436b 100644 --- a/app/Transformers/TaskTransformer.php +++ b/app/Transformers/TaskTransformer.php @@ -14,7 +14,6 @@ namespace App\Transformers; use App\Models\Document; use App\Models\Task; use App\Models\TaskStatus; -use App\Transformers\TaskStatusTransformer; use App\Utils\Traits\MakesHash; use League\Fractal\Resource\Item; @@ -48,8 +47,9 @@ class TaskTransformer extends EntityTransformer { $transformer = new ClientTransformer($this->serializer); - if(!$task->client) + if (!$task->client) { return null; + } return $this->includeItem($task->client, $transformer, Client::class); } @@ -58,8 +58,9 @@ class TaskTransformer extends EntityTransformer { $transformer = new TaskStatusTransformer($this->serializer); - if(!$task->status) + if (!$task->status) { return null; + } return $this->includeItem($task->status, $transformer, TaskStatus::class); } diff --git a/app/Utils/Helpers.php b/app/Utils/Helpers.php index 92b41c6ed83a..5bef865ce085 100644 --- a/app/Utils/Helpers.php +++ b/app/Utils/Helpers.php @@ -118,17 +118,15 @@ class Helpers // 04-10-2022 Return Early if no reserved keywords are present, this is a very expensive process $string_hit = false; - foreach ( [':MONTH',':YEAR',':QUARTER',':WEEK'] as $string ) - { - - if(stripos($value, $string) !== FALSE) { - $string_hit = true; + foreach ([':MONTH',':YEAR',':QUARTER',':WEEK'] as $string) { + if (stripos($value, $string) !== false) { + $string_hit = true; } - } - if(!$string_hit) + if (!$string_hit) { return $value; + } // 04-10-2022 Return Early if no reserved keywords are present, this is a very expensive process Carbon::setLocale($entity->locale()); @@ -248,7 +246,10 @@ class Helpers $replacement = sprintf('%s to %s', $_left, $_right); $value = preg_replace( - sprintf('/%s/', preg_quote($match)), $replacement, $value, 1 + sprintf('/%s/', preg_quote($match)), + $replacement, + $value, + 1 ); } } @@ -269,7 +270,10 @@ class Helpers if (! Str::contains($match, ['-', '+', '/', '*'])) { $value = preg_replace( - sprintf('/%s/', $matches->keys()->first()), $replacements['literal'][$matches->keys()->first()], $value, 1 + sprintf('/%s/', $matches->keys()->first()), + $replacements['literal'][$matches->keys()->first()], + $value, + 1 ); } @@ -312,20 +316,22 @@ class Helpers $final_date = $currentDateTime->copy()->addMonths($output - $currentDateTime->month); $output = \sprintf( - '%s %s', - $final_date->translatedFormat('F'), - $final_date->year, - ); + '%s %s', + $final_date->translatedFormat('F'), + $final_date->year, + ); } $value = preg_replace( - $target, $output, $value, 1 + $target, + $output, + $value, + 1 ); } } return $value; - } /** diff --git a/app/Utils/HtmlEngine.php b/app/Utils/HtmlEngine.php index aea963783fa1..f528512f21ab 100644 --- a/app/Utils/HtmlEngine.php +++ b/app/Utils/HtmlEngine.php @@ -20,8 +20,6 @@ use App\Models\GatewayType; use App\Models\InvoiceInvitation; use App\Models\QuoteInvitation; use App\Models\RecurringInvoiceInvitation; -use App\Utils\Ninja; -use App\Utils\Number; use App\Utils\Traits\AppSetup; use App\Utils\Traits\DesignCalculator; use App\Utils\Traits\MakesDates; @@ -67,7 +65,7 @@ class HtmlEngine $this->contact = $invitation->contact->load('client'); - $this->client = $this->contact->client->load('company','country'); + $this->client = $this->contact->client->load('company', 'country'); $this->entity->load('client'); @@ -187,29 +185,26 @@ class HtmlEngine $data['$credit.custom3'] = &$data['$invoice.custom3']; $data['$credit.custom4'] = &$data['$invoice.custom4']; - if($this->entity->project) { + if ($this->entity->project) { $data['$project.name'] = ['value' => $this->entity->project->name, 'label' => ctrans('texts.project')]; $data['$invoice.project'] = &$data['$project.name']; } - if($this->entity->status_id == 4) { + if ($this->entity->status_id == 4) { $data['$status_logo'] = ['value' => '
' . ctrans('texts.paid') .'
', 'label' => '']; } - if($this->entity->vendor) { + if ($this->entity->vendor) { $data['$invoice.vendor'] = ['value' => $this->entity->vendor->present()->name(), 'label' => ctrans('texts.vendor_name')]; } - if(strlen($this->company->getSetting('qr_iban')) > 5) - { - try{ + if (strlen($this->company->getSetting('qr_iban')) > 5) { + try { $data['$swiss_qr'] = ['value' => (new SwissQrGenerator($this->entity, $this->company))->run(), 'label' => '']; - } - catch(\Exception $e){ + } catch(\Exception $e) { $data['$swiss_qr'] = ['value' => '', 'label' => '']; } } - } if ($this->entity_string == 'quote') { @@ -246,15 +241,14 @@ class HtmlEngine $data['$credit.custom3'] = &$data['$quote.custom3']; $data['$credit.custom4'] = &$data['$quote.custom4']; - if($this->entity->project) { + if ($this->entity->project) { $data['$project.name'] = ['value' => $this->entity->project->name, 'label' => ctrans('texts.project_name')]; $data['$invoice.project'] = &$data['$project.name']; } - if($this->entity->vendor) { + if ($this->entity->vendor) { $data['$invoice.vendor'] = ['value' => $this->entity->vendor->present()->name(), 'label' => ctrans('texts.vendor_name')]; } - } if ($this->entity_string == 'credit') { @@ -290,7 +284,6 @@ class HtmlEngine $data['$invoice.custom2'] = &$data['$credit.custom2']; $data['$invoice.custom3'] = &$data['$credit.custom3']; $data['$invoice.custom4'] = &$data['$credit.custom4']; - } $data['$portal_url'] = ['value' => $this->invitation->getPortalLink(), 'label' =>'']; @@ -301,10 +294,11 @@ class HtmlEngine $data['$subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getSubTotal(), $this->client) ?: ' ', 'label' => ctrans('texts.subtotal')]; $data['$gross_subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getGrossSubTotal(), $this->client) ?: ' ', 'label' => ctrans('texts.subtotal')]; - if($this->entity->uses_inclusive_taxes) + if ($this->entity->uses_inclusive_taxes) { $data['$net_subtotal'] = ['value' => Number::formatMoney(($this->entity_calc->getSubTotal() - $this->entity->total_taxes - $this->entity_calc->getTotalDiscount()), $this->client) ?: ' ', 'label' => ctrans('texts.net_subtotal')]; - else + } else { $data['$net_subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getSubTotal() - $this->entity_calc->getTotalDiscount(), $this->client) ?: ' ', 'label' => ctrans('texts.net_subtotal')]; + } $data['$invoice.subtotal'] = &$data['$subtotal']; @@ -314,15 +308,12 @@ class HtmlEngine $data['$balance_due_raw'] = ['value' => $this->entity->partial, 'label' => ctrans('texts.partial_due')]; $data['$amount_raw'] = ['value' => $this->entity->partial, 'label' => ctrans('texts.partial_due')]; $data['$due_date'] = ['value' => $this->translateDate($this->entity->partial_due_date, $this->client->date_format(), $this->client->locale()) ?: ' ', 'label' => ctrans('texts.'.$this->entity_string.'_due_date')]; - } else { - - if($this->entity->status_id == 1){ + if ($this->entity->status_id == 1) { $data['$balance_due'] = ['value' => Number::formatMoney($this->entity->amount, $this->client) ?: ' ', 'label' => ctrans('texts.balance_due')]; $data['$balance_due_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.balance_due')]; $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')]; - } - else{ + } else { $data['$balance_due'] = ['value' => Number::formatMoney($this->entity->balance, $this->client) ?: ' ', 'label' => ctrans('texts.balance_due')]; $data['$balance_due_raw'] = ['value' => $this->entity->balance, 'label' => ctrans('texts.balance_due')]; $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')]; @@ -336,13 +327,13 @@ class HtmlEngine if ($this->entity_string == 'credit') { $data['$balance_due'] = ['value' => Number::formatMoney($this->entity->balance, $this->client) ?: ' ', 'label' => ctrans('texts.credit_balance')]; $data['$balance_due_raw'] = ['value' => $this->entity->balance, 'label' => ctrans('texts.credit_balance')]; - $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')]; + $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')]; } if ($this->entity_string == 'credit' && $this->entity->status_id == 1) { $data['$balance_due'] = ['value' => Number::formatMoney($this->entity->amount, $this->client) ?: ' ', 'label' => ctrans('texts.credit_balance')]; $data['$balance_due_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.credit_balance')]; - $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')]; + $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')]; } /* Do not change the order of these */ @@ -425,8 +416,9 @@ class HtmlEngine $data['$country_2'] = ['value' => isset($this->client->country) ? $this->client->country->iso_3166_2 : '', 'label' => ctrans('texts.country')]; $data['$email'] = ['value' => isset($this->contact) ? $this->contact->email : 'no contact email on record', 'label' => ctrans('texts.email')]; - if(str_contains($data['$email']['value'], 'example.com')) + if (str_contains($data['$email']['value'], 'example.com')) { $data['$email'] = ['value' => '', 'label' => ctrans('texts.email')]; + } $data['$client_name'] = ['value' => $this->entity->present()->clientName() ?: ' ', 'label' => ctrans('texts.client_name')]; $data['$client.name'] = &$data['$client_name']; @@ -642,7 +634,6 @@ class HtmlEngine $data['$payments'] = ['value' => '', 'label' => ctrans('texts.payments')]; if ($this->entity_string == 'invoice' && $this->entity->payments()->exists()) { - $payment_list = '

'; foreach ($this->entity->payments as $payment) { @@ -652,9 +643,8 @@ class HtmlEngine $data['$payments'] = ['value' => $payment_list, 'label' => ctrans('texts.payments')]; } - if(($this->entity_string == 'invoice' || $this->entity_string == 'recurring_invoice') && isset($this->company?->custom_fields?->company1)) - { - $data['$sepa_qr_code'] = ['value' => (new EpcQrGenerator($this->company, $this->entity,$data['$amount_raw']['value']))->getQrCode(), 'label' => '']; + if (($this->entity_string == 'invoice' || $this->entity_string == 'recurring_invoice') && isset($this->company?->custom_fields?->company1)) { + $data['$sepa_qr_code'] = ['value' => (new EpcQrGenerator($this->company, $this->entity, $data['$amount_raw']['value']))->getQrCode(), 'label' => '']; } $arrKeysLength = array_map('strlen', array_keys($data)); @@ -735,27 +725,21 @@ class HtmlEngine private function getCountryName() :string { - $countries = Cache::get('countries'); if (! $countries) { $this->buildCache(true); $countries = Cache::get('countries'); - } - if($countries){ - - + if ($countries) { $country = $countries->filter(function ($item) { return $item->id == $this->settings->country_id; })->first(); - - - } - else + } else { $country = Country::find($this->settings->country_id); + } if ($country) { return ctrans('texts.country_' . $country->name); @@ -769,8 +753,9 @@ class HtmlEngine { $country = Country::find($this->settings->country_id); - if($country) + if ($country) { return $country->iso_3166_2; + } // if ($country) { // return ctrans('texts.country_' . $country->iso_3166_2); // } @@ -948,8 +933,8 @@ html { /** * Generate markup for HTML images on entity. - * - * @return string|void + * + * @return string|void */ protected function generateEntityImagesMarkup() { diff --git a/app/Utils/Ninja.php b/app/Utils/Ninja.php index b66d40b8260d..3274983d540e 100644 --- a/app/Utils/Ninja.php +++ b/app/Utils/Ninja.php @@ -193,8 +193,7 @@ class Ninja */ public static function isBase64Encoded(string $s) : bool { - - // Check if there are valid base64 characters + // Check if there are valid base64 characters if (! preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s)) { return false; } diff --git a/app/Utils/Number.php b/app/Utils/Number.php index e2891b7c54b9..4d23798394c6 100644 --- a/app/Utils/Number.php +++ b/app/Utils/Number.php @@ -13,7 +13,6 @@ namespace App\Utils; use App\Models\Company; use App\Models\Currency; -use App\Models\Vendor; /** * Class Number. @@ -136,7 +135,6 @@ class Number */ public static function formatMoney($value, $entity) :string { - $value = floatval($value); $currency = $entity->currency(); @@ -227,8 +225,7 @@ class Number /* 08-02-2023 special if block to render $0.5 to $0.50*/ if ($v < 1 && strlen($v) == 3) { $precision = 2; - } - elseif ($v < 1) { + } elseif ($v < 1) { $precision = strlen($v) - strrpos($v, '.') - 1; } diff --git a/app/Utils/PhantomJS/Phantom.php b/app/Utils/PhantomJS/Phantom.php index 0ec93ddcdc32..00b3b206b55e 100644 --- a/app/Utils/PhantomJS/Phantom.php +++ b/app/Utils/PhantomJS/Phantom.php @@ -27,7 +27,6 @@ use App\Utils\HtmlEngine; use App\Utils\Traits\MakesHash; use App\Utils\Traits\Pdf\PageNumbering; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Response; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; @@ -112,8 +111,9 @@ class Phantom $instance = Storage::disk(config('filesystems.default'))->put($file_path, $pdf); - if($return_pdf) + if ($return_pdf) { return $pdf; + } return $file_path; } diff --git a/app/Utils/Statics.php b/app/Utils/Statics.php index f1d6e86d96e5..cd6f9bcdd3f6 100644 --- a/app/Utils/Statics.php +++ b/app/Utils/Statics.php @@ -71,7 +71,6 @@ class Statics foreach (config('ninja.cached_tables') as $name => $class) { if (! Cache::has($name)) { - // check that the table exists in case the migration is pending if (! Schema::hasTable((new $class())->getTable())) { continue; diff --git a/app/Utils/SystemHealth.php b/app/Utils/SystemHealth.php index 04e4165a1255..be4fce4fa454 100644 --- a/app/Utils/SystemHealth.php +++ b/app/Utils/SystemHealth.php @@ -13,7 +13,6 @@ namespace App\Utils; use App\Libraries\MultiDB; use App\Mail\TestMailServer; -use App\Models\Company; use Exception; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; @@ -89,33 +88,30 @@ class SystemHealth private static function checkCurrencySanity() { - - if(!self::simpleDbCheck()) + if (!self::simpleDbCheck()) { return true; - - if(strlen(config('ninja.currency_converter_api_key')) == 0){ - - try{ - $cs = DB::table('clients') - ->select('settings->currency_id as id') - ->get(); - } - catch(\Exception $e){ - return true; //fresh installs, there may be no DB connection, nor migrations could have run yet. } - $currency_count = $cs->unique('id')->filter(function ($value){ - return !is_null($value->id); - })->count(); + if (strlen(config('ninja.currency_converter_api_key')) == 0) { + try { + $cs = DB::table('clients') + ->select('settings->currency_id as id') + ->get(); + } catch(\Exception $e) { + return true; //fresh installs, there may be no DB connection, nor migrations could have run yet. + } + + $currency_count = $cs->unique('id')->filter(function ($value) { + return !is_null($value->id); + })->count(); - if($currency_count > 1) + if ($currency_count > 1) { return true; - + } } return false; - } private static function checkQueueSize() @@ -217,8 +213,9 @@ class SystemHealth private static function checkPhpCli() { - if(!function_exists('exec')) + if (!function_exists('exec')) { return "Unable to check CLI version"; + } try { exec('php -v', $foo, $exitCode); @@ -278,7 +275,7 @@ class SystemHealth $x = DB::connection()->getDatabaseName(); $result['success'] = true; } catch (Exception $e) { - // $x = [config('database.connections.'.config('database.default').'.database') => false]; + // $x = [config('database.connections.'.config('database.default').'.database') => false]; $result['success'] = false; $result['message'] = $e->getMessage(); } diff --git a/app/Utils/TemplateEngine.php b/app/Utils/TemplateEngine.php index 31e8d23eb199..ca10200a882e 100644 --- a/app/Utils/TemplateEngine.php +++ b/app/Utils/TemplateEngine.php @@ -26,17 +26,13 @@ use App\Models\QuoteInvitation; use App\Models\Vendor; use App\Models\VendorContact; use App\Services\PdfMaker\Designs\Utilities\DesignHelpers; -use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use App\Utils\Traits\MakesInvoiceHtml; use App\Utils\Traits\MakesTemplateData; -use App\Utils\VendorHtmlEngine; use DB; use Illuminate\Support\Facades\App; -use Illuminate\Support\Facades\Lang; use Illuminate\Support\Str; use League\CommonMark\CommonMarkConverter; -use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles; class TemplateEngine { @@ -88,7 +84,6 @@ class TemplateEngine public function build() { - return $this->setEntity() ->setSettingsObject() ->setTemplates() @@ -188,12 +183,13 @@ class TemplateEngine private function entityValues($contact) { - if (in_array($this->entity, ['purchaseOrder', 'purchase_order'])) + if (in_array($this->entity, ['purchaseOrder', 'purchase_order'])) { $this->labels_and_values = (new VendorHtmlEngine($this->entity_obj->invitations->first()))->generateLabelsAndValues(); - elseif($this->entity == 'payment') + } elseif ($this->entity == 'payment') { $this->labels_and_values = (new PaymentEmailEngine($this->entity_obj, $this->entity_obj->client->contacts->first()))->generateLabelsAndValues(); - else + } else { $this->labels_and_values = (new HtmlEngine($this->entity_obj->invitations->first()))->generateLabelsAndValues(); + } $this->body = strtr($this->body, $this->labels_and_values['labels']); @@ -219,10 +215,9 @@ class TemplateEngine $data['footer'] = ''; $data['logo'] = auth()->user()->company()->present()->logo(); - if ($this->entity_obj->client()->exists()) + if ($this->entity_obj->client()->exists()) { $data = array_merge($data, Helpers::sharedEmailVariables($this->entity_obj->client)); - else { - + } else { $data['signature'] = $this->settings->email_signature; $data['settings'] = $this->settings; $data['whitelabel'] = $this->entity_obj ? $this->entity_obj->company->account->isPaid() : true; @@ -269,10 +264,11 @@ class TemplateEngine private function mockEntity() { - if (!$this->entity && $this->template && str_contains($this->template, 'purchase_order')) + if (!$this->entity && $this->template && str_contains($this->template, 'purchase_order')) { $this->entity = 'purchaseOrder'; - elseif(str_contains($this->template, 'payment')) + } elseif (str_contains($this->template, 'payment')) { $this->entity = 'payment'; + } DB::connection(config('database.default'))->beginTransaction(); @@ -292,8 +288,6 @@ class TemplateEngine ]); if ($this->entity == 'payment') { - - $this->entity_obj = Payment::factory()->create([ 'user_id' => auth()->user()->id, 'company_id' => auth()->user()->company()->id, @@ -309,7 +303,7 @@ class TemplateEngine 'client_id' => $client->id, 'amount' => 10, 'balance' => 10, - 'number' => rand(1,10000) + 'number' => rand(1, 10000) ]); $invitation = InvoiceInvitation::factory()->create([ @@ -322,7 +316,6 @@ class TemplateEngine $this->entity_obj->invoices()->attach($invoice->id, [ 'amount' => 10, ]); - } if (!$this->entity || $this->entity == 'invoice') { @@ -356,7 +349,6 @@ class TemplateEngine } if ($this->entity == 'purchaseOrder') { - $vendor = Vendor::factory()->create([ 'user_id' => auth()->user()->id, 'company_id' => auth()->user()->company()->id, @@ -386,7 +378,6 @@ class TemplateEngine } if ($vendor) { - $this->entity_obj->setRelation('invitations', $invitation); $this->entity_obj->setRelation('vendor', $vendor); $this->entity_obj->setRelation('company', auth()->user()->company()); diff --git a/app/Utils/Traits/AppSetup.php b/app/Utils/Traits/AppSetup.php index c2a04d631a53..97f6cc6c47c6 100644 --- a/app/Utils/Traits/AppSetup.php +++ b/app/Utils/Traits/AppSetup.php @@ -14,9 +14,7 @@ namespace App\Utils\Traits; use App\DataMapper\EmailTemplateDefaults; use App\Utils\Ninja; use App\Utils\SystemHealth; -use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\Schema; use Illuminate\Support\Str; trait AppSetup @@ -38,7 +36,6 @@ trait AppSetup foreach ($cached_tables as $name => $class) { if (! Cache::has($name) || $force) { - if ($name == 'payment_terms') { $orderBy = 'num_days'; } elseif ($name == 'fonts') { diff --git a/app/Utils/Traits/CleanLineItems.php b/app/Utils/Traits/CleanLineItems.php index 8eed99a8c6f8..4e16d287326f 100644 --- a/app/Utils/Traits/CleanLineItems.php +++ b/app/Utils/Traits/CleanLineItems.php @@ -46,7 +46,6 @@ trait CleanLineItems unset($invoice_item->casts); foreach ($invoice_item as $key => $value) { - //if the key has not been set, we set it to a default value if (! array_key_exists($key, $item) || ! isset($item[$key])) { $item[$key] = $value; diff --git a/app/Utils/Traits/ClientGroupSettingsSaver.php b/app/Utils/Traits/ClientGroupSettingsSaver.php index 2bfe99f8fd2c..fa9d5fca2ae3 100644 --- a/app/Utils/Traits/ClientGroupSettingsSaver.php +++ b/app/Utils/Traits/ClientGroupSettingsSaver.php @@ -11,7 +11,6 @@ namespace App\Utils\Traits; -use App\DataMapper\ClientSettings; use App\DataMapper\CompanySettings; use stdClass; @@ -234,7 +233,7 @@ trait ClientGroupSettingsSaver case 'json': json_decode($value); - return json_last_error() == JSON_ERROR_NONE; + return json_last_error() == JSON_ERROR_NONE; default: return false; } diff --git a/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php b/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php index 28e3e1069d9f..2b4a894094f1 100644 --- a/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php +++ b/app/Utils/Traits/CompanyGatewayFeesAndLimitsSaver.php @@ -62,7 +62,7 @@ trait CompanyGatewayFeesAndLimitsSaver case 'real': case 'float': case 'double': - return ! is_string($value) && (is_float($value) || is_numeric(strval($value))); + return ! is_string($value) && (is_float($value) || is_numeric(strval($value))); // return is_float($value) || is_numeric(strval($value)); case 'string': return (is_string($value) && method_exists($value, '__toString')) || is_null($value) || is_string($value); @@ -76,7 +76,7 @@ trait CompanyGatewayFeesAndLimitsSaver case 'json': json_decode($value); - return json_last_error() == JSON_ERROR_NONE; + return json_last_error() == JSON_ERROR_NONE; default: return false; } diff --git a/app/Utils/Traits/CompanySettingsSaver.php b/app/Utils/Traits/CompanySettingsSaver.php index 5f2ff03025db..6f0c3217df8f 100644 --- a/app/Utils/Traits/CompanySettingsSaver.php +++ b/app/Utils/Traits/CompanySettingsSaver.php @@ -36,7 +36,6 @@ trait CompanySettingsSaver */ public function saveSettings($settings, $entity) { - /* No Settings, No Save!*/ if (! $settings) { return; @@ -114,8 +113,9 @@ trait CompanySettingsSaver elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter') { $value = 'integer'; - if($key == 'besr_id') + if ($key == 'besr_id') { $value = 'string'; + } if (! property_exists($settings, $key)) { continue; @@ -185,8 +185,9 @@ trait CompanySettingsSaver $value = 'string'; } - if($key == 'besr_id') + if ($key == 'besr_id') { $value = 'string'; + } if (! property_exists($settings, $key)) { continue; @@ -260,7 +261,7 @@ trait CompanySettingsSaver case 'json': json_decode($value); - return json_last_error() == JSON_ERROR_NONE; + return json_last_error() == JSON_ERROR_NONE; default: return false; } diff --git a/app/Utils/Traits/DesignCalculator.php b/app/Utils/Traits/DesignCalculator.php index 97e887dfe39f..83bf016a13d3 100644 --- a/app/Utils/Traits/DesignCalculator.php +++ b/app/Utils/Traits/DesignCalculator.php @@ -13,7 +13,6 @@ namespace App\Utils\Traits; trait DesignCalculator { - private function resolveCompanyLogoSize() { $design_map = [ @@ -48,23 +47,26 @@ trait DesignCalculator "11221" => "65%", //"C-DB1" ]; - if(isset($this->settings->company_logo_size) && strlen($this->settings->company_logo_size) > 1) + if (isset($this->settings->company_logo_size) && strlen($this->settings->company_logo_size) > 1) { return $this->settings->company_logo_size; + } - if($this->entity->design_id && array_key_exists($this->entity->design_id, $design_int_map)) + if ($this->entity->design_id && array_key_exists($this->entity->design_id, $design_int_map)) { return $design_int_map[$this->entity->design_id]; + } $default_design_id = $this->entity_string."_design_id"; - if($default_design_id == 'recurring_invoice_design_id') + if ($default_design_id == 'recurring_invoice_design_id') { $default_design_id = 'invoice_design_id'; + } $design_id = $this->settings->{$default_design_id}; - if(array_key_exists($design_id, $design_map)) + if (array_key_exists($design_id, $design_map)) { return $design_map[$design_id]; + } return '65%'; - } -} \ No newline at end of file +} diff --git a/app/Utils/Traits/GeneratesConvertedQuoteCounter.php b/app/Utils/Traits/GeneratesConvertedQuoteCounter.php index 4de13e640f93..1c331694d46a 100644 --- a/app/Utils/Traits/GeneratesConvertedQuoteCounter.php +++ b/app/Utils/Traits/GeneratesConvertedQuoteCounter.php @@ -33,7 +33,6 @@ use Illuminate\Support\Str; */ trait GeneratesConvertedQuoteCounter { - private int $update_counter; private function harvestQuoteCounter($quote, $invoice, Client $client) @@ -369,8 +368,7 @@ trait GeneratesConvertedQuoteCounter } //if ($type == 'credit') { - return (bool) $client->getSetting('shared_invoice_credit_counter'); - + return (bool) $client->getSetting('shared_invoice_credit_counter'); } /** @@ -479,15 +477,12 @@ trait GeneratesConvertedQuoteCounter $reset_counter_frequency = (int) $client->getSetting('reset_counter_frequency_id'); if ($reset_counter_frequency == 0) { - - if($client->getSetting('reset_counter_date')){ - - $settings = $client->company->settings; - $settings->reset_counter_date = ""; - $client->company->settings = $settings; - $client->company->save(); - - } + if ($client->getSetting('reset_counter_date')) { + $settings = $client->company->settings; + $settings->reset_counter_date = ""; + $client->company->settings = $settings; + $client->company->save(); + } return; } @@ -536,7 +531,7 @@ trait GeneratesConvertedQuoteCounter $new_reset_date = $reset_date->addYears(2); break; - default: + default: $new_reset_date = $reset_date->addYear(); break; } diff --git a/app/Utils/Traits/GeneratesCounter.php b/app/Utils/Traits/GeneratesCounter.php index 0b67f9a124e1..b4596f981cfa 100644 --- a/app/Utils/Traits/GeneratesCounter.php +++ b/app/Utils/Traits/GeneratesCounter.php @@ -34,7 +34,6 @@ use Illuminate\Support\Str; */ trait GeneratesCounter { - private int $update_counter; //todo in the form validation, we need to ensure that if a prefix and pattern is set we throw a validation error, @@ -161,7 +160,6 @@ trait GeneratesCounter default: return 'default_number_counter'; - } } @@ -400,7 +398,7 @@ trait GeneratesCounter } //credit - return (bool) $client->getSetting('shared_invoice_credit_counter'); + return (bool) $client->getSetting('shared_invoice_credit_counter'); } /** @@ -421,7 +419,6 @@ trait GeneratesCounter $check_counter = 1; do { - $number = $this->padCounter($counter, $padding); $number = $this->applyNumberPattern($entity, $number, $pattern); @@ -434,13 +431,10 @@ trait GeneratesCounter $check_counter++; if ($check_counter > 100) { - $this->update_counter = $counter--; return $number.'_'.Str::random(5); - } - } while ($check); $this->update_counter = $counter--; @@ -518,15 +512,12 @@ trait GeneratesCounter $reset_counter_frequency = (int) $client->getSetting('reset_counter_frequency_id'); if ($reset_counter_frequency == 0) { - - if($client->getSetting('reset_counter_date')){ - - $settings = $client->company->settings; - $settings->reset_counter_date = ""; - $client->company->settings = $settings; - $client->company->save(); - - } + if ($client->getSetting('reset_counter_date')) { + $settings = $client->company->settings; + $settings->reset_counter_date = ""; + $client->company->settings = $settings; + $client->company->save(); + } return; } @@ -574,7 +565,7 @@ trait GeneratesCounter $new_reset_date = $reset_date->addYears(2); break; - default: + default: $new_reset_date = $reset_date->addYear(); break; } @@ -611,14 +602,11 @@ trait GeneratesCounter $reset_counter_frequency = (int) $settings->reset_counter_frequency_id; if ($reset_counter_frequency == 0) { - - if($settings->reset_counter_date){ - - $settings->reset_counter_date = ""; - $company->settings = $settings; - $company->save(); - - } + if ($settings->reset_counter_date) { + $settings->reset_counter_date = ""; + $company->settings = $settings; + $company->save(); + } return; } @@ -658,7 +646,7 @@ trait GeneratesCounter $new_reset_date = $reset_date->addYears(2); break; - default: + default: $new_reset_date = $reset_date->addYear(); break; } diff --git a/app/Utils/Traits/Inviteable.php b/app/Utils/Traits/Inviteable.php index 161d66587f45..5fd1efbbca4b 100644 --- a/app/Utils/Traits/Inviteable.php +++ b/app/Utils/Traits/Inviteable.php @@ -12,12 +12,11 @@ namespace App\Utils\Traits; use App\Utils\Ninja; -use Illuminate\Support\Str; -use BaconQrCode\Renderer\ImageRenderer; use BaconQrCode\Renderer\Image\SvgImageBackEnd; +use BaconQrCode\Renderer\ImageRenderer; use BaconQrCode\Renderer\RendererStyle\RendererStyle; use BaconQrCode\Writer; - +use Illuminate\Support\Str; /** * Class Inviteable. @@ -61,7 +60,6 @@ trait Inviteable public function getPaymentQrCode() { - $renderer = new ImageRenderer( new RendererStyle(200), new SvgImageBackEnd() @@ -72,7 +70,6 @@ trait Inviteable return " {$qr}"; - } public function getUnsubscribeLink() diff --git a/app/Utils/Traits/MakesInvoiceHtml.php b/app/Utils/Traits/MakesInvoiceHtml.php index 529544c7661e..cd203329f28e 100644 --- a/app/Utils/Traits/MakesInvoiceHtml.php +++ b/app/Utils/Traits/MakesInvoiceHtml.php @@ -11,9 +11,7 @@ namespace App\Utils\Traits; -use App\Designs\Designer; use Exception; -use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\File; use Illuminate\View\Factory; diff --git a/app/Utils/Traits/MakesInvoiceValues.php b/app/Utils/Traits/MakesInvoiceValues.php index eb4c83d1e916..69c44fff9f82 100644 --- a/app/Utils/Traits/MakesInvoiceValues.php +++ b/app/Utils/Traits/MakesInvoiceValues.php @@ -11,10 +11,7 @@ namespace App\Utils\Traits; -use App\Models\Country; -use App\Models\Credit; use App\Models\Invoice; -use App\Models\Quote; use App\Utils\Helpers; use App\Utils\Number; use Carbon\Carbon; @@ -263,7 +260,6 @@ trait MakesInvoiceValues */ public function transformLineItems($items, $table_type = '$product') :array { //$start = microtime(true); - $entity = $this->client ? $this->client : $this->vendor; $data = []; @@ -284,7 +280,7 @@ trait MakesInvoiceValues if ($table_type == '$task' && $item->type_id != 2) { // if ($item->type_id != 4 && $item->type_id != 5) { - continue; + continue; // } } diff --git a/app/Utils/Traits/MakesReminders.php b/app/Utils/Traits/MakesReminders.php index 58fb5d3ef155..2d9f8b80b607 100644 --- a/app/Utils/Traits/MakesReminders.php +++ b/app/Utils/Traits/MakesReminders.php @@ -21,7 +21,6 @@ trait MakesReminders { public function inReminderWindow($schedule_reminder, $num_days_reminder) { - switch ($schedule_reminder) { case 'after_invoice_date': return Carbon::parse($this->date)->addDays($num_days_reminder)->startOfDay()->eq(Carbon::now()->startOfDay()); @@ -93,7 +92,7 @@ trait MakesReminders switch ($endless_reminder_frequency_id) { case RecurringInvoice::FREQUENCY_DAILY: return Carbon::parse($date)->addDay()->startOfDay(); - case RecurringInvoice::FREQUENCY_WEEKLY: + case RecurringInvoice::FREQUENCY_WEEKLY: return Carbon::parse($date)->addWeek()->startOfDay(); case RecurringInvoice::FREQUENCY_TWO_WEEKS: return Carbon::parse($date)->addWeeks(2)->startOfDay(); diff --git a/app/Utils/Traits/MakesTemplateData.php b/app/Utils/Traits/MakesTemplateData.php index cff45b82cfd1..c4a9fcb7ba12 100644 --- a/app/Utils/Traits/MakesTemplateData.php +++ b/app/Utils/Traits/MakesTemplateData.php @@ -203,7 +203,8 @@ trait MakesTemplateData $data['$task.tax_name3'] = ['value' => 'CA Sales Tax', 'label' => ctrans('texts.tax')]; $data['$task.line_total'] = ['value' => '$100.00', 'label' => ctrans('texts.line_total')]; - $data['$vendor_name'] = ['value' => 'Joey Diaz Denkins', 'label' => ctrans('texts.vendor_name')];; + $data['$vendor_name'] = ['value' => 'Joey Diaz Denkins', 'label' => ctrans('texts.vendor_name')]; + ; $data['$vendor.name'] = &$data['$vendor_name']; $data['$vendor'] = &$data['$vendor_name']; diff --git a/app/Utils/Traits/Notifications/UserNotifies.php b/app/Utils/Traits/Notifications/UserNotifies.php index 89cddfbd93ec..7f0e7f5d16ad 100644 --- a/app/Utils/Traits/Notifications/UserNotifies.php +++ b/app/Utils/Traits/Notifications/UserNotifies.php @@ -162,12 +162,12 @@ trait UserNotifies /** * Underrated method right here, last ones * are always the best - * - * @param CompanyUser $company_user + * + * @param CompanyUser $company_user * @param Invoice | Quote | Credit | PurchaseOrder | Product $entity - * @param array $required_notification - * - * @return bool + * @param array $required_notification + * + * @return bool */ private function checkNotificationExists($company_user, $entity, $required_notification): bool { diff --git a/app/Utils/Traits/NumberFormatter.php b/app/Utils/Traits/NumberFormatter.php index f0778a3d0dba..96684e03650f 100644 --- a/app/Utils/Traits/NumberFormatter.php +++ b/app/Utils/Traits/NumberFormatter.php @@ -21,7 +21,6 @@ trait NumberFormatter /* 08-01-2022 allow increased precision means we need to transform from scientific notation to a regular string */ return number_format($this->parseFloat(rtrim(sprintf('%f', $value), '0')), $precision, '.', ''); - } /** @@ -33,7 +32,6 @@ trait NumberFormatter */ private function parseFloat($value) : float { - // check for comma as decimal separator if (preg_match('/,[\d]{1,2}$/', $value)) { $value = str_replace(',', '.', $value); diff --git a/app/Utils/Traits/Pdf/PageNumbering.php b/app/Utils/Traits/Pdf/PageNumbering.php index d46dfc83d23b..5e930ffaa2c0 100644 --- a/app/Utils/Traits/Pdf/PageNumbering.php +++ b/app/Utils/Traits/Pdf/PageNumbering.php @@ -11,7 +11,6 @@ namespace App\Utils\Traits\Pdf; -use App\Utils\Traits\Pdf\PDF; use setasign\Fpdi\PdfParser\StreamReader; trait PageNumbering diff --git a/app/Utils/Traits/SavesDocuments.php b/app/Utils/Traits/SavesDocuments.php index 28526da97f9a..b7ffd0cda2c4 100644 --- a/app/Utils/Traits/SavesDocuments.php +++ b/app/Utils/Traits/SavesDocuments.php @@ -33,8 +33,9 @@ trait SavesDocuments return false; } - if(!is_array($document_array)) + if (!is_array($document_array)) { return; + } foreach ($document_array as $document) { $document = (new UploadFile( diff --git a/app/Utils/Traits/SettingsSaver.php b/app/Utils/Traits/SettingsSaver.php index f14a87e80f2b..e53a764318f9 100644 --- a/app/Utils/Traits/SettingsSaver.php +++ b/app/Utils/Traits/SettingsSaver.php @@ -35,9 +35,8 @@ trait SettingsSaver ksort($casts); foreach ($casts as $key => $value) { - //try casting floats here - if($value == 'float' && property_exists($settings, $key)){ + if ($value == 'float' && property_exists($settings, $key)) { $settings->{$key} = floatval($settings->{$key}); } @@ -52,11 +51,12 @@ trait SettingsSaver continue; } /*Separate loop if it is a _id field which is an integer cast as a string*/ - elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter' || ($key == 'payment_terms' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1) || ($key == 'valid_until' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1)) { + elseif (substr($key, -3) == '_id' || substr($key, -14) == 'number_counter' || ($key == 'payment_terms' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1) || ($key == 'valid_until' && property_exists($settings, $key) && strlen($settings->{$key}) >= 1)) { $value = 'integer'; - if($key == 'gmail_sending_user_id' || $key == 'besr_id') + if ($key == 'gmail_sending_user_id' || $key == 'besr_id') { $value = 'string'; + } if (! property_exists($settings, $key)) { continue; @@ -100,7 +100,7 @@ trait SettingsSaver case 'double': return !is_string($value) && (is_float($value) || is_numeric(strval($value))); case 'string': - return !is_int($value) || ( is_string( $value ) && method_exists($value, '__toString') ) || is_null($value) || is_string($value); + return !is_int($value) || (is_string($value) && method_exists($value, '__toString')) || is_null($value) || is_string($value); case 'bool': case 'boolean': return is_bool($value) || (int) filter_var($value, FILTER_VALIDATE_BOOLEAN); @@ -111,7 +111,7 @@ trait SettingsSaver case 'json': json_decode($value); - return json_last_error() == JSON_ERROR_NONE; + return json_last_error() == JSON_ERROR_NONE; default: return false; } diff --git a/app/Utils/Traits/SubscriptionHooker.php b/app/Utils/Traits/SubscriptionHooker.php index 6896a8ac78f7..df03068464b7 100644 --- a/app/Utils/Traits/SubscriptionHooker.php +++ b/app/Utils/Traits/SubscriptionHooker.php @@ -11,9 +11,8 @@ namespace App\Utils\Traits; -use GuzzleHttp\RequestOptions; use GuzzleHttp\Exception\ClientException; -use GuzzleHttp\Psr7\Message; +use GuzzleHttp\RequestOptions; /** * Class SubscriptionHooker. @@ -27,17 +26,19 @@ trait SubscriptionHooker 'X-Requested-With' => 'XMLHttpRequest', ]; - if(!isset($subscription->webhook_configuration['post_purchase_url']) && !isset($subscription->webhook_configuration['post_purchase_rest_method'])) + if (!isset($subscription->webhook_configuration['post_purchase_url']) && !isset($subscription->webhook_configuration['post_purchase_rest_method'])) { return []; + } if (count($subscription->webhook_configuration['post_purchase_headers']) >= 1) { $headers = array_merge($headers, $subscription->webhook_configuration['post_purchase_headers']); } $client = new \GuzzleHttp\Client( - [ - 'headers' => $headers, - ]); + [ + 'headers' => $headers, + ] + ); $post_purchase_rest_method = (string) $subscription->webhook_configuration['post_purchase_rest_method']; $post_purchase_url = (string) $subscription->webhook_configuration['post_purchase_url']; @@ -49,22 +50,21 @@ trait SubscriptionHooker return array_merge($body, json_decode($response->getBody(), true)); } catch (ClientException $e) { - $message = $e->getMessage(); $error = json_decode($e->getResponse()->getBody()->getContents()); - if(is_null($error)){ - nlog("empty response"); + if (is_null($error)) { + nlog("empty response"); nlog($e->getMessage()); } - if($error && property_exists($error, 'message')) + if ($error && property_exists($error, 'message')) { $message = $error->message; + } return array_merge($body, ['message' => $message, 'status_code' => 500]); - } - catch (\Exception $e) { + } catch (\Exception $e) { return array_merge($body, ['message' => $e->getMessage(), 'status_code' => 500]); } } diff --git a/app/Utils/Traits/Uploadable.php b/app/Utils/Traits/Uploadable.php index 3100a9c6c58d..69be5021f470 100644 --- a/app/Utils/Traits/Uploadable.php +++ b/app/Utils/Traits/Uploadable.php @@ -23,7 +23,7 @@ trait Uploadable public function removeLogo($company) { //if (Storage::disk(config('filesystems.default'))->exists($company->settings->company_logo)) { - (new UnlinkFile(config('filesystems.default'), $company->settings->company_logo))->handle(); + (new UnlinkFile(config('filesystems.default'), $company->settings->company_logo))->handle(); //} } diff --git a/app/Utils/VendorHtmlEngine.php b/app/Utils/VendorHtmlEngine.php index c57d79d44870..b8d28390cdac 100644 --- a/app/Utils/VendorHtmlEngine.php +++ b/app/Utils/VendorHtmlEngine.php @@ -14,18 +14,13 @@ namespace App\Utils; use App\Models\Country; use App\Models\CreditInvitation; -use App\Models\GatewayType; use App\Models\InvoiceInvitation; use App\Models\PurchaseOrderInvitation; use App\Models\QuoteInvitation; use App\Models\RecurringInvoiceInvitation; -use App\Services\PdfMaker\Designs\Utilities\DesignHelpers; -use App\Utils\Ninja; -use App\Utils\Number; use App\Utils\Traits\AppSetup; use App\Utils\Traits\DesignCalculator; use App\Utils\Traits\MakesDates; -use App\Utils\transformTranslations; use Exception; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Cache; @@ -71,9 +66,9 @@ class VendorHtmlEngine $this->contact = $invitation->contact->load('vendor'); - $this->vendor = $this->contact->vendor->load('company','country'); + $this->vendor = $this->contact->vendor->load('company', 'country'); - if(!$this->vendor->currency_id){ + if (!$this->vendor->currency_id) { $this->vendor->currency_id = $this->company->settings->currency_id; $this->vendor->save(); } @@ -116,7 +111,7 @@ class VendorHtmlEngine public function buildEntityDataArray() :array { - if (! $this->vendor->currency()) { + if (! $this->vendor->currency()) { throw new Exception(debug_backtrace()[1]['function'], 1); exit; } @@ -176,25 +171,23 @@ class VendorHtmlEngine $data['$subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getSubTotal(), $this->vendor) ?: ' ', 'label' => ctrans('texts.subtotal')]; $data['$gross_subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getGrossSubTotal(), $this->vendor) ?: ' ', 'label' => ctrans('texts.subtotal')]; - if($this->entity->uses_inclusive_taxes) + if ($this->entity->uses_inclusive_taxes) { $data['$net_subtotal'] = ['value' => Number::formatMoney(($this->entity_calc->getSubTotal() - $this->entity->total_taxes - $this->entity_calc->getTotalDiscount()), $this->vendor) ?: ' ', 'label' => ctrans('texts.net_subtotal')]; - else + } else { $data['$net_subtotal'] = ['value' => Number::formatMoney($this->entity_calc->getSubTotal() - $this->entity_calc->getTotalDiscount(), $this->vendor) ?: ' ', 'label' => ctrans('texts.net_subtotal')]; + } if ($this->entity->partial > 0) { $data['$balance_due'] = ['value' => Number::formatMoney($this->entity->partial, $this->vendor) ?: ' ', 'label' => ctrans('texts.partial_due')]; $data['$balance_due_raw'] = ['value' => $this->entity->partial, 'label' => ctrans('texts.partial_due')]; $data['$amount_raw'] = ['value' => $this->entity->partial, 'label' => ctrans('texts.partial_due')]; $data['$due_date'] = ['value' => $this->translateDate($this->entity->partial_due_date, $this->company->date_format(), $this->company->locale()) ?: ' ', 'label' => ctrans('texts.'.$this->entity_string.'_due_date')]; - } else { - - if($this->entity->status_id == 1){ + if ($this->entity->status_id == 1) { $data['$balance_due'] = ['value' => Number::formatMoney($this->entity->amount, $this->vendor) ?: ' ', 'label' => ctrans('texts.balance_due')]; $data['$balance_due_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.balance_due')]; $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')]; - } - else{ + } else { $data['$balance_due'] = ['value' => Number::formatMoney($this->entity->balance, $this->vendor) ?: ' ', 'label' => ctrans('texts.balance_due')]; $data['$balance_due_raw'] = ['value' => $this->entity->balance, 'label' => ctrans('texts.balance_due')]; $data['$amount_raw'] = ['value' => $this->entity->amount, 'label' => ctrans('texts.amount')]; @@ -255,8 +248,9 @@ class VendorHtmlEngine $data['$country_2'] = ['value' => isset($this->vendor->country) ? $this->vendor->country->iso_3166_2 : '', 'label' => ctrans('texts.country')]; $data['$email'] = ['value' => isset($this->contact) ? $this->contact->email : 'no contact email on record', 'label' => ctrans('texts.email')]; - if(str_contains($data['$email']['value'], 'example.com')) + if (str_contains($data['$email']['value'], 'example.com')) { $data['$email'] = ['value' => '', 'label' => ctrans('texts.email')]; + } $data['$vendor_name'] = ['value' => $this->vendor->present()->name() ?: ' ', 'label' => ctrans('texts.vendor_name')]; $data['$vendor.name'] = &$data['$vendor_name']; @@ -426,9 +420,7 @@ class VendorHtmlEngine $data['$payments'] = ['value' => '', 'label' => ctrans('texts.payments')]; - if($this->entity->client()->exists()) - { - + if ($this->entity->client()->exists()) { $data['$client1'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'client1', $this->entity->client->custom_value1, $this->entity->client) ?: ' ', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'client1')]; $data['$client2'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'client2', $this->entity->client->custom_value2, $this->entity->client) ?: ' ', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'client2')]; $data['$client3'] = ['value' => $this->helpers->formatCustomFieldValue($this->company->custom_fields, 'client3', $this->entity->client->custom_value3, $this->entity->client) ?: ' ', 'label' => $this->helpers->makeCustomField($this->company->custom_fields, 'client3')]; @@ -486,7 +478,6 @@ class VendorHtmlEngine $data['$client.balance'] = ['value' => Number::formatMoney($this->entity->client->balance, $this->entity->client), 'label' => ctrans('texts.account_balance')]; $data['$client_balance'] = ['value' => Number::formatMoney($this->entity->client->balance, $this->entity->client), 'label' => ctrans('texts.account_balance')]; - } @@ -568,27 +559,21 @@ class VendorHtmlEngine private function getCountryName() :string { - $countries = Cache::get('countries'); if (! $countries) { $this->buildCache(true); $countries = Cache::get('countries'); - } - if($countries){ - - + if ($countries) { $country = $countries->filter(function ($item) { return $item->id == $this->settings->country_id; })->first(); - - - } - else + } else { $country = Country::find($this->settings->country_id); + } if ($country) { return ctrans('texts.country_' . $country->name); @@ -602,8 +587,9 @@ class VendorHtmlEngine { $country = Country::find($this->settings->country_id); - if($country) + if ($country) { return $country->iso_3166_2; + } // if ($country) { // return ctrans('texts.country_' . $country->iso_3166_2); // } @@ -780,8 +766,8 @@ html { /** * Generate markup for HTML images on entity. - * - * @return string|void + * + * @return string|void */ protected function generateEntityImagesMarkup() { @@ -831,5 +817,4 @@ html {
'; } - } diff --git a/config/flare.php b/config/flare.php index a4896f353761..ebb9eabdebc1 100644 --- a/config/flare.php +++ b/config/flare.php @@ -1,16 +1,16 @@ env('NINJA_COMPANY_ID', null), 'ninja_default_company_gateway_id' => env('NINJA_COMPANY_GATEWAY_ID', null), 'ninja_hosted_secret' => env('NINJA_HOSTED_SECRET', ''), - 'ninja_hosted_header' =>env('NINJA_HEADER',''), + 'ninja_hosted_header' =>env('NINJA_HEADER', ''), 'internal_queue_enabled' => env('INTERNAL_QUEUE_ENABLED', true), 'ninja_apple_api_key' => env('APPLE_API_KEY', false), 'ninja_apple_private_key' => env('APPLE_PRIVATE_KEY', false), @@ -199,17 +199,17 @@ return [ 'ninja_apple_issuer_id' => env('APPLE_ISSUER_ID', false), 'react_app_enabled' => env('REACT_APP_ENABLED', false), 'ninja_apple_client_id' => env('APPLE_CLIENT_ID', false), - 'ninja_apple_client_secret' => env('APPLE_CLIENT_SECRET',false), - 'ninja_apple_redirect_url' => env('APPLE_REDIRECT_URI',false), - 'twilio_account_sid' => env('TWILIO_ACCOUNT_SID',false), - 'twilio_auth_token' => env('TWILIO_AUTH_TOKEN',false), - 'twilio_verify_sid' => env('TWILIO_VERIFY_SID',false), + 'ninja_apple_client_secret' => env('APPLE_CLIENT_SECRET', false), + 'ninja_apple_redirect_url' => env('APPLE_REDIRECT_URI', false), + 'twilio_account_sid' => env('TWILIO_ACCOUNT_SID', false), + 'twilio_auth_token' => env('TWILIO_AUTH_TOKEN', false), + 'twilio_verify_sid' => env('TWILIO_VERIFY_SID', false), 'yodlee' => [ - 'client_id' => env('YODLEE_CLIENT_ID',false), + 'client_id' => env('YODLEE_CLIENT_ID', false), 'client_secret' => env('YODLEE_CLIENT_SECRET', false), 'admin_name' => env('YODLEE_LOGIN_ADMIN_NAME', false), 'test_mode' => env("YODLEE_TEST_MODE", false), 'dev_mode' => env("YODLEE_DEV_MODE", false), 'config_name' => env("YODLEE_CONFIG_NAME", false), ], -]; \ No newline at end of file +]; diff --git a/config/purchase.php b/config/purchase.php index 2791bd868288..b461c41559c8 100644 --- a/config/purchase.php +++ b/config/purchase.php @@ -17,8 +17,8 @@ use Imdhemy\Purchases\Events\GooglePlay\SubscriptionDeferred; use Imdhemy\Purchases\Events\GooglePlay\SubscriptionExpired; use Imdhemy\Purchases\Events\GooglePlay\SubscriptionInGracePeriod; use Imdhemy\Purchases\Events\GooglePlay\SubscriptionOnHold; -use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPauseScheduleChanged; use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPaused; +use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPauseScheduleChanged; use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPriceChangeConfirmed; use Imdhemy\Purchases\Events\GooglePlay\SubscriptionPurchased; use Imdhemy\Purchases\Events\GooglePlay\SubscriptionRecovered; diff --git a/config/services.php b/config/services.php index 36d6a704ec6b..78d3df8341d6 100644 --- a/config/services.php +++ b/config/services.php @@ -19,14 +19,14 @@ return [ */ 'mailgun' => [ - 'domain' => env('MAILGUN_DOMAIN',''), - 'secret' => env('MAILGUN_SECRET',''), + 'domain' => env('MAILGUN_DOMAIN', ''), + 'secret' => env('MAILGUN_SECRET', ''), 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), 'scheme' => 'https', ], 'postmark' => [ - 'token' => env('POSTMARK_SECRET',''), + 'token' => env('POSTMARK_SECRET', ''), ], 'microsoft' => [ diff --git a/database/factories/AccountFactory.php b/database/factories/AccountFactory.php index 66220630d833..371c2a3f9193 100644 --- a/database/factories/AccountFactory.php +++ b/database/factories/AccountFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\Account; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; diff --git a/database/factories/BankIntegrationFactory.php b/database/factories/BankIntegrationFactory.php index ad588f872a84..2cc88e5f7ad8 100644 --- a/database/factories/BankIntegrationFactory.php +++ b/database/factories/BankIntegrationFactory.php @@ -11,9 +11,7 @@ namespace Database\Factories; -use App\Models\Account; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Support\Str; class BankIntegrationFactory extends Factory { @@ -38,4 +36,4 @@ class BankIntegrationFactory extends Factory 'is_deleted' => false, ]; } -} \ No newline at end of file +} diff --git a/database/factories/BankTransactionFactory.php b/database/factories/BankTransactionFactory.php index 404f268d5787..e47a822100cd 100644 --- a/database/factories/BankTransactionFactory.php +++ b/database/factories/BankTransactionFactory.php @@ -11,9 +11,7 @@ namespace Database\Factories; -use App\Models\Account; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Support\Str; class BankTransactionFactory extends Factory { @@ -26,7 +24,7 @@ class BankTransactionFactory extends Factory { return [ 'transaction_id' => $this->faker->randomNumber(9, true) , - 'amount' => $this->faker->randomFloat(2,10,10000) , + 'amount' => $this->faker->randomFloat(2, 10, 10000) , 'currency_id' => '1', 'account_type' => 'creditCard', 'category_id' => 1, @@ -35,7 +33,7 @@ class BankTransactionFactory extends Factory 'bank_account_id' => 1 , 'description' =>$this->faker->words(5, true) , 'status_id'=> 1, - 'base_type' => (bool)rand(0,1) ? 'CREDIT' : 'DEBIT', + 'base_type' => (bool)rand(0, 1) ? 'CREDIT' : 'DEBIT', ]; } } diff --git a/database/factories/BankTransactionRuleFactory.php b/database/factories/BankTransactionRuleFactory.php index af30349dffcc..c257902c84ac 100644 --- a/database/factories/BankTransactionRuleFactory.php +++ b/database/factories/BankTransactionRuleFactory.php @@ -11,9 +11,7 @@ namespace Database\Factories; -use App\Models\Account; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Support\Str; class BankTransactionRuleFactory extends Factory { @@ -27,8 +25,8 @@ class BankTransactionRuleFactory extends Factory return [ 'name' => $this->faker->name(), // 'applies_to' => (bool)rand(0,1) ? 'CREDIT' : 'DEBIT', - 'matches_on_all' => (bool)rand(0,1), - 'auto_convert' => (bool)rand(0,1), + 'matches_on_all' => (bool)rand(0, 1), + 'auto_convert' => (bool)rand(0, 1), ]; } } diff --git a/database/factories/ClientContactFactory.php b/database/factories/ClientContactFactory.php index 473f919c30c3..706c2bc30fb4 100644 --- a/database/factories/ClientContactFactory.php +++ b/database/factories/ClientContactFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\ClientContact; use Illuminate\Database\Eloquent\Factories\Factory; class ClientContactFactory extends Factory diff --git a/database/factories/ClientFactory.php b/database/factories/ClientFactory.php index 045bdddf041f..5535cca440fa 100644 --- a/database/factories/ClientFactory.php +++ b/database/factories/ClientFactory.php @@ -12,7 +12,6 @@ namespace Database\Factories; use App\DataMapper\ClientSettings; -use App\Models\Client; use Illuminate\Database\Eloquent\Factories\Factory; class ClientFactory extends Factory diff --git a/database/factories/CompanyFactory.php b/database/factories/CompanyFactory.php index 2b08b87101c4..d70a899bfbf4 100644 --- a/database/factories/CompanyFactory.php +++ b/database/factories/CompanyFactory.php @@ -12,7 +12,6 @@ namespace Database\Factories; use App\DataMapper\CompanySettings; -use App\Models\Company; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Factories\Factory; diff --git a/database/factories/CreditInvitationFactory.php b/database/factories/CreditInvitationFactory.php index 950d6e84363a..ebf0b2895aea 100644 --- a/database/factories/CreditInvitationFactory.php +++ b/database/factories/CreditInvitationFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\CreditInvitation; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; diff --git a/database/factories/DocumentFactory.php b/database/factories/DocumentFactory.php index 0b2642a84e99..b3183de7fff0 100644 --- a/database/factories/DocumentFactory.php +++ b/database/factories/DocumentFactory.php @@ -11,9 +11,7 @@ namespace Database\Factories; -use App\Models\Document; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Support\Str; class DocumentFactory extends Factory { diff --git a/database/factories/ExpenseCategoryFactory.php b/database/factories/ExpenseCategoryFactory.php index b158299b826d..1069882a6bf7 100644 --- a/database/factories/ExpenseCategoryFactory.php +++ b/database/factories/ExpenseCategoryFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\ExpenseCategory; use Illuminate\Database\Eloquent\Factories\Factory; class ExpenseCategoryFactory extends Factory diff --git a/database/factories/ExpenseFactory.php b/database/factories/ExpenseFactory.php index 8560fc2ceec2..0de98a169e83 100644 --- a/database/factories/ExpenseFactory.php +++ b/database/factories/ExpenseFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\Expense; use Illuminate\Database\Eloquent\Factories\Factory; class ExpenseFactory extends Factory diff --git a/database/factories/GatewayFactory.php b/database/factories/GatewayFactory.php index d21f6ddcbc8c..4750d76d51f8 100644 --- a/database/factories/GatewayFactory.php +++ b/database/factories/GatewayFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\Gateway; use Illuminate\Database\Eloquent\Factories\Factory; class GatewayFactory extends Factory diff --git a/database/factories/InvoiceInvitationFactory.php b/database/factories/InvoiceInvitationFactory.php index e5d6edc56a0e..fb23d37fb9f8 100644 --- a/database/factories/InvoiceInvitationFactory.php +++ b/database/factories/InvoiceInvitationFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\InvoiceInvitation; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; diff --git a/database/factories/ProductFactory.php b/database/factories/ProductFactory.php index 7f8f25833838..ca66833b3d35 100644 --- a/database/factories/ProductFactory.php +++ b/database/factories/ProductFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\Product; use Illuminate\Database\Eloquent\Factories\Factory; class ProductFactory extends Factory @@ -30,7 +29,7 @@ class ProductFactory extends Factory 'price' => $this->faker->numberBetween(1, 1000), 'quantity' => $this->faker->numberBetween(1, 100), 'custom_value1' => 'https://picsum.photos/200', - 'custom_value2' => rand(0,100), + 'custom_value2' => rand(0, 100), 'custom_value3' => $this->faker->text(20), 'custom_value4' => $this->faker->text(20), 'is_deleted' => false, diff --git a/database/factories/ProjectFactory.php b/database/factories/ProjectFactory.php index 46f0276dae62..a5dfb9515459 100644 --- a/database/factories/ProjectFactory.php +++ b/database/factories/ProjectFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\Project; use Illuminate\Database\Eloquent\Factories\Factory; class ProjectFactory extends Factory diff --git a/database/factories/PurchaseOrderFactory.php b/database/factories/PurchaseOrderFactory.php index df91de22f5ba..ddfaface41f1 100644 --- a/database/factories/PurchaseOrderFactory.php +++ b/database/factories/PurchaseOrderFactory.php @@ -6,7 +6,7 @@ * * @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com) * - * @license https://www.elastic.co/licensing/elastic-license + * @license https://www.elastic.co/licensing/elastic-license */ namespace Database\Factories; diff --git a/database/factories/PurchaseOrderInvitationFactory.php b/database/factories/PurchaseOrderInvitationFactory.php index a775099731d6..0e72088d25df 100644 --- a/database/factories/PurchaseOrderInvitationFactory.php +++ b/database/factories/PurchaseOrderInvitationFactory.php @@ -2,7 +2,6 @@ namespace Database\Factories; -use App\Models\PurchaseOrderInvitation; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; diff --git a/database/factories/QuoteInvitationFactory.php b/database/factories/QuoteInvitationFactory.php index 7fcaa1a3016c..fbeba27f48b1 100644 --- a/database/factories/QuoteInvitationFactory.php +++ b/database/factories/QuoteInvitationFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\QuoteInvitation; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; diff --git a/database/factories/RecurringExpenseFactory.php b/database/factories/RecurringExpenseFactory.php index fb58a0f3dd27..68b109451aee 100644 --- a/database/factories/RecurringExpenseFactory.php +++ b/database/factories/RecurringExpenseFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\RecurringExpense; use Illuminate\Database\Eloquent\Factories\Factory; class RecurringExpenseFactory extends Factory diff --git a/database/factories/SchedulerFactory.php b/database/factories/SchedulerFactory.php index 8b839c5e6b2e..aba12d2f257f 100644 --- a/database/factories/SchedulerFactory.php +++ b/database/factories/SchedulerFactory.php @@ -12,7 +12,6 @@ namespace Database\Factories; use App\Models\RecurringInvoice; -use App\Models\Scheduler; use Illuminate\Database\Eloquent\Factories\Factory; class SchedulerFactory extends Factory @@ -26,12 +25,12 @@ class SchedulerFactory extends Factory { return [ 'name' => $this->faker->name(), - 'is_paused' => rand(0,1), - 'is_deleted' => rand(0,1), + 'is_paused' => rand(0, 1), + 'is_deleted' => rand(0, 1), 'parameters' => [], 'frequency_id' => RecurringInvoice::FREQUENCY_MONTHLY, - 'next_run' => now()->addSeconds(rand(86400,8640000)), - 'next_run_client' => now()->addSeconds(rand(86400,8640000)), + 'next_run' => now()->addSeconds(rand(86400, 8640000)), + 'next_run_client' => now()->addSeconds(rand(86400, 8640000)), 'template' => 'client_statement', ]; } diff --git a/database/factories/SubscriptionFactory.php b/database/factories/SubscriptionFactory.php index f8bbf991da5a..81607dd83bd7 100644 --- a/database/factories/SubscriptionFactory.php +++ b/database/factories/SubscriptionFactory.php @@ -13,7 +13,6 @@ namespace Database\Factories; use App\Models\RecurringInvoice; -use App\Models\Subscription; use Illuminate\Database\Eloquent\Factories\Factory; class SubscriptionFactory extends Factory diff --git a/database/factories/TaskFactory.php b/database/factories/TaskFactory.php index b252652d0b69..326607e8efba 100644 --- a/database/factories/TaskFactory.php +++ b/database/factories/TaskFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\Task; use Illuminate\Database\Eloquent\Factories\Factory; class TaskFactory extends Factory diff --git a/database/factories/TaskStatusFactory.php b/database/factories/TaskStatusFactory.php index 0ac62f60bfa3..940aef5373bc 100644 --- a/database/factories/TaskStatusFactory.php +++ b/database/factories/TaskStatusFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\TaskStatus; use Illuminate\Database\Eloquent\Factories\Factory; class TaskStatusFactory extends Factory diff --git a/database/factories/TaxRateFactory.php b/database/factories/TaxRateFactory.php index ef1be4c3a7be..2b2a65023781 100644 --- a/database/factories/TaxRateFactory.php +++ b/database/factories/TaxRateFactory.php @@ -11,9 +11,7 @@ namespace Database\Factories; -use App\Models\TaxRate; use Illuminate\Database\Eloquent\Factories\Factory; -use Illuminate\Support\Str; class TaxRateFactory extends Factory { diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index 8e8edc2f2192..ce391a46a8aa 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; class UserFactory extends Factory diff --git a/database/factories/VendorContactFactory.php b/database/factories/VendorContactFactory.php index f0bede1531c3..03b8556e8b74 100644 --- a/database/factories/VendorContactFactory.php +++ b/database/factories/VendorContactFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\VendorContact; use Illuminate\Database\Eloquent\Factories\Factory; class VendorContactFactory extends Factory diff --git a/database/factories/VendorFactory.php b/database/factories/VendorFactory.php index 7fd4b0668857..bfcec1759227 100644 --- a/database/factories/VendorFactory.php +++ b/database/factories/VendorFactory.php @@ -11,7 +11,6 @@ namespace Database\Factories; -use App\Models\Vendor; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; 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 2298d3e5b239..f13e1357068f 100644 --- a/database/migrations/2021_03_08_205030_add_russian_lang.php +++ b/database/migrations/2021_03_08_205030_add_russian_lang.php @@ -2,7 +2,6 @@ use App\Models\Company; use App\Models\Language; -use App\Models\User; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; diff --git a/database/migrations/2021_03_19_221024_add_unique_constraints_on_all_entities.php b/database/migrations/2021_03_19_221024_add_unique_constraints_on_all_entities.php index 07791c4d9b89..2e82dc28520d 100644 --- a/database/migrations/2021_03_19_221024_add_unique_constraints_on_all_entities.php +++ b/database/migrations/2021_03_19_221024_add_unique_constraints_on_all_entities.php @@ -1,8 +1,6 @@ id = 59; - $forte->name = 'Forte'; - $forte->key = 'kivcvjexxvdiyqtj3mju5d6yhpeht2xs'; + $forte->name = 'Forte'; + $forte->key = 'kivcvjexxvdiyqtj3mju5d6yhpeht2xs'; $forte->provider = 'Forte'; $forte->is_offsite = true; $forte->fields = \json_encode($fields); diff --git a/database/migrations/2022_04_22_115838_client_settings_parse_for_types.php b/database/migrations/2022_04_22_115838_client_settings_parse_for_types.php index 78a1d443e1b0..45702dc09ab8 100644 --- a/database/migrations/2022_04_22_115838_client_settings_parse_for_types.php +++ b/database/migrations/2022_04_22_115838_client_settings_parse_for_types.php @@ -4,8 +4,6 @@ use App\Models\Client; use App\Utils\Ninja; use App\Utils\Traits\ClientGroupSettingsSaver; use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; return new class extends Migration { use ClientGroupSettingsSaver; diff --git a/database/migrations/2022_04_26_032252_convert_custom_fields_column_from_varchar_to_text.php b/database/migrations/2022_04_26_032252_convert_custom_fields_column_from_varchar_to_text.php index 5592b0da8d8f..fe35bd53fad2 100644 --- a/database/migrations/2022_04_26_032252_convert_custom_fields_column_from_varchar_to_text.php +++ b/database/migrations/2022_04_26_032252_convert_custom_fields_column_from_varchar_to_text.php @@ -1,6 +1,5 @@ id = 47; $type->name = 'Klarna'; @@ -28,8 +25,7 @@ return new class extends Migration { $pt = PaymentType::find(48); - if(!$pt) - { + if (!$pt) { $type = new PaymentType(); $type->id = 48; $type->name = 'Interac E-Transfer'; @@ -38,8 +34,7 @@ return new class extends Migration { $gt = GatewayType::find(23); - if(!$gt) - { + if (!$gt) { $type = new GatewayType(); $type->id = 23; $type->alias = 'klarna'; diff --git a/database/migrations/2022_05_18_162443_create_schedulers_table.php b/database/migrations/2022_05_18_162443_create_schedulers_table.php index 26a9c7ce90d4..6b4abb51a4d2 100644 --- a/database/migrations/2022_05_18_162443_create_schedulers_table.php +++ b/database/migrations/2022_05_18_162443_create_schedulers_table.php @@ -41,6 +41,5 @@ return new class extends Migration { */ public function down() { - } }; diff --git a/database/migrations/2022_05_30_181109_drop_scheduled_jobs_table.php b/database/migrations/2022_05_30_181109_drop_scheduled_jobs_table.php index 0f1d48dd59c7..caac82143cc0 100644 --- a/database/migrations/2022_05_30_181109_drop_scheduled_jobs_table.php +++ b/database/migrations/2022_05_30_181109_drop_scheduled_jobs_table.php @@ -9,7 +9,6 @@ * @license https://www.elastic.co/licensing/elastic-license */ use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { diff --git a/database/migrations/2022_06_01_215859_set_recurring_client_timestamp.php b/database/migrations/2022_06_01_215859_set_recurring_client_timestamp.php index 5011d72ac5b6..0a228f8b18b1 100644 --- a/database/migrations/2022_06_01_215859_set_recurring_client_timestamp.php +++ b/database/migrations/2022_06_01_215859_set_recurring_client_timestamp.php @@ -32,7 +32,6 @@ return new class extends Migration { }); RecurringInvoice::withTrashed()->whereNotNull('next_send_date')->cursor()->each(function ($recurring_invoice) { - // $offset = $recurring_invoice->client->timezone_offset(); // $re = Carbon::parse($recurring_invoice->next_send_date)->subSeconds($offset)->format('Y-m-d'); $re = Carbon::parse($recurring_invoice->next_send_date)->format('Y-m-d'); diff --git a/database/migrations/2022_06_10_030503_set_account_flag_for_react.php b/database/migrations/2022_06_10_030503_set_account_flag_for_react.php index 89051c861910..ac80d2b13247 100644 --- a/database/migrations/2022_06_10_030503_set_account_flag_for_react.php +++ b/database/migrations/2022_06_10_030503_set_account_flag_for_react.php @@ -9,8 +9,6 @@ * @license https://www.elastic.co/licensing/elastic-license */ use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; return new class extends Migration { /** diff --git a/database/migrations/2022_06_21_104350_fixes_for_description_in_pdf_designs.php b/database/migrations/2022_06_21_104350_fixes_for_description_in_pdf_designs.php index 616114139785..6fb71e56d8a1 100644 --- a/database/migrations/2022_06_21_104350_fixes_for_description_in_pdf_designs.php +++ b/database/migrations/2022_06_21_104350_fixes_for_description_in_pdf_designs.php @@ -9,8 +9,6 @@ * @license https://www.elastic.co/licensing/elastic-license */ use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; class FixesForDescriptionInPdfDesigns extends Migration { @@ -31,6 +29,5 @@ class FixesForDescriptionInPdfDesigns extends Migration */ public function down() { - } } diff --git a/database/migrations/2022_06_24_141018_upgrade_failed_jobs_table.php b/database/migrations/2022_06_24_141018_upgrade_failed_jobs_table.php index 6ff0098e5689..3567d00a6ca8 100644 --- a/database/migrations/2022_06_24_141018_upgrade_failed_jobs_table.php +++ b/database/migrations/2022_06_24_141018_upgrade_failed_jobs_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * diff --git a/database/migrations/2022_06_30_000126_add_flag_to_accounts_table.php b/database/migrations/2022_06_30_000126_add_flag_to_accounts_table.php index 3e3ab2fc78ab..116d611f6a76 100644 --- a/database/migrations/2022_06_30_000126_add_flag_to_accounts_table.php +++ b/database/migrations/2022_06_30_000126_add_flag_to_accounts_table.php @@ -34,6 +34,5 @@ class AddFlagToAccountsTable extends Migration */ public function down() { - } } diff --git a/database/migrations/2022_07_06_080127_add_purchase_order_to_expense.php b/database/migrations/2022_07_06_080127_add_purchase_order_to_expense.php index b99bfc84968f..741b54b3999b 100644 --- a/database/migrations/2022_07_06_080127_add_purchase_order_to_expense.php +++ b/database/migrations/2022_07_06_080127_add_purchase_order_to_expense.php @@ -33,15 +33,12 @@ class AddPurchaseOrderToExpense extends Migration $language = Language::find(36); - if(!$language){ - + if (!$language) { Language::unguard(); Language::create(['id' => 36, 'name' => 'Bulgarian', 'locale' => 'bg']); $this->buildCache(true); - } - } /** diff --git a/database/migrations/2022_07_09_235510_add_index_to_payment_hash.php b/database/migrations/2022_07_09_235510_add_index_to_payment_hash.php index e5495b50a8b3..35cecc5360f8 100644 --- a/database/migrations/2022_07_09_235510_add_index_to_payment_hash.php +++ b/database/migrations/2022_07_09_235510_add_index_to_payment_hash.php @@ -25,7 +25,7 @@ class AddIndexToPaymentHash extends Migration }); Schema::table('products', function (Blueprint $table) { - $table->index(['company_id', 'user_id', 'assigned_user_id', 'updated_at'],'pro_co_us_up_index'); + $table->index(['company_id', 'user_id', 'assigned_user_id', 'updated_at'], 'pro_co_us_up_index'); }); } diff --git a/database/migrations/2022_07_12_45766_add_matomo.php b/database/migrations/2022_07_12_45766_add_matomo.php index 6eb354c2784a..68f5ae670dd5 100644 --- a/database/migrations/2022_07_12_45766_add_matomo.php +++ b/database/migrations/2022_07_12_45766_add_matomo.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -14,9 +13,8 @@ return new class extends Migration public function up() { Schema::table('companies', function (Blueprint $table) { - $table->string('matomo_url',191)->nullable(); + $table->string('matomo_url', 191)->nullable(); $table->bigInteger('matomo_id')->nullable(); }); - } -}; \ No newline at end of file +}; diff --git a/database/migrations/2022_07_18_033756_fixes_for_date_formats_table_react.php b/database/migrations/2022_07_18_033756_fixes_for_date_formats_table_react.php index 78b1adec8a09..de837a9f9619 100644 --- a/database/migrations/2022_07_18_033756_fixes_for_date_formats_table_react.php +++ b/database/migrations/2022_07_18_033756_fixes_for_date_formats_table_react.php @@ -1,11 +1,8 @@ format_moment = 'ddd MMM D, YYYY'; $df->save(); } - if($df = App\Models\DateFormat::find(14)) - { - + if ($df = App\Models\DateFormat::find(14)) { $df->format_moment = 'DD/MM/YYYY'; $df->save(); - } } diff --git a/database/migrations/2022_07_21_023805_add_hebrew_language.php b/database/migrations/2022_07_21_023805_add_hebrew_language.php index aa29ad54c727..47ec6122e772 100644 --- a/database/migrations/2022_07_21_023805_add_hebrew_language.php +++ b/database/migrations/2022_07_21_023805_add_hebrew_language.php @@ -2,8 +2,6 @@ use App\Models\Language; use Illuminate\Database\Migrations\Migration; -use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\Schema; class AddHebrewLanguage extends Migration { @@ -17,41 +15,30 @@ class AddHebrewLanguage extends Migration Language::unguard(); - if(!Language::find(33)) { - + if (!Language::find(33)) { $serbian = ['id' => 33, 'name' => 'Serbian', 'locale' => 'sr']; Language::create($serbian); - } - if(!Language::find(34)) { - + if (!Language::find(34)) { $slovak = ['id' => 34, 'name' => 'Slovak', 'locale' => 'sk']; Language::create($slovak); - } - if(!Language::find(35)) { - + if (!Language::find(35)) { $estonia = ['id' => 35, 'name' => 'Estonian', 'locale' => 'et']; Language::create($estonia); - } - if(!Language::find(36)) { - + if (!Language::find(36)) { $bulgarian = ['id' => 36, 'name' => 'Bulgarian', 'locale' => 'bg']; Language::create($bulgarian); - } - if(!Language::find(37)) { - + if (!Language::find(37)) { $hebrew = ['id' => 37, 'name' => 'Hebrew', 'locale' => 'he']; Language::create($hebrew); - } - } /** diff --git a/database/migrations/2022_07_26_091216_add_sms_verification_to_hosted_account.php b/database/migrations/2022_07_26_091216_add_sms_verification_to_hosted_account.php index 7ef526562963..703780d29218 100644 --- a/database/migrations/2022_07_26_091216_add_sms_verification_to_hosted_account.php +++ b/database/migrations/2022_07_26_091216_add_sms_verification_to_hosted_account.php @@ -19,11 +19,9 @@ class AddSmsVerificationToHostedAccount extends Migration $table->boolean('account_sms_verified')->default(0); }); - App\Models\Account::query()->cursor()->each(function ($account){ - + App\Models\Account::query()->cursor()->each(function ($account) { $account->account_sms_verified = true; $account->save(); - }); } @@ -34,6 +32,5 @@ class AddSmsVerificationToHostedAccount extends Migration */ public function down() { - } } diff --git a/database/migrations/2022_07_28_232340_enabled_expense_tax_rates_to_companies_table.php b/database/migrations/2022_07_28_232340_enabled_expense_tax_rates_to_companies_table.php index 04a07d8f7d22..8f820e7c3507 100644 --- a/database/migrations/2022_07_28_232340_enabled_expense_tax_rates_to_companies_table.php +++ b/database/migrations/2022_07_28_232340_enabled_expense_tax_rates_to_companies_table.php @@ -5,8 +5,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -18,11 +17,9 @@ return new class extends Migration $table->boolean('enabled_expense_tax_rates')->default(0); }); - Company::query()->where('enabled_item_tax_rates', true)->cursor()->each(function ($company){ - + Company::query()->where('enabled_item_tax_rates', true)->cursor()->each(function ($company) { $company->enabled_expense_tax_rates = true; $company->save(); - }); } @@ -33,6 +30,5 @@ return new class extends Migration */ public function down() { - } }; diff --git a/database/migrations/2022_07_29_091235_correction_for_companies_table_types.php b/database/migrations/2022_07_29_091235_correction_for_companies_table_types.php index 45564710b6a5..0a5d7bf5cf1c 100644 --- a/database/migrations/2022_07_29_091235_correction_for_companies_table_types.php +++ b/database/migrations/2022_07_29_091235_correction_for_companies_table_types.php @@ -5,8 +5,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -18,11 +17,9 @@ return new class extends Migration $table->unsignedInteger('enabled_expense_tax_rates')->default(0)->change(); }); - Company::query()->where('enabled_item_tax_rates', true)->cursor()->each(function ($company){ - + Company::query()->where('enabled_item_tax_rates', true)->cursor()->each(function ($company) { $company->enabled_expense_tax_rates = $company->enabled_item_tax_rates; $company->save(); - }); } diff --git a/database/migrations/2022_08_05_023357_bank_integration.php b/database/migrations/2022_08_05_023357_bank_integration.php index 1375b50af314..55639c89208b 100644 --- a/database/migrations/2022_08_05_023357_bank_integration.php +++ b/database/migrations/2022_08_05_023357_bank_integration.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -13,7 +12,6 @@ return new class extends Migration */ public function up() { - Schema::create('bank_integrations', function (Blueprint $table) { $table->id(); $table->unsignedInteger('account_id'); @@ -44,9 +42,9 @@ return new class extends Migration Schema::table('accounts', function (Blueprint $table) { $table->text('bank_integration_account_id')->nullable(); - }); + }); - Schema::create('bank_transactions', function (Blueprint $table){ + Schema::create('bank_transactions', function (Blueprint $table) { $table->id(); $table->unsignedInteger('company_id'); $table->unsignedInteger('user_id'); @@ -75,21 +73,19 @@ return new class extends Migration $table->foreign('bank_integration_id')->references('id')->on('bank_integrations')->onDelete('cascade')->onUpdate('cascade'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade'); $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade'); - }); Schema::table('expense_categories', function (Blueprint $table) { $table->unsignedInteger('bank_category_id')->nullable(); - }); + }); Schema::table('payments', function (Blueprint $table) { $table->unsignedBigInteger('transaction_id')->nullable(); - }); + }); Schema::table('expenses', function (Illuminate\Database\Schema\Blueprint $table) { $table->unsignedBigInteger('transaction_id')->nullable()->change(); - }); - + }); } /** @@ -99,6 +95,5 @@ return new class extends Migration */ public function down() { - } }; diff --git a/database/migrations/2022_08_11_011534_licenses_table_for_self_host.php b/database/migrations/2022_08_11_011534_licenses_table_for_self_host.php index 8fffec838a07..44169f6abb4c 100644 --- a/database/migrations/2022_08_11_011534_licenses_table_for_self_host.php +++ b/database/migrations/2022_08_11_011534_licenses_table_for_self_host.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * diff --git a/database/migrations/2022_08_24_215917_invoice_task_project_companies_table.php b/database/migrations/2022_08_24_215917_invoice_task_project_companies_table.php index 1e9e8e1d05a6..ffa4de323603 100644 --- a/database/migrations/2022_08_24_215917_invoice_task_project_companies_table.php +++ b/database/migrations/2022_08_24_215917_invoice_task_project_companies_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * diff --git a/database/migrations/2022_08_26_232500_add_email_status_column_to_purchase_order_invitations_table.php b/database/migrations/2022_08_26_232500_add_email_status_column_to_purchase_order_invitations_table.php index 944b55b346f1..ad3a80544983 100644 --- a/database/migrations/2022_08_26_232500_add_email_status_column_to_purchase_order_invitations_table.php +++ b/database/migrations/2022_08_26_232500_add_email_status_column_to_purchase_order_invitations_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -13,11 +12,9 @@ return new class extends Migration */ public function up() { - Schema::table('purchase_order_invitations', function (Blueprint $table) { - $table->enum('email_status', ['delivered', 'bounced', 'spam'])->nullable(); + $table->enum('email_status', ['delivered', 'bounced', 'spam'])->nullable(); }); - } /** @@ -27,6 +24,5 @@ return new class extends Migration */ public function down() { - } }; diff --git a/database/migrations/2022_08_28_210111_add_index_to_payments_table.php b/database/migrations/2022_08_28_210111_add_index_to_payments_table.php index 7f798db6a48d..029fc3e8d0d6 100644 --- a/database/migrations/2022_08_28_210111_add_index_to_payments_table.php +++ b/database/migrations/2022_08_28_210111_add_index_to_payments_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -29,7 +28,6 @@ return new class extends Migration Schema::table('quotes', function (Blueprint $table) { $table->index(['company_id','updated_at']); }); - } /** diff --git a/database/migrations/2022_09_05_024719_update_designs_for_tech_template.php b/database/migrations/2022_09_05_024719_update_designs_for_tech_template.php index f0f45d4a4bb2..9b6265db822b 100644 --- a/database/migrations/2022_09_05_024719_update_designs_for_tech_template.php +++ b/database/migrations/2022_09_05_024719_update_designs_for_tech_template.php @@ -1,11 +1,8 @@ fields); $fields->threeds = false; @@ -27,16 +22,13 @@ return new class extends Migration $g->save(); } - CompanyGateway::where('gateway_key', 'f7ec488676d310683fb51802d076d713')->cursor()->each(function ($cg){ - + CompanyGateway::where('gateway_key', 'f7ec488676d310683fb51802d076d713')->cursor()->each(function ($cg) { $config = $cg->getConfig(); $config->threeds = false; $cg->setConfig($config); $cg->save(); - }); - } /** diff --git a/database/migrations/2022_09_30_235337_add_idempotency_key_to_payments.php b/database/migrations/2022_09_30_235337_add_idempotency_key_to_payments.php index 7f95df32434d..1171c3ea3c42 100644 --- a/database/migrations/2022_09_30_235337_add_idempotency_key_to_payments.php +++ b/database/migrations/2022_09_30_235337_add_idempotency_key_to_payments.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -17,7 +16,6 @@ return new class extends Migration $table->string('idempotency_key', 64)->nullable()->index(); $table->unique(['company_id', 'idempotency_key']); - }); } @@ -28,6 +26,5 @@ return new class extends Migration */ public function down() { - } }; diff --git a/database/migrations/2022_10_05_205645_add_indexes_to_client_hash.php b/database/migrations/2022_10_05_205645_add_indexes_to_client_hash.php index 09658b6e71ed..ff3cef56bb1c 100644 --- a/database/migrations/2022_10_05_205645_add_indexes_to_client_hash.php +++ b/database/migrations/2022_10_05_205645_add_indexes_to_client_hash.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -27,7 +26,6 @@ return new class extends Migration $table->index([\DB::raw('contact_key(20)')]); $table->index('email'); }); - } /** diff --git a/database/migrations/2022_10_06_011344_add_key_to_products.php b/database/migrations/2022_10_06_011344_add_key_to_products.php index 3b5e03f21566..b45f0d2baee1 100644 --- a/database/migrations/2022_10_06_011344_add_key_to_products.php +++ b/database/migrations/2022_10_06_011344_add_key_to_products.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -26,7 +25,6 @@ return new class extends Migration Schema::table('accounts', function (Blueprint $table) { $table->index('key'); }); - } /** @@ -36,6 +34,5 @@ return new class extends Migration */ public function down() { - } }; diff --git a/database/migrations/2022_10_07_065455_add_key_to_company_tokens_table.php b/database/migrations/2022_10_07_065455_add_key_to_company_tokens_table.php index 4811e76d33f1..9603ff640cd8 100644 --- a/database/migrations/2022_10_07_065455_add_key_to_company_tokens_table.php +++ b/database/migrations/2022_10_07_065455_add_key_to_company_tokens_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -25,6 +24,5 @@ return new class extends Migration */ public function down() { - } }; diff --git a/database/migrations/2022_10_10_070137_add_documentable_index.php b/database/migrations/2022_10_10_070137_add_documentable_index.php index c97c96501319..598f50920c3e 100644 --- a/database/migrations/2022_10_10_070137_add_documentable_index.php +++ b/database/migrations/2022_10_10_070137_add_documentable_index.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -13,24 +12,23 @@ return new class extends Migration */ public function up() { - Schema::table('documents', function (Blueprint $table) { + Schema::table('documents', function (Blueprint $table) { $table->index(['documentable_id', 'documentable_type', 'deleted_at']); - }); + }); - Schema::table('expenses', function (Blueprint $table) { + Schema::table('expenses', function (Blueprint $table) { $table->index(['invoice_id', 'deleted_at']); - }); + }); - Schema::table('company_tokens', function (Blueprint $table) { + Schema::table('company_tokens', function (Blueprint $table) { $table->dropIndex('company_tokens_token_index'); $table->index(['token','deleted_at']); - }); + }); - Schema::table('invoice_invitations', function (Blueprint $table) { + Schema::table('invoice_invitations', function (Blueprint $table) { $table->dropIndex('invoice_invitations_key_index'); $table->index(['key','deleted_at']); - }); - + }); } /** diff --git a/database/migrations/2022_10_27_044909_add_user_sms_verification_code.php b/database/migrations/2022_10_27_044909_add_user_sms_verification_code.php index b0dcaa823b9d..f16ebe910ff8 100644 --- a/database/migrations/2022_10_27_044909_add_user_sms_verification_code.php +++ b/database/migrations/2022_10_27_044909_add_user_sms_verification_code.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -13,7 +12,7 @@ return new class extends Migration */ public function up() { - Schema::table('users', function (Blueprint $table) { + Schema::table('users', function (Blueprint $table) { $table->string('sms_verification_code', 191)->nullable(); }); } diff --git a/database/migrations/2022_11_02_063742_add_verified_number_flag_to_users_table.php b/database/migrations/2022_11_02_063742_add_verified_number_flag_to_users_table.php index 432a13c19744..91f35f7926da 100644 --- a/database/migrations/2022_11_02_063742_add_verified_number_flag_to_users_table.php +++ b/database/migrations/2022_11_02_063742_add_verified_number_flag_to_users_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * diff --git a/database/migrations/2022_11_04_013539_disabled_upstream_bank_integrations_table.php b/database/migrations/2022_11_04_013539_disabled_upstream_bank_integrations_table.php index 736de042740d..868c9002dee7 100644 --- a/database/migrations/2022_11_04_013539_disabled_upstream_bank_integrations_table.php +++ b/database/migrations/2022_11_04_013539_disabled_upstream_bank_integrations_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -13,11 +12,9 @@ return new class extends Migration */ public function up() { - Schema::table('bank_integrations', function (Blueprint $table) { $table->boolean('disabled_upstream')->default(false); }); - } /** diff --git a/database/migrations/2022_11_06_215526_drop_html_backups_column_from_backups_table.php b/database/migrations/2022_11_06_215526_drop_html_backups_column_from_backups_table.php index 9f35d53dddce..f2e1bfea3feb 100644 --- a/database/migrations/2022_11_06_215526_drop_html_backups_column_from_backups_table.php +++ b/database/migrations/2022_11_06_215526_drop_html_backups_column_from_backups_table.php @@ -1,13 +1,10 @@ dropColumn('html_backup'); }); } @@ -31,8 +25,6 @@ return new class extends Migration Schema::table('bank_integrations', function (Blueprint $table) { $table->boolean('auto_sync')->default(false); }); - - } /** diff --git a/database/migrations/2022_11_13_034143_bank_transaction_rules_table.php b/database/migrations/2022_11_13_034143_bank_transaction_rules_table.php index 7609d1a7d3fd..1ea4e59c9ee3 100644 --- a/database/migrations/2022_11_13_034143_bank_transaction_rules_table.php +++ b/database/migrations/2022_11_13_034143_bank_transaction_rules_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -13,7 +12,6 @@ return new class extends Migration */ public function up() { - Schema::create('bank_transaction_rules', function (Blueprint $table) { $table->id(); $table->unsignedInteger('company_id'); @@ -21,7 +19,7 @@ return new class extends Migration $table->string('name'); //name of rule $table->mediumText('rules')->nullable(); //array of rule objects - $table->boolean('auto_convert')->default(false); //auto convert to match + $table->boolean('auto_convert')->default(false); //auto convert to match $table->boolean('matches_on_all')->default(false); //match on all rules or just one $table->string('applies_to')->default('CREDIT'); //CREDIT/DEBIT @@ -36,8 +34,6 @@ return new class extends Migration $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade'); $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade'); }); - - } /** diff --git a/database/migrations/2022_11_16_093535_calmness_design.php b/database/migrations/2022_11_16_093535_calmness_design.php index 898d96549a87..895bfa3bef94 100644 --- a/database/migrations/2022_11_16_093535_calmness_design.php +++ b/database/migrations/2022_11_16_093535_calmness_design.php @@ -1,14 +1,10 @@ boolean('invoice_task_lock')->default(false); $table->boolean('use_vendor_currency')->default(false); }); - Schema::table('purchase_orders', function (Blueprint $table) - { + Schema::table('purchase_orders', function (Blueprint $table) { $table->unsignedInteger('currency_id')->nullable(); }); - Schema::table('bank_transactions', function (Blueprint $table) - { + Schema::table('bank_transactions', function (Blueprint $table) { $table->bigInteger('bank_transaction_rule_id')->nullable(); }); - Schema::table('subscriptions', function (Blueprint $table) - { + Schema::table('subscriptions', function (Blueprint $table) { $table->boolean('registration_required')->default(false); $table->boolean('use_inventory_management')->default(false); $table->text('optional_product_ids')->nullable(); $table->text('optional_recurring_product_ids')->nullable(); - }); $currencies = [ @@ -69,8 +62,6 @@ return new class extends Migration \Illuminate\Support\Facades\Artisan::call('ninja:design-update'); $this->buildCache(true); - - } /** diff --git a/database/migrations/2022_11_30_063229_add_payment_id_to_bank_transaction_table.php b/database/migrations/2022_11_30_063229_add_payment_id_to_bank_transaction_table.php index 08547668ebfa..affa8ec6ff57 100644 --- a/database/migrations/2022_11_30_063229_add_payment_id_to_bank_transaction_table.php +++ b/database/migrations/2022_11_30_063229_add_payment_id_to_bank_transaction_table.php @@ -5,9 +5,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ - +return new class extends Migration { use AppSetup; /** @@ -24,7 +22,6 @@ return new class extends Migration \Illuminate\Support\Facades\Artisan::call('ninja:design-update'); $this->buildCache(true); - } /** @@ -34,6 +31,5 @@ return new class extends Migration */ public function down() { - } }; diff --git a/database/migrations/2022_12_07_024625_add_properties_to_companies_table.php b/database/migrations/2022_12_07_024625_add_properties_to_companies_table.php index 78336ab3e2a8..3f3abd3eda0a 100644 --- a/database/migrations/2022_12_07_024625_add_properties_to_companies_table.php +++ b/database/migrations/2022_12_07_024625_add_properties_to_companies_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -26,6 +25,5 @@ return new class extends Migration */ public function down() { - } }; diff --git a/database/migrations/2022_12_20_063038_set_proforma_invoice_type.php b/database/migrations/2022_12_20_063038_set_proforma_invoice_type.php index 28dae37d58a9..dc28a0db225b 100644 --- a/database/migrations/2022_12_20_063038_set_proforma_invoice_type.php +++ b/database/migrations/2022_12_20_063038_set_proforma_invoice_type.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -13,17 +12,13 @@ return new class extends Migration */ public function up() { - - Schema::table('companies', function (Blueprint $table) - { + Schema::table('companies', function (Blueprint $table) { $table->boolean('notify_vendor_when_paid')->default(false); }); - Schema::table('invoices', function (Blueprint $table) - { + Schema::table('invoices', function (Blueprint $table) { $table->boolean('is_proforma')->default(false); }); - } /** diff --git a/database/migrations/2023_01_12_125540_set_auto_bill_on_regular_invoice_setting.php b/database/migrations/2023_01_12_125540_set_auto_bill_on_regular_invoice_setting.php index fade7d7ad3f4..5bbfc72610dd 100644 --- a/database/migrations/2023_01_12_125540_set_auto_bill_on_regular_invoice_setting.php +++ b/database/migrations/2023_01_12_125540_set_auto_bill_on_regular_invoice_setting.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -13,20 +12,15 @@ return new class extends Migration */ public function up() { - - Schema::table('accounts', function (Blueprint $table) - { + Schema::table('accounts', function (Blueprint $table) { $table->boolean('is_trial')->default(false); }); - Schema::table('companies', function (Blueprint $table) - { + Schema::table('companies', function (Blueprint $table) { $table->boolean('invoice_task_hours')->default(false); }); - Schema::table('schedulers', function (Blueprint $table) - { - + Schema::table('schedulers', function (Blueprint $table) { $table->dropColumn('repeat_every'); $table->dropColumn('start_from'); $table->dropColumn('scheduled_run'); @@ -34,13 +28,10 @@ return new class extends Migration $table->dropColumn('action_class'); $table->dropColumn('paused'); $table->dropColumn('company_id'); - }); - Schema::table('schedulers', function (Blueprint $table) - { - + Schema::table('schedulers', function (Blueprint $table) { $table->unsignedInteger('company_id'); $table->boolean('is_paused')->default(false); $table->unsignedInteger('frequency_id')->nullable(); @@ -54,9 +45,7 @@ return new class extends Migration $table->unique(['company_id', 'name']); $table->index(['company_id', 'deleted_at']); - }); - } /** diff --git a/database/migrations/2023_01_27_023127_update_design_templates.php b/database/migrations/2023_01_27_023127_update_design_templates.php index f0f45d4a4bb2..9b6265db822b 100644 --- a/database/migrations/2023_01_27_023127_update_design_templates.php +++ b/database/migrations/2023_01_27_023127_update_design_templates.php @@ -1,11 +1,8 @@ boolean('require_custom_value1')->default(false); $table->boolean('require_custom_value2')->default(false); $table->boolean('require_custom_value3')->default(false); $table->boolean('require_custom_value4')->default(false); - }); - } /** diff --git a/database/migrations/2023_02_07_114011_add_additional_product_fields.php b/database/migrations/2023_02_07_114011_add_additional_product_fields.php index 55f3e701666d..038927e3045b 100644 --- a/database/migrations/2023_02_07_114011_add_additional_product_fields.php +++ b/database/migrations/2023_02_07_114011_add_additional_product_fields.php @@ -5,8 +5,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -14,26 +13,20 @@ return new class extends Migration */ public function up() { - Schema::table('products', function (Blueprint $table){ + Schema::table('products', function (Blueprint $table) { $table->unsignedInteger("max_quantity")->nullable(); $table->string("product_image", 191)->nullable(); }); Company::query() ->chunk(1000, function ($companies) { - - foreach($companies as $c) - { - - $settings = $c->settings; - $settings->font_size = 16; - $c->settings = $settings; - $c->save(); - - } - - }); - + foreach ($companies as $c) { + $settings = $c->settings; + $settings->font_size = 16; + $c->settings = $settings; + $c->save(); + } + }); } /** diff --git a/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php b/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php index 281b7d8e4c9d..a763630ffbf8 100644 --- a/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php +++ b/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php @@ -4,8 +4,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; -return new class extends Migration -{ +return new class extends Migration { /** * Run the migrations. * @@ -14,11 +13,9 @@ return new class extends Migration public function up() { Schema::table('company_user', function (Blueprint $table) { - $table->mediumText('react_settings')->nullable(); \Illuminate\Support\Facades\Artisan::call('ninja:design-update'); - }); } @@ -29,6 +26,5 @@ return new class extends Migration */ public function down() { - } }; diff --git a/database/seeders/LanguageSeeder.php b/database/seeders/LanguageSeeder.php index fdb6e5f07e06..1291b915014e 100644 --- a/database/seeders/LanguageSeeder.php +++ b/database/seeders/LanguageSeeder.php @@ -69,39 +69,29 @@ class LanguageSeeder extends Seeder } } - if(!Language::find(33)) { - + if (!Language::find(33)) { $serbian = ['id' => 33, 'name' => 'Serbian', 'locale' => 'sr']; Language::create($serbian); - } - if(!Language::find(34)) { - + if (!Language::find(34)) { $slovak = ['id' => 34, 'name' => 'Slovak', 'locale' => 'sk']; Language::create($slovak); - } - if(!Language::find(35)) { - + if (!Language::find(35)) { $estonia = ['id' => 35, 'name' => 'Estonian', 'locale' => 'et']; Language::create($estonia); - } - if(!Language::find(36)) { - + if (!Language::find(36)) { $bulgarian = ['id' => 36, 'name' => 'Bulgarian', 'locale' => 'bg']; Language::create($bulgarian); - } - if(!Language::find(37)) { - + if (!Language::find(37)) { $hebrew = ['id' => 37, 'name' => 'Hebrew', 'locale' => 'he']; Language::create($hebrew); - } } } diff --git a/database/seeders/PaymentLibrariesSeeder.php b/database/seeders/PaymentLibrariesSeeder.php index a62240ed6779..b7420fb8c4ee 100644 --- a/database/seeders/PaymentLibrariesSeeder.php +++ b/database/seeders/PaymentLibrariesSeeder.php @@ -6,7 +6,7 @@ * * @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com) * - * @license https://www.elastic.co/licensing/elastic-license + * @license https://www.elastic.co/licensing/elastic-license */ namespace Database\Seeders; diff --git a/database/seeders/RandomDataSeeder.php b/database/seeders/RandomDataSeeder.php index 0659acb5eee6..50a6e5318d1f 100644 --- a/database/seeders/RandomDataSeeder.php +++ b/database/seeders/RandomDataSeeder.php @@ -54,7 +54,6 @@ class RandomDataSeeder extends Seeder */ public function run() { - /* Warm up the cache !*/ $cached_tables = config('ninja.cached_tables'); @@ -209,7 +208,6 @@ class RandomDataSeeder extends Seeder $credit->save(); $credit->service()->createInvitations()->markSent()->save(); - }); /* Recurring Invoice Factory */ diff --git a/lang/ar/texts.php b/lang/ar/texts.php index 4b3ae06c598f..2e86a79024ce 100644 --- a/lang/ar/texts.php +++ b/lang/ar/texts.php @@ -1,6 +1,6 @@ 'الشركة ', 'name' => 'الاسم', 'website' => 'الموقع الإلكتروني', @@ -4928,7 +4928,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4943,8 +4943,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/bg/texts.php b/lang/bg/texts.php index 8e9622e1e121..31d24cf5083f 100644 --- a/lang/bg/texts.php +++ b/lang/bg/texts.php @@ -1,6 +1,6 @@ 'Организация', 'name' => 'Име', 'website' => 'Уебсайт', @@ -4908,7 +4908,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4923,8 +4923,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/ca/texts.php b/lang/ca/texts.php index 9e39dc34fb69..3f06d96fc406 100644 --- a/lang/ca/texts.php +++ b/lang/ca/texts.php @@ -1,6 +1,6 @@ 'Organització', 'name' => 'Nom', 'website' => 'Lloc web', @@ -4902,7 +4902,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4917,8 +4917,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/cs/texts.php b/lang/cs/texts.php index 404b630dacf4..446f800cbf99 100644 --- a/lang/cs/texts.php +++ b/lang/cs/texts.php @@ -1,6 +1,6 @@ 'Organizace', 'name' => 'Název', 'website' => 'Stránky', @@ -4907,7 +4907,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/da/texts.php b/lang/da/texts.php index a60ae3cbb627..5c16f1d3781f 100644 --- a/lang/da/texts.php +++ b/lang/da/texts.php @@ -1,6 +1,6 @@ 'Organisation', 'name' => 'Navn', 'website' => 'Hjemmeside', @@ -4906,7 +4906,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4921,8 +4921,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/de/texts.php b/lang/de/texts.php index 381e9cea0a71..b7e30c8ae3fa 100644 --- a/lang/de/texts.php +++ b/lang/de/texts.php @@ -1,6 +1,6 @@ 'Unternehmen', 'name' => 'Name', 'website' => 'Webseite', @@ -4910,7 +4910,7 @@ https://invoiceninja.github.io/docs/migration/#troubleshooting', 'export_company' => 'Unternehmens Sicherungskopie erstellen', 'backup' => 'Sicherungskopie', 'notification_purchase_order_created_body' => 'Die folgende Bestellung :purchase_order wurde für den Lieferant :vendor in Höhe von :amount erstellt.', - 'notification_purchase_order_created_subject' => 'Bestellung :purchase_order wurde für :vendor erstellt', + 'notification_purchase_order_created_subject' => 'Bestellung :purchase_order wurde für :vendor erstellt', 'notification_purchase_order_sent_subject' => 'Bestellung :purchase_order wurde an :vendor gesendet', 'notification_purchase_order_sent' => 'Der folgende Lieferant :vendor hat eine Bestellung :purchase_order über :amount erhalten.', 'subscription_blocked' => 'Dieses Produkt ist ein eingeschränkter Artikel, bitte kontaktieren Sie den Lieferant für weitere Informationen.', @@ -4925,8 +4925,6 @@ https://invoiceninja.github.io/docs/migration/#troubleshooting', 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo ID', 'action_add_to_invoice' => 'Zur Rechnung hinzufügen', -); +]; return $LANG; - -?> diff --git a/lang/el/texts.php b/lang/el/texts.php index 1bfb24ce4651..7571fbe703e9 100644 --- a/lang/el/texts.php +++ b/lang/el/texts.php @@ -1,6 +1,6 @@ 'Οργανισμός', 'name' => 'Επωνυμία', 'website' => 'Ιστοσελίδα', @@ -4907,7 +4907,7 @@ email που είναι συνδεδεμένη με το λογαριασμό σ 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ email που είναι συνδεδεμένη με το λογαριασμό σ 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/en/texts.php b/lang/en/texts.php index dd851787bb5b..7c3a28af4e1b 100644 --- a/lang/en/texts.php +++ b/lang/en/texts.php @@ -1,6 +1,6 @@ 'Organization', 'name' => 'Name', 'website' => 'Website', @@ -4908,7 +4908,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4953,9 +4953,7 @@ $LANG = array( 'markup' => 'Markup', 'unlock_pro' => 'Unlock Pro', 'preferences' => 'Preferences' -); +]; return $LANG; - -?> diff --git a/lang/en_GB/texts.php b/lang/en_GB/texts.php index 1fd6dfc5ab52..b80c6e368524 100644 --- a/lang/en_GB/texts.php +++ b/lang/en_GB/texts.php @@ -1,6 +1,6 @@ 'Organisation', 'name' => 'Name', 'website' => 'Website', @@ -4908,7 +4908,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4923,8 +4923,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/es/texts.php b/lang/es/texts.php index a18ee8e23f15..0e0f21b7528e 100644 --- a/lang/es/texts.php +++ b/lang/es/texts.php @@ -1,6 +1,6 @@ 'Empresa', 'name' => 'Nombre', 'website' => 'Sitio Web', @@ -4905,7 +4905,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4920,8 +4920,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/es_ES/texts.php b/lang/es_ES/texts.php index b959d47b5cdc..8c7291c928a4 100644 --- a/lang/es_ES/texts.php +++ b/lang/es_ES/texts.php @@ -1,6 +1,6 @@ 'Organización', 'name' => 'Nombre', 'website' => 'Página Web', @@ -4897,7 +4897,7 @@ Una vez que tenga los montos, vuelva a esta página de métodos de pago y haga c 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4912,8 +4912,6 @@ Una vez que tenga los montos, vuelva a esta página de métodos de pago y haga c 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/et/texts.php b/lang/et/texts.php index 5dd80f4aaf79..10cf428ab5ac 100644 --- a/lang/et/texts.php +++ b/lang/et/texts.php @@ -1,6 +1,6 @@ 'Organisatsioon', 'name' => 'Nimi', 'website' => 'Kodulehekülg', @@ -4904,7 +4904,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4919,8 +4919,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/fa/texts.php b/lang/fa/texts.php index 84cc31cb375f..4fee58be66bf 100644 --- a/lang/fa/texts.php +++ b/lang/fa/texts.php @@ -1,6 +1,6 @@ 'شرکت', 'name' => 'نام', 'website' => 'وب سایت', @@ -4907,7 +4907,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/fi/texts.php b/lang/fi/texts.php index e67bedc21ea6..054e25d770f7 100644 --- a/lang/fi/texts.php +++ b/lang/fi/texts.php @@ -1,6 +1,6 @@ 'Yritys', 'name' => 'Nimi', 'website' => 'Kotisivu', @@ -4907,7 +4907,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/fr/texts.php b/lang/fr/texts.php index 878c9bd0ba1e..725d4ce3be54 100644 --- a/lang/fr/texts.php +++ b/lang/fr/texts.php @@ -1,6 +1,6 @@ 'Entreprise', 'name' => 'Nom', 'website' => 'Site Web', @@ -4901,7 +4901,7 @@ Lorsque les montant apparaîtront sur votre relevé, veuillez revenir sur cette 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4916,8 +4916,6 @@ Lorsque les montant apparaîtront sur votre relevé, veuillez revenir sur cette 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/fr_CA/texts.php b/lang/fr_CA/texts.php index 804f48a5789c..e245a41271a9 100644 --- a/lang/fr_CA/texts.php +++ b/lang/fr_CA/texts.php @@ -1,6 +1,6 @@ 'Entreprise', 'name' => 'Nom', 'website' => 'Site web', @@ -4899,7 +4899,7 @@ Lorsque les montant apparaîtront sur votre relevé, veuillez revenir sur cette 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4914,8 +4914,6 @@ Lorsque les montant apparaîtront sur votre relevé, veuillez revenir sur cette 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/he/texts.php b/lang/he/texts.php index 6123bb15ed35..02b0f4cfe7c4 100644 --- a/lang/he/texts.php +++ b/lang/he/texts.php @@ -1,6 +1,6 @@ 'ארגון ', 'name' => 'שם', 'website' => 'אתר אינטרנט', @@ -4900,7 +4900,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4915,8 +4915,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/hr/texts.php b/lang/hr/texts.php index 94925e687748..d4663611e631 100644 --- a/lang/hr/texts.php +++ b/lang/hr/texts.php @@ -1,6 +1,6 @@ 'Organizacija', 'name' => 'Ime', 'website' => 'Web', @@ -4908,7 +4908,7 @@ Nevažeći kontakt email', 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4923,8 +4923,6 @@ Nevažeći kontakt email', 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/it/texts.php b/lang/it/texts.php index d81634c2da4a..7a1e91f8a7f1 100644 --- a/lang/it/texts.php +++ b/lang/it/texts.php @@ -1,6 +1,6 @@ 'Organizzazione', 'name' => 'Nome', 'website' => 'Sito web', @@ -4910,7 +4910,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4925,8 +4925,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/ja/texts.php b/lang/ja/texts.php index 355d911f93dd..0a0bc3b1a8bf 100644 --- a/lang/ja/texts.php +++ b/lang/ja/texts.php @@ -1,6 +1,6 @@ '組織', 'name' => '名前', 'website' => 'WEBサイト', @@ -4907,7 +4907,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/lt/texts.php b/lang/lt/texts.php index 9d105ef6a0ae..b423f3b5dc93 100644 --- a/lang/lt/texts.php +++ b/lang/lt/texts.php @@ -1,6 +1,6 @@ 'Įmonė', 'name' => 'Pavadinimas', 'website' => 'Internetinis puslapis', @@ -4907,7 +4907,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/lv_LV/texts.php b/lang/lv_LV/texts.php index 9d41588662a0..05a407bbc9f8 100644 --- a/lang/lv_LV/texts.php +++ b/lang/lv_LV/texts.php @@ -1,6 +1,6 @@ 'Uzņēmums', 'name' => 'Nosaukums', 'website' => 'Mājas lapa', @@ -4907,7 +4907,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/mk_MK/texts.php b/lang/mk_MK/texts.php index badd60d36290..57403832dbe3 100644 --- a/lang/mk_MK/texts.php +++ b/lang/mk_MK/texts.php @@ -1,6 +1,6 @@ 'Организација', 'name' => 'Име', 'website' => 'Веб Страна', @@ -4908,7 +4908,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4923,8 +4923,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/nb_NO/texts.php b/lang/nb_NO/texts.php index 269677f60fb3..df957da11864 100644 --- a/lang/nb_NO/texts.php +++ b/lang/nb_NO/texts.php @@ -1,6 +1,6 @@ 'Organisasjon', 'name' => 'Navn', 'website' => 'Nettside', @@ -4907,7 +4907,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/nl/texts.php b/lang/nl/texts.php index e29db171503e..be0baa4481e7 100644 --- a/lang/nl/texts.php +++ b/lang/nl/texts.php @@ -1,6 +1,6 @@ 'Organisatie', 'name' => 'Naam', 'website' => 'Website', @@ -4901,7 +4901,7 @@ Email: :email
', 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4916,8 +4916,6 @@ Email: :email
', 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/pl/texts.php b/lang/pl/texts.php index c8f67fa6af42..7ab9092c514e 100644 --- a/lang/pl/texts.php +++ b/lang/pl/texts.php @@ -1,6 +1,6 @@ 'Organizacja', 'name' => 'Nazwa', 'website' => 'Strona internetowa', @@ -4904,7 +4904,7 @@ Gdy przelewy zostaną zaksięgowane na Twoim koncie, wróć do tej strony i klik 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4919,8 +4919,6 @@ Gdy przelewy zostaną zaksięgowane na Twoim koncie, wróć do tej strony i klik 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/pt_BR/texts.php b/lang/pt_BR/texts.php index 2a29da257d31..f811c6d2e50f 100644 --- a/lang/pt_BR/texts.php +++ b/lang/pt_BR/texts.php @@ -1,6 +1,6 @@ 'Empresa', 'name' => 'Nome', 'website' => 'Website', @@ -4901,7 +4901,7 @@ Quando tiver as quantias, volte a esta página de formas de pagamento e clique " 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4916,8 +4916,6 @@ Quando tiver as quantias, volte a esta página de formas de pagamento e clique " 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/pt_PT/texts.php b/lang/pt_PT/texts.php index 51cedad607cd..04b9ee53db8e 100644 --- a/lang/pt_PT/texts.php +++ b/lang/pt_PT/texts.php @@ -1,6 +1,6 @@ 'Organização', 'name' => 'Nome', 'website' => 'Site', @@ -4904,7 +4904,7 @@ O envio de E-mails foi suspenso. Será retomado às 23:00 UTC.', 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4919,8 +4919,6 @@ O envio de E-mails foi suspenso. Será retomado às 23:00 UTC.', 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/ro/texts.php b/lang/ro/texts.php index ba7f1abd0f33..13da5b986dea 100644 --- a/lang/ro/texts.php +++ b/lang/ro/texts.php @@ -1,6 +1,6 @@ 'Organizație', 'name' => 'Nume', 'website' => 'Site web', @@ -4911,7 +4911,7 @@ Odată ce sumele au ajuns la dumneavoastră, reveniți la pagina cu metode de pl 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4926,8 +4926,6 @@ Odată ce sumele au ajuns la dumneavoastră, reveniți la pagina cu metode de pl 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/ru_RU/texts.php b/lang/ru_RU/texts.php index 6ef760e6c3be..ac6debf474c2 100644 --- a/lang/ru_RU/texts.php +++ b/lang/ru_RU/texts.php @@ -1,6 +1,6 @@ 'Организация', 'name' => 'Название', 'website' => 'Веб-сайт', @@ -4908,7 +4908,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4923,8 +4923,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/sk/texts.php b/lang/sk/texts.php index 7851b7ede3f5..a2cc7a2f484b 100644 --- a/lang/sk/texts.php +++ b/lang/sk/texts.php @@ -1,6 +1,6 @@ 'Organizácia', 'name' => 'Meno', 'website' => 'Web', @@ -4904,7 +4904,7 @@ Nemôžete nájsť faktúru? Potrebujete poradiť? Radi Vám pomôžeme 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4919,8 +4919,6 @@ Nemôžete nájsť faktúru? Potrebujete poradiť? Radi Vám pomôžeme 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/sl/texts.php b/lang/sl/texts.php index ca8f29c41e2b..4fbe1f212289 100644 --- a/lang/sl/texts.php +++ b/lang/sl/texts.php @@ -1,6 +1,6 @@ 'Organizacija', 'name' => 'Ime', 'website' => 'Spletna stran', @@ -4907,7 +4907,7 @@ Ko imate zneske, se vrnite na to stran plačilnega sredstva in kliknite na "Comp 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ Ko imate zneske, se vrnite na to stran plačilnega sredstva in kliknite na "Comp 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/sq/texts.php b/lang/sq/texts.php index f49b00457bd9..16281bfa0e96 100644 --- a/lang/sq/texts.php +++ b/lang/sq/texts.php @@ -1,6 +1,6 @@ 'Organizata', 'name' => 'Emri', 'website' => 'Website', @@ -4905,7 +4905,7 @@ Pasi të keni pranuar shumat, kthehuni në faqen e metodave të pagesës dhe kli 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4920,8 +4920,6 @@ Pasi të keni pranuar shumat, kthehuni në faqen e metodave të pagesës dhe kli 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/sr/texts.php b/lang/sr/texts.php index f0eb40e2673f..fb06a089b0a9 100644 --- a/lang/sr/texts.php +++ b/lang/sr/texts.php @@ -1,6 +1,6 @@ 'Organizacija', 'name' => 'Ime', 'website' => 'Sajt', @@ -4907,7 +4907,7 @@ Kada budete imali iznose, vratite se na ovu stranicu sa načinima plaćanja i k 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4922,8 +4922,6 @@ Kada budete imali iznose, vratite se na ovu stranicu sa načinima plaćanja i k 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/sv/texts.php b/lang/sv/texts.php index e12083139bc9..67d8904f8ce4 100644 --- a/lang/sv/texts.php +++ b/lang/sv/texts.php @@ -1,6 +1,6 @@ 'Organisation', 'name' => 'Namn', 'website' => 'Hemsida', @@ -4914,7 +4914,7 @@ Den här funktionen kräver att en produkt skapas och en betalningsgateway är k 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4929,8 +4929,6 @@ Den här funktionen kräver att en produkt skapas och en betalningsgateway är k 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/th/texts.php b/lang/th/texts.php index 27a7a7242b3c..d99ca1899cda 100644 --- a/lang/th/texts.php +++ b/lang/th/texts.php @@ -1,6 +1,6 @@ 'องค์กร', 'name' => 'ชื่อ', 'website' => 'เว็บไซต์', @@ -4908,7 +4908,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4923,8 +4923,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/tr_TR/texts.php b/lang/tr_TR/texts.php index 70774aab0f52..e21b3b289a05 100644 --- a/lang/tr_TR/texts.php +++ b/lang/tr_TR/texts.php @@ -1,6 +1,6 @@ 'Şirket', 'name' => 'Ünvan', 'website' => 'Web adresi', @@ -4906,7 +4906,7 @@ adresine gönderildi. Müthiş tüm özelliklerin kilidini açmak için lütfen 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4921,8 +4921,6 @@ adresine gönderildi. Müthiş tüm özelliklerin kilidini açmak için lütfen 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/lang/zh_TW/texts.php b/lang/zh_TW/texts.php index 75522b696149..cc073088e541 100644 --- a/lang/zh_TW/texts.php +++ b/lang/zh_TW/texts.php @@ -1,6 +1,6 @@ '組織', 'name' => '姓名', 'website' => '網站', @@ -4904,7 +4904,7 @@ $LANG = array( 'export_company' => 'Create company backup', 'backup' => 'Backup', 'notification_purchase_order_created_body' => 'The following purchase_order :purchase_order was created for vendor :vendor for :amount.', - 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', + 'notification_purchase_order_created_subject' => 'Purchase Order :purchase_order was created for :vendor', 'notification_purchase_order_sent_subject' => 'Purchase Order :purchase_order was sent to :vendor', 'notification_purchase_order_sent' => 'The following vendor :vendor was emailed Purchase Order :purchase_order for :amount.', 'subscription_blocked' => 'This product is a restricted item, please contact the vendor for further information.', @@ -4919,8 +4919,6 @@ $LANG = array( 'matomo_url' => 'Matomo URL', 'matomo_id' => 'Matomo Id', 'action_add_to_invoice' => 'Add To Invoice', -); +]; return $LANG; - -?> diff --git a/preload.php b/preload.php index 6bf7ece52e44..f7a8f68a76c7 100644 --- a/preload.php +++ b/preload.php @@ -133,4 +133,4 @@ class Preloader \Illuminate\Http\UploadedFile::class, \Illuminate\Support\Carbon::class, ) - ->load(); \ No newline at end of file + ->load(); diff --git a/routes/api.php b/routes/api.php index b3c52da44482..7b2809a7a472 100644 --- a/routes/api.php +++ b/routes/api.php @@ -14,10 +14,10 @@ use App\Http\Controllers\AccountController; use App\Http\Controllers\ActivityController; use App\Http\Controllers\Auth\ForgotPasswordController; use App\Http\Controllers\Auth\LoginController; +use App\Http\Controllers\Bank\YodleeController; use App\Http\Controllers\BankIntegrationController; use App\Http\Controllers\BankTransactionController; use App\Http\Controllers\BankTransactionRuleController; -use App\Http\Controllers\Bank\YodleeController; use App\Http\Controllers\BaseController; use App\Http\Controllers\ChartController; use App\Http\Controllers\ClientController; @@ -350,7 +350,6 @@ Route::group(['middleware' => ['throttle:300,1', 'api_db', 'token_auth', 'locale Route::post('subscriptions/bulk', [SubscriptionController::class, 'bulk'])->name('subscriptions.bulk'); Route::get('statics', StaticController::class); // Route::post('apple_pay/upload_file','ApplyPayController::class, 'upload'); - }); Route::post('api/v1/sms_reset', [TwilioController::class, 'generate2faResetCode'])->name('sms_reset.generate')->middleware('throttle:10,1'); @@ -376,4 +375,4 @@ Route::post('api/v1/yodlee/data_updates', [YodleeController::class, 'dataUpdates Route::post('api/v1/yodlee/refresh_updates', [YodleeController::class, 'refreshUpdatesWebhook'])->middleware('throttle:100,1'); Route::post('api/v1/yodlee/balance', [YodleeController::class, 'balanceWebhook'])->middleware('throttle:100,1'); -Route::fallback([BaseController::class, 'notFound']); \ No newline at end of file +Route::fallback([BaseController::class, 'notFound']); diff --git a/routes/client.php b/routes/client.php index c02a23cb26a3..b77efaf61c7b 100644 --- a/routes/client.php +++ b/routes/client.php @@ -5,7 +5,6 @@ use App\Http\Controllers\Auth\ContactLoginController; use App\Http\Controllers\Auth\ContactRegisterController; use App\Http\Controllers\Auth\ContactResetPasswordController; use App\Http\Controllers\BaseController; -use App\Http\Controllers\ClientPortal\DocumentController; use App\Http\Controllers\ClientPortal\PaymentMethodController; use App\Http\Controllers\ClientPortal\SubscriptionController; use App\Http\Controllers\ClientPortal\TaskController; @@ -45,7 +44,6 @@ Route::get('client/ninja/{contact_key}/{company_key}', [App\Http\Controllers\Cli Route::post('client/ninja/trial_confirmation', [App\Http\Controllers\ClientPortal\NinjaPlanController::class, 'trial_confirmation'])->name('client.trial.response')->middleware(['domain_db']); Route::group(['middleware' => ['auth:contact', 'locale', 'domain_db','check_client_existence'], 'prefix' => 'client', 'as' => 'client.'], function () { - Route::get('dashboard', [App\Http\Controllers\ClientPortal\DashboardController::class, 'index'])->name('dashboard'); // name = (dashboard. index / create / show / update / destroy / edit Route::get('plan', [App\Http\Controllers\ClientPortal\NinjaPlanController::class, 'plan'])->name('plan'); // name = (dashboard. index / create / show / update / destroy / edit @@ -109,7 +107,6 @@ Route::group(['middleware' => ['auth:contact', 'locale', 'domain_db','check_clie Route::post('upload', App\Http\Controllers\ClientPortal\UploadController::class)->name('upload.store'); Route::get('logout', [ContactLoginController::class, 'logout'])->name('logout'); - }); Route::post('payments/process/response', [App\Http\Controllers\ClientPortal\PaymentController::class, 'response'])->name('client.payments.response')->middleware(['locale', 'domain_db', 'verify_hash']); @@ -133,9 +130,8 @@ Route::group(['middleware' => ['invite_db'], 'prefix' => 'client', 'as' => 'clie Route::get('pay/{invitation_key}', [App\Http\Controllers\ClientPortal\InvitationController::class, 'payInvoice'])->name('pay.invoice'); Route::get('unsubscribe/{entity}/{invitation_key}', [App\Http\Controllers\ClientPortal\InvitationController::class, 'unsubscribe'])->name('unsubscribe'); - }); Route::get('phantom/{entity}/{invitation_key}', [Phantom::class, 'displayInvitation'])->middleware(['invite_db', 'phantom_secret'])->name('phantom_view'); -Route::fallback([BaseController::class, 'notFoundClient']); \ No newline at end of file +Route::fallback([BaseController::class, 'notFoundClient']); diff --git a/routes/web.php b/routes/web.php index 26ddc312bec6..2a47d1bf4cde 100644 --- a/routes/web.php +++ b/routes/web.php @@ -18,7 +18,7 @@ use Illuminate\Support\Facades\Route; //Auth::routes(['password.reset' => false]); Route::get('/', [BaseController::class, 'flutterRoute'])->middleware('guest'); - // Route::get('self-update', [SelfUpdateController::class, 'update'])->middleware('guest'); +// Route::get('self-update', [SelfUpdateController::class, 'update'])->middleware('guest'); Route::get('setup', [SetupController::class, 'index'])->middleware('guest'); Route::post('setup', [SetupController::class, 'doSetup'])->middleware('guest'); @@ -58,4 +58,4 @@ Route::get('yodlee/onboard/{token}', [YodleeController::class, 'auth'])->name('y Route::get('checkout/3ds_redirect/{company_key}/{company_gateway_id}/{hash}', [Checkout3dsController::class, 'index'])->middleware('domain_db')->name('checkout.3ds_redirect'); Route::get('mollie/3ds_redirect/{company_key}/{company_gateway_id}/{hash}', [Mollie3dsController::class, 'index'])->middleware('domain_db')->name('mollie.3ds_redirect'); Route::get('gocardless/ibp_redirect/{company_key}/{company_gateway_id}/{hash}', [GoCardlessController::class, 'ibpRedirect'])->middleware('domain_db')->name('gocardless.ibp_redirect'); -Route::get('.well-known/apple-developer-merchantid-domain-association', [ApplePayDomainController::class, 'showAppleMerchantId']); \ No newline at end of file +Route::get('.well-known/apple-developer-merchantid-domain-association', [ApplePayDomainController::class, 'showAppleMerchantId']); diff --git a/tests/Browser/ClientPortal/Gateways/Braintree/ACHTest.php b/tests/Browser/ClientPortal/Gateways/Braintree/ACHTest.php index e884e63ed64c..580eb4cf95eb 100644 --- a/tests/Browser/ClientPortal/Gateways/Braintree/ACHTest.php +++ b/tests/Browser/ClientPortal/Gateways/Braintree/ACHTest.php @@ -6,7 +6,6 @@ use App\DataMapper\FeesAndLimits; use App\Models\Company; use App\Models\CompanyGateway; use App\Models\GatewayType; -use Illuminate\Foundation\Testing\DatabaseMigrations; use Laravel\Dusk\Browser; use Tests\Browser\Pages\ClientPortal\Login; use Tests\DuskTestCase; diff --git a/tests/Browser/ClientPortal/Gateways/Braintree/CreditCardTest.php b/tests/Browser/ClientPortal/Gateways/Braintree/CreditCardTest.php index ef125ab77981..9dc3fdb5a72c 100644 --- a/tests/Browser/ClientPortal/Gateways/Braintree/CreditCardTest.php +++ b/tests/Browser/ClientPortal/Gateways/Braintree/CreditCardTest.php @@ -16,7 +16,6 @@ use App\DataMapper\FeesAndLimits; use App\Models\Company; use App\Models\CompanyGateway; use App\Models\GatewayType; -use App\Models\Invoice; use Laravel\Dusk\Browser; use Tests\Browser\Pages\ClientPortal\Login; use Tests\DuskTestCase; diff --git a/tests/Browser/ClientPortal/Gateways/Stripe/AlipayTest.php b/tests/Browser/ClientPortal/Gateways/Stripe/AlipayTest.php index 68f7435ce425..b58545eb3a7d 100644 --- a/tests/Browser/ClientPortal/Gateways/Stripe/AlipayTest.php +++ b/tests/Browser/ClientPortal/Gateways/Stripe/AlipayTest.php @@ -16,7 +16,6 @@ use App\DataMapper\FeesAndLimits; use App\Models\Client; use App\Models\CompanyGateway; use App\Models\GatewayType; -use Illuminate\Foundation\Testing\DatabaseMigrations; use Laravel\Dusk\Browser; use Tests\Browser\Pages\ClientPortal\Login; use Tests\DuskTestCase; diff --git a/tests/Browser/ClientPortal/LoginTest.php b/tests/Browser/ClientPortal/LoginTest.php index 407e2f3c2999..e8934b6b6574 100644 --- a/tests/Browser/ClientPortal/LoginTest.php +++ b/tests/Browser/ClientPortal/LoginTest.php @@ -12,7 +12,6 @@ namespace Tests\Browser\ClientPortal; -use Illuminate\Foundation\Testing\DatabaseMigrations; use Laravel\Dusk\Browser; use Tests\DuskTestCase; diff --git a/tests/Browser/ClientPortal/QuotesTest.php b/tests/Browser/ClientPortal/QuotesTest.php index b05c8992f506..ce4b024fe8fb 100644 --- a/tests/Browser/ClientPortal/QuotesTest.php +++ b/tests/Browser/ClientPortal/QuotesTest.php @@ -12,7 +12,6 @@ namespace Tests\Browser\ClientPortal; -use App\Models\Quote; use Laravel\Dusk\Browser; use Tests\Browser\Pages\ClientPortal\Login; use Tests\DuskTestCase; diff --git a/tests/DuskTestCase.php b/tests/DuskTestCase.php index 7521085d9880..590eaa3eb96b 100644 --- a/tests/DuskTestCase.php +++ b/tests/DuskTestCase.php @@ -44,7 +44,8 @@ abstract class DuskTestCase extends BaseTestCase return RemoteWebDriver::create( $_ENV['DUSK_DRIVER_URL'] ?? 'http://localhost:9515', DesiredCapabilities::chrome()->setCapability( - ChromeOptions::CAPABILITY, $options + ChromeOptions::CAPABILITY, + $options ) ); } diff --git a/tests/Feature/Account/AccountEmailQuotaTest.php b/tests/Feature/Account/AccountEmailQuotaTest.php index 408a33754c95..0ddd3142a3c5 100644 --- a/tests/Feature/Account/AccountEmailQuotaTest.php +++ b/tests/Feature/Account/AccountEmailQuotaTest.php @@ -18,13 +18,10 @@ use App\Models\Account; use App\Models\Company; use App\Utils\Ninja; use Illuminate\Support\Facades\Cache; -use Livewire\Livewire; -use Tests\MockAccountData; use Tests\TestCase; class AccountEmailQuotaTest extends TestCase { - protected function setUp(): void { parent::setUp(); @@ -33,7 +30,6 @@ class AccountEmailQuotaTest extends TestCase public function testIfQuotaBreached() { - config([ 'ninja.production' => true ]); @@ -92,12 +88,10 @@ class AccountEmailQuotaTest extends TestCase $this->assertTrue($account->emailQuotaExceeded()); Cache::forget('123ifyouknowwhatimean'); - } public function testQuotaValidRule() { - $account = Account::factory()->create([ 'hosted_client_count' => 1000, 'hosted_company_count' => 1000, @@ -115,7 +109,6 @@ class AccountEmailQuotaTest extends TestCase $this->assertFalse($account->emailQuotaExceeded()); Cache::forget('123ifyouknowwhatimean'); - } public function testEmailSentCount() @@ -140,7 +133,5 @@ class AccountEmailQuotaTest extends TestCase $this->assertEquals(3000, $count); Cache::forget('123ifyouknowwhatimean'); - } - } diff --git a/tests/Feature/ActivityApiTest.php b/tests/Feature/ActivityApiTest.php index 115bed1732fc..271b54d2ad0c 100644 --- a/tests/Feature/ActivityApiTest.php +++ b/tests/Feature/ActivityApiTest.php @@ -55,5 +55,4 @@ class ActivityApiTest extends TestCase $response->assertStatus(200); } - } diff --git a/tests/Feature/ApplePayDomainMerchantUrlTest.php b/tests/Feature/ApplePayDomainMerchantUrlTest.php index 8082bd3f131a..173d007bda2e 100644 --- a/tests/Feature/ApplePayDomainMerchantUrlTest.php +++ b/tests/Feature/ApplePayDomainMerchantUrlTest.php @@ -40,7 +40,7 @@ class ApplePayDomainMerchantUrlTest extends TestCase public function testMerchantFieldGet() { // if (! config('ninja.testvars.stripe')) { - $this->markTestSkipped('Skip test no company gateways installed'); + $this->markTestSkipped('Skip test no company gateways installed'); // } $config = new \stdClass; diff --git a/tests/Feature/Bank/BankTransactionRuleTest.php b/tests/Feature/Bank/BankTransactionRuleTest.php index f6a1051d968c..7c014d5ba206 100644 --- a/tests/Feature/Bank/BankTransactionRuleTest.php +++ b/tests/Feature/Bank/BankTransactionRuleTest.php @@ -12,13 +12,9 @@ namespace Tests\Feature\Bank; -use App\Factory\BankIntegrationFactory; -use App\Factory\BankTransactionFactory; use App\Models\BankIntegration; use App\Models\BankTransaction; use App\Models\BankTransactionRule; -use App\Models\Invoice; -use App\Services\Bank\ProcessBankRules; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Validation\ValidationException; use Tests\MockAccountData; @@ -44,15 +40,12 @@ class BankTransactionRuleTest extends TestCase public function testMatchingWithStripos() { - - $bt_value = strtolower(str_replace(" ", "", 'hello soldier')); $rule_value = strtolower(str_replace(" ", "", 'solider')); $rule_length = iconv_strlen($rule_value); - $this->assertFalse(stripos($rule_value, $bt_value) !== false); + $this->assertFalse(stripos($rule_value, $bt_value) !== false); $this->assertFalse(stripos($bt_value, $rule_value) !== false); - } public function testBankRuleBulkActions() @@ -89,12 +82,10 @@ class BankTransactionRuleTest extends TestCase 'X-API-TOKEN' => $this->token, ])->post('/api/v1/bank_transaction_rules/bulk', $data) ->assertStatus(200); - } public function testValidationContainsRule() { - $bi = BankIntegration::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -126,7 +117,7 @@ class BankTransactionRuleTest extends TestCase 'value' => 'hello', ] ] - ]); + ]); $bt = $bt->refresh(); @@ -146,7 +137,6 @@ class BankTransactionRuleTest extends TestCase public function testUpdateValidationRules() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -166,15 +156,15 @@ class BankTransactionRuleTest extends TestCase $data = [ - "applies_to" => "DEBIT", - "archived_at" => 0, - "auto_convert" => False, - "category_id" => $this->expense_category->hashed_id, - "is_deleted" => False, - "isChanged" => True, - "matches_on_all" => True, - "name" => "TEST 22", - "updated_at" => 1669060432, + "applies_to" => "DEBIT", + "archived_at" => 0, + "auto_convert" => false, + "category_id" => $this->expense_category->hashed_id, + "is_deleted" => false, + "isChanged" => true, + "matches_on_all" => true, + "name" => "TEST 22", + "updated_at" => 1669060432, "vendor_id" => $this->vendor->hashed_id ]; @@ -186,23 +176,20 @@ class BankTransactionRuleTest extends TestCase 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->putJson('/api/v1/bank_transaction_rules/'. $br->hashed_id. '?include=expense_category', $data); - } catch (ValidationException $e) { $message = json_decode($e->validator->getMessageBag(), 1); nlog($message); } - if($response){ + if ($response) { $arr = $response->json(); -nlog($arr); - $response->assertStatus(200); + nlog($arr); + $response->assertStatus(200); } - } public function testMatchingBankTransactionExpenseAmountLessThanEqualTo() { - $bi = BankIntegration::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -250,7 +237,6 @@ nlog($arr); public function testMatchingBankTransactionExpenseAmountLessThan() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -293,7 +279,6 @@ nlog($arr); public function testMatchingBankTransactionExpenseAmountGreaterThan() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -337,7 +322,6 @@ nlog($arr); public function testMatchingBankTransactionExpenseAmountMiss() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -380,7 +364,6 @@ nlog($arr); public function testMatchingBankTransactionExpenseAmount() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -424,7 +407,6 @@ nlog($arr); public function testMatchingBankTransactionExpenseIsEmpty() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -468,7 +450,6 @@ nlog($arr); public function testMatchingBankTransactionExpenseIsEmptyMiss() { - $bi = BankIntegration::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -515,7 +496,6 @@ nlog($arr); public function testMatchingBankTransactionExpenseStartsWithMiss() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -560,7 +540,6 @@ nlog($arr); public function testMatchingBankTransactionExpenseStartsWith() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -603,52 +582,50 @@ nlog($arr); public function testMatchingBankTransactionExpenseContainsMiss() - { + { + $br = BankTransactionRule::factory()->create([ + 'company_id' => $this->company->id, + 'user_id' => $this->user->id, + 'matches_on_all' => false, + 'auto_convert' => true, + 'applies_to' => 'DEBIT', + 'client_id' => $this->client->id, + 'vendor_id' => $this->vendor->id, + 'rules' => [ + [ + 'search_key' => 'description', + 'operator' => 'contains', + 'value' => 'asdddfd', + ] + ] + ]); - $br = BankTransactionRule::factory()->create([ - 'company_id' => $this->company->id, - 'user_id' => $this->user->id, - 'matches_on_all' => false, - 'auto_convert' => true, - 'applies_to' => 'DEBIT', - 'client_id' => $this->client->id, - 'vendor_id' => $this->vendor->id, - 'rules' => [ - [ - 'search_key' => 'description', - 'operator' => 'contains', - 'value' => 'asdddfd', - ] - ] - ]); + $bi = BankIntegration::factory()->create([ + 'company_id' => $this->company->id, + 'user_id' => $this->user->id, + 'account_id' => $this->account->id, + ]); - $bi = BankIntegration::factory()->create([ - 'company_id' => $this->company->id, - 'user_id' => $this->user->id, - 'account_id' => $this->account->id, - ]); - - $bt = BankTransaction::factory()->create([ - 'bank_integration_id' => $bi->id, - 'company_id' => $this->company->id, - 'user_id' => $this->user->id, - 'description' => 'Something asd bizarre', - 'base_type' => 'DEBIT', - 'amount' => 100 - ]); + $bt = BankTransaction::factory()->create([ + 'bank_integration_id' => $bi->id, + 'company_id' => $this->company->id, + 'user_id' => $this->user->id, + 'description' => 'Something asd bizarre', + 'base_type' => 'DEBIT', + 'amount' => 100 + ]); - $bt->service()->processRules(); + $bt->service()->processRules(); - $bt = $bt->fresh(); + $bt = $bt->fresh(); - $this->assertNull($bt->expense_id); - } + $this->assertNull($bt->expense_id); + } public function testMatchingBankTransactionExpenseContains() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -691,7 +668,6 @@ nlog($arr); public function testMatchingBankTransactionExpenseMiss() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -733,7 +709,6 @@ nlog($arr); public function testMatchingBankTransactionExpense() { - $br = BankTransactionRule::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -776,7 +751,6 @@ nlog($arr); public function testMatchingBankTransactionInvoice() { - $this->invoice->number = "MUHMUH"; $this->invoice->save(); @@ -819,7 +793,4 @@ nlog($arr); $this->assertEquals(BankTransaction::STATUS_MATCHED, $bt->status_id); } - - - -} \ No newline at end of file +} diff --git a/tests/Feature/Bank/BankTransactionTest.php b/tests/Feature/Bank/BankTransactionTest.php index 9be72919ffc8..a2c6157b28b2 100644 --- a/tests/Feature/Bank/BankTransactionTest.php +++ b/tests/Feature/Bank/BankTransactionTest.php @@ -24,7 +24,6 @@ use Tests\TestCase; class BankTransactionTest extends TestCase { - use DatabaseTransactions; use MockAccountData; @@ -74,13 +73,10 @@ class BankTransactionTest extends TestCase 'X-API-TOKEN' => $this->token, ])->post('/api/v1/bank_transactions/bulk', $data) ->assertStatus(200); - - } public function testLinkExpenseToTransaction() { - $data = []; $bi = BankIntegrationFactory::create($this->company->id, $this->user->id, $this->account->id); @@ -119,12 +115,10 @@ class BankTransactionTest extends TestCase $this->assertEquals($bt->refresh()->expense_id, $this->expense->id); $this->assertEquals($this->vendor->id, $bt->vendor_id); $this->assertEquals(BankTransaction::STATUS_CONVERTED, $bt->status_id); - } public function testLinkingManuallyPaidInvoices() { - $invoice = InvoiceFactory::create($this->company->id, $this->user->id); $invoice->client_id = $this->client->id; $invoice->status_id = Invoice::STATUS_SENT; @@ -180,13 +174,11 @@ class BankTransactionTest extends TestCase $this->assertEquals($bt->refresh()->payment_id, $p->id); $this->assertEquals(BankTransaction::STATUS_CONVERTED, $bt->status_id); $this->assertEquals($invoice->hashed_id, $bt->invoice_ids); - } public function testLinkPaymentToTransaction() { - $data = []; $bi = BankIntegrationFactory::create($this->company->id, $this->user->id, $this->account->id); @@ -221,7 +213,6 @@ class BankTransactionTest extends TestCase $this->assertEquals($this->payment->refresh()->transaction_id, $bt->id); $this->assertEquals($bt->refresh()->payment_id, $this->payment->id); $this->assertEquals(BankTransaction::STATUS_CONVERTED, $bt->status_id); - } @@ -244,10 +235,9 @@ class BankTransactionTest extends TestCase public function testMatchBankTransactionValidationShouldPass() { - - if (config('ninja.testvars.travis') !== false) { - $this->markTestSkipped('Skip test for Github Actions'); - } + if (config('ninja.testvars.travis') !== false) { + $this->markTestSkipped('Skip test for Github Actions'); + } $data = []; @@ -278,5 +268,4 @@ class BankTransactionTest extends TestCase $response->assertStatus(200); } - -} \ No newline at end of file +} diff --git a/tests/Feature/Bank/YodleeApiTest.php b/tests/Feature/Bank/YodleeApiTest.php index e586c71519e3..2cbd504c48bc 100644 --- a/tests/Feature/Bank/YodleeApiTest.php +++ b/tests/Feature/Bank/YodleeApiTest.php @@ -38,15 +38,13 @@ class YodleeApiTest extends TestCase parent::setUp(); // if(!config('ninja.yodlee.client_id')) - $this->markTestSkipped('Skip test no Yodlee API credentials found'); + $this->markTestSkipped('Skip test no Yodlee API credentials found'); $this->makeTestData(); - } public function testExpenseGenerationFromBankFeed() { - $bi = BankIntegrationFactory::create($this->company->id, $this->user->id, $this->account->id); $bi->save(); @@ -73,7 +71,6 @@ class YodleeApiTest extends TestCase $this->assertNotNull($expense); $this->assertEquals(10, (int)$expense->amount); - } public function testIncomeMatchingAndPaymentGeneration() @@ -148,7 +145,7 @@ class YodleeApiTest extends TestCase $transactions = $yodlee->getTransactionCategories(); - $this->assertTrue(property_exists($transactions,'transactionCategory')); + $this->assertTrue(property_exists($transactions, 'transactionCategory')); $t = collect($transactions->transactionCategory); @@ -157,7 +154,6 @@ class YodleeApiTest extends TestCase $this->assertNotNull($x); $this->assertEquals('Automotive Expenses', $x->highLevelCategoryName); - } // public function testFunctionalMatching() @@ -165,7 +161,7 @@ class YodleeApiTest extends TestCase // $yodlee = new Yodlee('sbMem62e1e69547bfb1'); -// $accounts = $yodlee->getAccounts(); +// $accounts = $yodlee->getAccounts(); // foreach($accounts as $account) // { @@ -216,7 +212,6 @@ class YodleeApiTest extends TestCase public function testDataMatching() { - $transaction = collect([ (object)[ 'description' => 'tinkertonkton' @@ -256,19 +251,14 @@ class YodleeApiTest extends TestCase $invoice = $transaction->first(function ($value, $key) { - return str_contains($value->description, 'tinker'); - }); $this->assertNotNull($invoice); - - } public function testYodleeInstance() { - $yodlee = new Yodlee(); $this->assertNotNull($yodlee); @@ -278,7 +268,6 @@ class YodleeApiTest extends TestCase public function testAccessTokenGeneration() { - $yodlee = new Yodlee('sbMem62e1e69547bfb1'); $access_token = $yodlee->getAccessToken(); @@ -463,13 +452,11 @@ class YodleeApiTest extends TestCase public function testGetCategories() { - $yodlee = new Yodlee('sbMem62e1e69547bfb2'); $transactions = $yodlee->getTransactionCategories(); $this->assertIsArray($transactions->transactionCategory); - } @@ -497,7 +484,7 @@ class YodleeApiTest extends TestCase [includeInNetWorth] => 1 [providerId] => 18769 [providerName] => Dag Site Captcha - [isManual] => + [isManual] => [currentBalance] => stdClass Object ( [currency] => USD @@ -541,7 +528,7 @@ class YodleeApiTest extends TestCase [includeInNetWorth] => 1 [providerId] => 18769 [providerName] => Dag Site Captcha - [isManual] => + [isManual] => [availableBalance] => stdClass Object ( [currency] => USD @@ -576,7 +563,6 @@ class YodleeApiTest extends TestCase */ public function testGetAccounts() { - $yodlee = new Yodlee('sbMem62e1e69547bfb1'); $accounts = $yodlee->getAccounts(); @@ -612,7 +598,7 @@ class YodleeApiTest extends TestCase [original] => CHEROKEE NATION TAX TA TAHLEQUAH OK ) - [isManual] => + [isManual] => [sourceType] => AGGREGATED [date] => 2022-08-03 [transactionDate] => 2022-08-03 @@ -628,23 +614,20 @@ class YodleeApiTest extends TestCase [checkNumber] => 998 ) - + */ public function testGetTransactions() { - $yodlee = new Yodlee('sbMem62e1e69547bfb1'); $transactions = $yodlee->getTransactions(['categoryId' => 2, 'fromDate' => '2000-01-01']); $this->assertIsArray($transactions); - } public function testGetTransactionsWithParams() { - $yodlee = new Yodlee('sbMem62e1e69547bfb1'); $data = [ @@ -654,10 +637,8 @@ class YodleeApiTest extends TestCase 'fromDate' => '2000-10-10', /// YYYY-MM-DD ]; - $accounts = $yodlee->getTransactions($data); + $accounts = $yodlee->getTransactions($data); $this->assertIsArray($accounts); - } - } diff --git a/tests/Feature/Bank/YodleeBankTransactionTest.php b/tests/Feature/Bank/YodleeBankTransactionTest.php index dbd56ebffcb9..fb658ed9bb60 100644 --- a/tests/Feature/Bank/YodleeBankTransactionTest.php +++ b/tests/Feature/Bank/YodleeBankTransactionTest.php @@ -20,7 +20,6 @@ use Tests\TestCase; class YodleeBankTransactionTest extends TestCase { - use DatabaseTransactions; use MockAccountData; @@ -28,8 +27,9 @@ class YodleeBankTransactionTest extends TestCase { parent::setUp(); - if(!config('ninja.yodlee.client_id')) + if (!config('ninja.yodlee.client_id')) { $this->markTestSkipped('Skip test no Yodlee API credentials found'); + } $this->makeTestData(); @@ -40,7 +40,6 @@ class YodleeBankTransactionTest extends TestCase public function testDataMatching1() { - $this->invoice->number = "super-funk-1234"; $this->invoice->save(); @@ -56,32 +55,25 @@ class YodleeBankTransactionTest extends TestCase BankTransaction::where('company_id', $this->company->id) ->where('status_id', BankTransaction::STATUS_UNMATCHED) ->cursor() - ->each(function ($bt) use($invoices){ - - $invoice = $invoices->first(function ($value, $key) use ($bt){ - - return str_contains($value->number, $bt->description); - - }); - - if($invoice) - { - $bt->invoice_ids = $invoice->hashed_id; - $bt->status_id = BankTransaction::STATUS_MATCHED; - $bt->save(); - } + ->each(function ($bt) use ($invoices) { + $invoice = $invoices->first(function ($value, $key) use ($bt) { + return str_contains($value->number, $bt->description); + }); + if ($invoice) { + $bt->invoice_ids = $invoice->hashed_id; + $bt->status_id = BankTransaction::STATUS_MATCHED; + $bt->save(); + } }); $this->assertTrue(BankTransaction::where('invoice_ids', $this->invoice->hashed_id)->exists()); - } public function testDataMatching2() { - $this->invoice->number = "super-funk-1234"; $this->invoice->save(); @@ -97,28 +89,19 @@ class YodleeBankTransactionTest extends TestCase BankTransaction::where('company_id', $this->company->id) ->where('status_id', BankTransaction::STATUS_UNMATCHED) ->cursor() - ->each(function ($bt) use($invoices){ - - $invoice = $invoices->first(function ($value, $key) use ($bt){ - - return str_contains($value->number, $bt->description); - - }); - - if($invoice) - { - $bt->invoice_ids = $invoice->hashed_id; - $bt->status_id = BankTransaction::STATUS_MATCHED; - $bt->save(); - } + ->each(function ($bt) use ($invoices) { + $invoice = $invoices->first(function ($value, $key) use ($bt) { + return str_contains($value->number, $bt->description); + }); + if ($invoice) { + $bt->invoice_ids = $invoice->hashed_id; + $bt->status_id = BankTransaction::STATUS_MATCHED; + $bt->save(); + } }); $this->assertTrue(BankTransaction::where('invoice_ids', $this->invoice->hashed_id)->exists()); - } - - - -} \ No newline at end of file +} diff --git a/tests/Feature/BankIntegrationApiTest.php b/tests/Feature/BankIntegrationApiTest.php index 13c317ffa74d..fc69c8f8f2f1 100644 --- a/tests/Feature/BankIntegrationApiTest.php +++ b/tests/Feature/BankIntegrationApiTest.php @@ -15,7 +15,6 @@ use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\Session; -use Illuminate\Validation\ValidationException; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/Feature/BankTransactionRuleApiTest.php b/tests/Feature/BankTransactionRuleApiTest.php index ec38d470c9fc..59edbda2e15b 100644 --- a/tests/Feature/BankTransactionRuleApiTest.php +++ b/tests/Feature/BankTransactionRuleApiTest.php @@ -15,7 +15,6 @@ use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\Session; -use Illuminate\Validation\ValidationException; use Tests\MockAccountData; use Tests\TestCase; @@ -51,7 +50,7 @@ $rules = [ 'applies_to' => 'bail|sometimes|bool', ]; -if(isset($this->category_id)) +if(isset($this->category_id)) $rules['category_id'] = 'bail|sometimes|exists:expense_categories,id,'.auth()->user()->company()->id.',is_deleted,0'; if(isset($this->vendor_id)) @@ -66,8 +65,8 @@ if(isset($this->client_id)) 'name' => 'The First Rule', 'rules' => [ [ - "operator" => "contains", - "search_key" => "description", + "operator" => "contains", + "search_key" => "description", "value" => "mobile" ], ], @@ -105,7 +104,6 @@ if(isset($this->client_id)) public function testBankRulePost() { - $data = [ 'name' => 'The First Rule', 'rules' => [], @@ -124,12 +122,10 @@ if(isset($this->client_id)) $response->assertStatus(200); $this->assertEquals('The First Rule', $arr['data']['name']); - } public function testBankRulePut() { - $data = [ 'name' => 'The First Rule', 'rules' => [], @@ -167,7 +163,6 @@ if(isset($this->client_id)) $response->assertStatus(200); $this->assertEquals('A New Name For The First Rule', $arr['data']['name']); - } public function testBankTransactionRuleGet() diff --git a/tests/Feature/BaseApiTest.php b/tests/Feature/BaseApiTest.php index 3f3c219ab3e1..75d4ae7f24b4 100644 --- a/tests/Feature/BaseApiTest.php +++ b/tests/Feature/BaseApiTest.php @@ -22,7 +22,6 @@ use App\Models\BankTransaction; use App\Models\BankTransactionRule; use App\Models\Client; use App\Models\ClientContact; -use App\Models\ClientGatewayToken; use App\Models\Company; use App\Models\CompanyGateway; use App\Models\CompanyToken; @@ -49,7 +48,6 @@ use App\Models\TaxRate; use App\Models\User; use App\Models\Vendor; use App\Models\VendorContact; -use App\Models\Webhook; use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Support\Str; use Illuminate\Testing\Fluent\AssertableJson; @@ -382,7 +380,6 @@ class BaseApiTest extends TestCase $cgt = ClientGatewayTokenFactory::create($company->id); $cgt->save(); - } // public function testGeneratingClassName() @@ -400,41 +397,38 @@ class BaseApiTest extends TestCase */ public function testOwnerRoutes() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->owner_token, ])->get('/api/v1/users/'); - $response->assertStatus(200) - ->assertJson(fn (AssertableJson $json) => $json->has('data',2)->etc()); + $response->assertStatus(200) + ->assertJson(fn (AssertableJson $json) => $json->has('data', 2)->etc()); /*does not test the number of records however*/ - collect($this->list_routes)->filter(function ($route){ + collect($this->list_routes)->filter(function ($route) { return !in_array($route, ['users','designs','payment_terms']); - })->each(function($route){ + })->each(function ($route) { // nlog($route); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->owner_token, ])->get("/api/v1/{$route}/") - ->assertJson(fn (AssertableJson $json) => + ->assertJson( + fn (AssertableJson $json) => $json->has('meta') - ->has('data',1) - ); + ->has('data', 1) + ); }); - } public function testOwnerAccessCompany() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->low_token, ])->get('/api/v1/companies/'.$this->company->hashed_id) ->assertStatus(403); - } @@ -445,42 +439,40 @@ class BaseApiTest extends TestCase $this->owner_cu->is_admin = true; $this->owner_cu->is_locked = false; $this->owner_cu->permissions = '[]'; - $this->owner_cu->save(); + $this->owner_cu->save(); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->owner_token, ])->get('/api/v1/users/'); - $response->assertStatus(200) - ->assertJson(fn (AssertableJson $json) => $json->has('data',2)->etc()); + $response->assertStatus(200) + ->assertJson(fn (AssertableJson $json) => $json->has('data', 2)->etc()); - collect($this->list_routes)->filter(function ($route){ + collect($this->list_routes)->filter(function ($route) { return !in_array($route, ['users','designs','payment_terms']); - })->each(function($route){ + })->each(function ($route) { // nlog($route); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->owner_token, ])->get("/api/v1/{$route}/") ->assertStatus(200) - ->assertJson(fn (AssertableJson $json) => + ->assertJson( + fn (AssertableJson $json) => $json->has('meta') - ->has('data',1) - ); + ->has('data', 1) + ); }); - } public function testAdminAccessCompany() { - - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->owner_token, - ])->get('/api/v1/companies/'.$this->company->hashed_id) - ->assertStatus(200); - + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->owner_token, + ])->get('/api/v1/companies/'.$this->company->hashed_id) + ->assertStatus(200); } public function testAdminLockedRoutes() @@ -490,7 +482,7 @@ class BaseApiTest extends TestCase $this->owner_cu->is_admin = true; $this->owner_cu->is_locked = true; $this->owner_cu->permissions = '[]'; - $this->owner_cu->save(); + $this->owner_cu->save(); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), @@ -498,9 +490,9 @@ class BaseApiTest extends TestCase ])->get('/api/v1/users/') ->assertStatus(403); - collect($this->list_routes)->filter(function ($route){ + collect($this->list_routes)->filter(function ($route) { return !in_array($route, ['users','designs','payment_terms']); - })->each(function($route){ + })->each(function ($route) { // nlog($route); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), @@ -508,25 +500,22 @@ class BaseApiTest extends TestCase ])->get("/api/v1/{$route}/") ->assertStatus(403); }); - } public function testAdminLockedCompany() { - $this->owner_cu = CompanyUser::where('user_id', $this->owner_cu->user_id)->where('company_id', $this->owner_cu->company_id)->first(); $this->owner_cu->is_owner = false; $this->owner_cu->is_admin = true; $this->owner_cu->is_locked = true; $this->owner_cu->permissions = '[]'; - $this->owner_cu->save(); - - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->owner_token, - ])->get('/api/v1/companies/'.$this->company->hashed_id) - ->assertStatus(403); + $this->owner_cu->save(); + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->owner_token, + ])->get('/api/v1/companies/'.$this->company->hashed_id) + ->assertStatus(403); } /** @@ -534,27 +523,26 @@ class BaseApiTest extends TestCase */ public function testRestrictedUserRoute() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->get('/api/v1/tasks/') ->assertStatus(200) - ->assertJson(fn (AssertableJson $json) => $json->has('data',1)->etc()); + ->assertJson(fn (AssertableJson $json) => $json->has('data', 1)->etc()); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->get('/api/v1/group_settings/') ->assertStatus(200) - ->assertJson(fn (AssertableJson $json) => $json->has('data',2)->etc()); + ->assertJson(fn (AssertableJson $json) => $json->has('data', 2)->etc()); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->get('/api/v1/designs/') ->assertStatus(200) - ->assertJson(fn (AssertableJson $json) => $json->has('data',11)->etc()); + ->assertJson(fn (AssertableJson $json) => $json->has('data', 11)->etc()); $response = $this->withHeaders([ @@ -562,35 +550,33 @@ class BaseApiTest extends TestCase 'X-API-TOKEN' => $this->low_token, ])->get('/api/v1/users/'); - $response->assertStatus(200) - ->assertJson(fn (AssertableJson $json) => $json->has('data',1)->etc()); + $response->assertStatus(200) + ->assertJson(fn (AssertableJson $json) => $json->has('data', 1)->etc()); - collect($this->list_routes)->filter(function ($route){ + collect($this->list_routes)->filter(function ($route) { return !in_array($route, ['tasks', 'users', 'group_settings','designs','client_gateway_tokens']); - })->each(function($route){ + })->each(function ($route) { $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->low_token, ])->get("/api/v1/{$route}/") - ->assertJson(fn (AssertableJson $json) => + ->assertJson( + fn (AssertableJson $json) => $json->has('meta') - ->has('data',0) - ); - + ->has('data', 0) + ); }); - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->low_token, - ])->get('/api/v1/companies/'.$this->company->hashed_id) - ->assertStatus(403); + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->low_token, + ])->get('/api/v1/companies/'.$this->company->hashed_id) + ->assertStatus(403); $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->low_token, ])->get('/api/v1/client_gateway_tokens/') ->assertStatus(403); - } - } diff --git a/tests/Feature/Client/ClientMergeTest.php b/tests/Feature/Client/ClientMergeTest.php index dc6f1806c43c..ef2c4ae62fd9 100644 --- a/tests/Feature/Client/ClientMergeTest.php +++ b/tests/Feature/Client/ClientMergeTest.php @@ -12,19 +12,14 @@ namespace Tests\Feature\Client; -use App\DataMapper\ClientSettings; -use App\DataMapper\CompanySettings; -use App\Http\Livewire\CreditsTable; use App\Models\Account; use App\Models\Client; use App\Models\ClientContact; use App\Models\Company; -use App\Models\Credit; use App\Models\User; use App\Utils\Traits\AppSetup; use Faker\Factory; use Illuminate\Foundation\Testing\DatabaseTransactions; -use Livewire\Livewire; use Tests\TestCase; class ClientMergeTest extends TestCase diff --git a/tests/Feature/ClientApiTest.php b/tests/Feature/ClientApiTest.php index 734aa4cef8f0..75bed1b223eb 100644 --- a/tests/Feature/ClientApiTest.php +++ b/tests/Feature/ClientApiTest.php @@ -55,13 +55,11 @@ class ClientApiTest extends TestCase $this->faker = \Faker\Factory::create(); Model::reguard(); - } public function testCrossCompanyBulkActionsFail() { - $account = Account::factory()->create([ 'hosted_client_count' => 1000, 'hosted_company_count' => 1000, @@ -122,7 +120,6 @@ class ClientApiTest extends TestCase $v = $this->app['validator']->make($data, $rules); $this->assertFalse($v->passes()); - } @@ -156,20 +153,17 @@ class ClientApiTest extends TestCase $data = [ 'action' => 'archive', - 'ids' => + 'ids' => $this->client->hashed_id ]; $v = $this->app['validator']->make($data, $rules); $this->assertFalse($v->passes()); - - } public function testClientStatement() { - $response = null; $data = [ @@ -195,12 +189,10 @@ class ClientApiTest extends TestCase $this->assertTrue($response->headers->get('content-type') == 'application/pdf'); $response->assertStatus(200); - } public function testClientStatementEmail() { - $response = null; $data = [ @@ -228,7 +220,6 @@ class ClientApiTest extends TestCase $response->assertStatus(200); - } @@ -267,7 +258,7 @@ class ClientApiTest extends TestCase 'currency_id' => '3', ], 'client_hash' => 'xx', - 'contacts' => + 'contacts' => [ [ 'first_name' => '', @@ -280,8 +271,8 @@ class ClientApiTest extends TestCase 'custom_value4' => '', ] ], - 'country_id' => NULL, - 'shipping_country_id' => NULL, + 'country_id' => null, + 'shipping_country_id' => null, 'user_id' => $this->user->id, ]; @@ -298,12 +289,10 @@ class ClientApiTest extends TestCase $c->refresh(); $this->assertEquals("3", $c->settings->currency_id); - } public function testClientSettingsSave() { - $std = new \stdClass; $std->entity = 'App\\Models\\Client'; $std->currency_id = 3; @@ -313,13 +302,11 @@ class ClientApiTest extends TestCase $this->saveSettings($std, $this->client); $this->assertTrue(true); - } public function testClientSettingsSave2() { - $std = new \stdClass; $std->entity = 'App\\Models\\Client'; $std->industry_id = ''; @@ -331,16 +318,14 @@ class ClientApiTest extends TestCase $this->saveSettings($std, $this->client); $this->assertTrue(true); - } public function testClientStoreValidation() { + auth()->login($this->user, false); + auth()->user()->setCompany($this->company); - auth()->login($this->user, false); - auth()->user()->setCompany($this->company); - - $data = array ( + $data = [ 'company_id' => $this->company->id, 'name' => 'Christian xx', 'phone' => '', @@ -366,16 +351,16 @@ class ClientApiTest extends TestCase 'balance' => '0', 'paid_to_date' => '0', 'credit_balance' => 0, - 'settings' => - (object) array( + 'settings' => + (object) [ 'entity' => 'App\\Models\\Client', 'currency_id' => '3', - ), + ], 'client_hash' => 'xx', - 'contacts' => - array ( - 0 => - array ( + 'contacts' => + [ + 0 => + [ 'first_name' => '', 'last_name' => '', 'email' => '', @@ -384,12 +369,12 @@ class ClientApiTest extends TestCase 'custom_value2' => '', 'custom_value3' => '', 'custom_value4' => '', - ), - ), - 'country_id' => NULL, - 'shipping_country_id' => NULL, + ], + ], + 'country_id' => null, + 'shipping_country_id' => null, 'user_id' => $this->user->id, - ); + ]; $request_name = StoreClientRequest::class; @@ -409,17 +394,13 @@ class ClientApiTest extends TestCase $_syn_request_class->setValidator($validator); $this->assertFalse($validator->fails()); - - } public function testClientImportDataStructure() { - - - $data = array ( + $data = [ 'company_id' => $this->company->id, 'name' => 'Christian xx', 'phone' => '', @@ -445,16 +426,16 @@ class ClientApiTest extends TestCase 'balance' => '0', 'paid_to_date' => '0', 'credit_balance' => 0, - 'settings' => - (object) array( + 'settings' => + (object) [ 'entity' => 'App\\Models\\Client', 'currency_id' => '3', - ), + ], 'client_hash' => 'xx', - 'contacts' => - array ( - 0 => - array ( + 'contacts' => + [ + 0 => + [ 'first_name' => '', 'last_name' => '', 'email' => '', @@ -463,12 +444,12 @@ class ClientApiTest extends TestCase 'custom_value2' => '', 'custom_value3' => '', 'custom_value4' => '', - ), - ), - 'country_id' => NULL, - 'shipping_country_id' => NULL, + ], + ], + 'country_id' => null, + 'shipping_country_id' => null, 'user_id' => $this->user->id, - ); + ]; $crepo = new ClientRepository(new ClientContactRepository()); @@ -481,7 +462,6 @@ class ClientApiTest extends TestCase public function testClientCsvImport() { - $settings = ClientSettings::defaults(); $settings->currency_id = "840"; @@ -521,8 +501,6 @@ class ClientApiTest extends TestCase $c = $crepo->save($data, ClientFactory::create($this->company->id, $this->user->id)); $c->saveQuietly(); - - } @@ -815,7 +793,7 @@ class ClientApiTest extends TestCase $response = false; - try{ + try { $response = $this->withHeaders([ 'X-API-TOKEN' => $this->token, ])->post('/api/v1/clients/bulk?action=archive', $data); @@ -824,7 +802,7 @@ class ClientApiTest extends TestCase nlog($message); } - if($response){ + if ($response) { $arr = $response->json(); $this->assertNotNull($arr['data'][0]['archived_at']); } @@ -976,6 +954,4 @@ class ClientApiTest extends TestCase $x = Number::formatValueNoTrailingZeroes(1.50000005, $currency); $this->assertEquals(1.50000005, $x); } - - } diff --git a/tests/Feature/ClientDeletedInvoiceCreationTest.php b/tests/Feature/ClientDeletedInvoiceCreationTest.php index 4d8f0ef6fa45..20a562514fd0 100644 --- a/tests/Feature/ClientDeletedInvoiceCreationTest.php +++ b/tests/Feature/ClientDeletedInvoiceCreationTest.php @@ -11,8 +11,6 @@ namespace Tests\Feature; -use App\Models\Client; -use App\Models\ClientContact; use App\Models\Invoice; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; diff --git a/tests/Feature/ClientGatewayTokenApiTest.php b/tests/Feature/ClientGatewayTokenApiTest.php index 196424e7272b..9a7849de06f6 100644 --- a/tests/Feature/ClientGatewayTokenApiTest.php +++ b/tests/Feature/ClientGatewayTokenApiTest.php @@ -16,7 +16,6 @@ use App\Models\GatewayType; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; -use Illuminate\Support\Facades\Session; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/Feature/ClientModelTest.php b/tests/Feature/ClientModelTest.php index 246e7b27f23e..464f26e4b6bc 100644 --- a/tests/Feature/ClientModelTest.php +++ b/tests/Feature/ClientModelTest.php @@ -13,7 +13,6 @@ namespace Tests\Feature; use App\Models\CompanyGateway; use Illuminate\Foundation\Testing\DatabaseTransactions; -use Illuminate\Support\Facades\URL; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/Feature/ClientPortal/InvoicesTest.php b/tests/Feature/ClientPortal/InvoicesTest.php index aa606e1f05d0..11cb71a7b4f9 100644 --- a/tests/Feature/ClientPortal/InvoicesTest.php +++ b/tests/Feature/ClientPortal/InvoicesTest.php @@ -12,7 +12,6 @@ namespace Tests\Feature\ClientPortal; -use App\DataMapper\ClientSettings; use App\Http\Livewire\InvoicesTable; use App\Models\Account; use App\Models\Client; diff --git a/tests/Feature/ClientTest.php b/tests/Feature/ClientTest.php index e321b29c6a75..17927bb747fb 100644 --- a/tests/Feature/ClientTest.php +++ b/tests/Feature/ClientTest.php @@ -67,13 +67,12 @@ class ClientTest extends TestCase { $line_items = []; - for($x=0; $x<$number; $x++) - { + for ($x=0; $x<$number; $x++) { $item = InvoiceItemFactory::create(); $item->quantity = 1; $item->cost = 10; - $line_items[] = $item; + $line_items[] = $item; } return $line_items; diff --git a/tests/Feature/CompanyGatewayApiTest.php b/tests/Feature/CompanyGatewayApiTest.php index f9764081885e..9af80c664c5f 100644 --- a/tests/Feature/CompanyGatewayApiTest.php +++ b/tests/Feature/CompanyGatewayApiTest.php @@ -85,7 +85,6 @@ class CompanyGatewayApiTest extends TestCase 'X-API-TOKEN' => $this->token, ])->post('/api/v1/company_gateways/bulk', $data) ->assertStatus(200); - } @@ -556,6 +555,6 @@ class CompanyGatewayApiTest extends TestCase $company_gateway = CompanyGateway::find($id); - $this->assertEquals(1.2, round($company_gateway->calcGatewayFee(10, GatewayType::CREDIT_CARD, true),1)); + $this->assertEquals(1.2, round($company_gateway->calcGatewayFee(10, GatewayType::CREDIT_CARD, true), 1)); } } diff --git a/tests/Feature/CompanyGatewayResolutionTest.php b/tests/Feature/CompanyGatewayResolutionTest.php index ef294c2b26fc..df01d5614ace 100644 --- a/tests/Feature/CompanyGatewayResolutionTest.php +++ b/tests/Feature/CompanyGatewayResolutionTest.php @@ -233,6 +233,6 @@ class CompanyGatewayResolutionTest extends TestCase $this->cg->save(); $fee = $this->cg->calcGatewayFee(89, GatewayType::CREDIT_CARD, false); - $this->assertEquals(1.89, round($fee,2)); + $this->assertEquals(1.89, round($fee, 2)); } } diff --git a/tests/Feature/CompanyGatewayTest.php b/tests/Feature/CompanyGatewayTest.php index ff1ce14afa0a..97118f1f92d3 100644 --- a/tests/Feature/CompanyGatewayTest.php +++ b/tests/Feature/CompanyGatewayTest.php @@ -158,7 +158,6 @@ class CompanyGatewayTest extends TestCase public function testGatewayFeesAreClearedAppropriately() { - $data = []; $data[1]['min_limit'] = -1; $data[1]['max_limit'] = -1; @@ -205,7 +204,6 @@ class CompanyGatewayTest extends TestCase public function testMarkPaidAdjustsGatewayFeeAppropriately() { - $data = []; $data[1]['min_limit'] = -1; $data[1]['max_limit'] = -1; @@ -248,8 +246,6 @@ class CompanyGatewayTest extends TestCase $i = Invoice::withTrashed()->find($this->invoice->id); $this->assertEquals($wiped_balance, $i->amount); - - } diff --git a/tests/Feature/CompanySettingsTest.php b/tests/Feature/CompanySettingsTest.php index 9a546d046117..9e65294280ad 100644 --- a/tests/Feature/CompanySettingsTest.php +++ b/tests/Feature/CompanySettingsTest.php @@ -6,7 +6,7 @@ * * @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com) * - * @license https://www.elastic.co/licensing/elastic-license + * @license https://www.elastic.co/licensing/elastic-license */ namespace Tests\Feature; @@ -81,10 +81,10 @@ class CompanySettingsTest extends TestCase $response = false; try { - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-Token' => $this->token, - ])->putJson('/api/v1/companies/'.$this->encodePrimaryKey($this->company->id), $this->company->toArray()); + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-Token' => $this->token, + ])->putJson('/api/v1/companies/'.$this->encodePrimaryKey($this->company->id), $this->company->toArray()); } catch (ValidationException $e) { $message = json_decode($e->validator->getMessageBag(), 1); nlog($message); diff --git a/tests/Feature/CompanyTest.php b/tests/Feature/CompanyTest.php index 418321dc16bc..a8eb0c8e894c 100644 --- a/tests/Feature/CompanyTest.php +++ b/tests/Feature/CompanyTest.php @@ -49,7 +49,6 @@ class CompanyTest extends TestCase public function testUpdateCompanyPropertyInvoiceTaskHours() { - $company_update = [ 'invoice_task_hours' => true ]; @@ -61,9 +60,9 @@ class CompanyTest extends TestCase ->assertStatus(200); - $arr = $response->json(); + $arr = $response->json(); - $this->assertTrue($arr['data']['invoice_task_hours']); + $this->assertTrue($arr['data']['invoice_task_hours']); $company_update = [ @@ -77,10 +76,9 @@ class CompanyTest extends TestCase ->assertStatus(200); - $arr = $response->json(); - - $this->assertFalse($arr['data']['invoice_task_hours']); + $arr = $response->json(); + $this->assertFalse($arr['data']['invoice_task_hours']); } public function testCompanyList() diff --git a/tests/Feature/CreditTest.php b/tests/Feature/CreditTest.php index d3118c1f089d..0e830189e813 100644 --- a/tests/Feature/CreditTest.php +++ b/tests/Feature/CreditTest.php @@ -53,13 +53,11 @@ class CreditTest extends TestCase $response->assertStatus(200); $this->assertTrue($response->headers->get('content-type') == 'application/pdf'); - } public function testBulkActions() { - $data = [ 'action' => 'archive', 'ids' => [$this->credit->hashed_id] @@ -92,7 +90,6 @@ class CreditTest extends TestCase 'X-API-TOKEN' => $this->token, ])->post('/api/v1/credits/bulk', $data) ->assertStatus(200); - } diff --git a/tests/Feature/DeleteInvoiceTest.php b/tests/Feature/DeleteInvoiceTest.php index 8dcf2daf4764..7828aa827dd7 100644 --- a/tests/Feature/DeleteInvoiceTest.php +++ b/tests/Feature/DeleteInvoiceTest.php @@ -184,7 +184,6 @@ class DeleteInvoiceTest extends TestCase $this->assertEquals(6000, $payment->amount); $this->assertFalse($payment->is_deleted); $this->assertNull($payment->deleted_at); - } public function testInvoiceDeletionAfterCancellation() diff --git a/tests/Feature/DesignApiTest.php b/tests/Feature/DesignApiTest.php index 723596e639b2..dec0cc00bed7 100644 --- a/tests/Feature/DesignApiTest.php +++ b/tests/Feature/DesignApiTest.php @@ -46,7 +46,6 @@ class DesignApiTest extends TestCase public function testDesignPost() { - $design = [ 'body' => 'body', 'includes' => 'includes', diff --git a/tests/Feature/Email/EmailServiceTest.php b/tests/Feature/Email/EmailServiceTest.php index 66b10b118a15..3f14e6e518df 100644 --- a/tests/Feature/Email/EmailServiceTest.php +++ b/tests/Feature/Email/EmailServiceTest.php @@ -15,11 +15,10 @@ use App\Services\Email\EmailObject; use App\Services\Email\EmailService; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; -use Illuminate\Routing\Middleware\ThrottleRequests; -use Tests\MockAccountData; -use Tests\TestCase; use Illuminate\Mail\Mailables\Address; use Illuminate\Support\Facades\Cache; +use Tests\MockAccountData; +use Tests\TestCase; /** * @test @@ -39,8 +38,9 @@ class EmailServiceTest extends TestCase { parent::setUp(); - if(!class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) + if (!class_exists(\Modules\Admin\Jobs\Account\EmailFilter::class)) { $this->markTestSkipped('Skipped :: test not needed in this environment'); + } $this->makeTestData(); @@ -59,7 +59,6 @@ class EmailServiceTest extends TestCase ]; $this->email_service = new EmailService($this->email_object, $this->company); - } public function testScanEmailsAttemptedFromVerifiedAccounts() @@ -76,21 +75,17 @@ class EmailServiceTest extends TestCase $this->assertFalse($this->email_service->preFlightChecksFail()); - collect($email_filter->getSpamKeywords())->each(function ($spam_subject){ - + collect($email_filter->getSpamKeywords())->each(function ($spam_subject) { $this->email_object->subject = $spam_subject; $this->assertTrue($this->email_service->preFlightChecksFail()); - }); - } public function scanEmailsAttemptedFromUnverifiedAccounts() { - config(['ninja.environment' => 'hosted']); Cache::put($this->account->key, 1); @@ -99,7 +94,6 @@ class EmailServiceTest extends TestCase $this->account->save(); $this->assertTrue($this->email_service->preFlightChecksFail()); - } @@ -113,45 +107,39 @@ class EmailServiceTest extends TestCase $this->account->save(); $this->assertFalse($this->email_service->preFlightChecksFail()); - } public function testClientMailersAreUnCapped() { - config(['ninja.environment' => 'hosted']); Cache::put($this->account->key, 1000000); collect([ - 'gmail', - 'office365', - 'client_postmark', + 'gmail', + 'office365', + 'client_postmark', 'client_mailgun']) - ->each(function ($mailer){ - + ->each(function ($mailer) { $this->email_object->settings->email_sending_method = $mailer; $this->assertFalse($this->email_service->preFlightChecksFail()); - }); $this->email_object->settings->email_sending_method = 'postmark'; $this->assertTrue($this->email_service->preFlightChecksFail()); - } public function testFlaggedInvalidEmailsPrevented() { - config(['ninja.environment' => 'hosted']); Cache::put($this->account->key, 1); - $this->email_object->to = [new Address("user@example.com", "Cool Name")]; + $this->email_object->to = [new Address("user@example.com", "Cool Name")]; - $this->assertTrue($this->email_service->preFlightChecksFail()); + $this->assertTrue($this->email_service->preFlightChecksFail()); collect([ @@ -159,21 +147,15 @@ class EmailServiceTest extends TestCase '', 'bademail', 'domain.com', - ])->each(function ($email){ - - + ])->each(function ($email) { $this->email_object->to = [new Address($email, "Cool Name")]; $this->assertTrue($this->email_service->preFlightChecksFail()); - }); - - } public function testFlaggedAccountsPrevented() { - Cache::put($this->account->key, 1); config(['ninja.environment' => 'hosted']); @@ -182,31 +164,23 @@ class EmailServiceTest extends TestCase $this->account->save(); $this->assertTrue($this->email_service->preFlightChecksFail()); - } public function testPreFlightChecksHosted() { - Cache::put($this->account->key, 1); config(['ninja.environment' => 'hosted']); $this->assertFalse($this->email_service->preFlightChecksFail()); - } public function testPreFlightChecksSelfHost() { - Cache::put($this->account->key, 1); config(['ninja.environment' => 'selfhost']); $this->assertFalse($this->email_service->preFlightChecksFail()); - } - - - } diff --git a/tests/Feature/EntityPaidToDateTest.php b/tests/Feature/EntityPaidToDateTest.php index e39f3b3891d1..3212ff63d7a6 100644 --- a/tests/Feature/EntityPaidToDateTest.php +++ b/tests/Feature/EntityPaidToDateTest.php @@ -11,25 +11,15 @@ namespace Tests\Feature; -use App\DataMapper\ClientSettings; -use App\Factory\ClientFactory; -use App\Factory\CreditFactory; -use App\Factory\InvoiceFactory; use App\Factory\InvoiceItemFactory; -use App\Factory\PaymentFactory; -use App\Helpers\Invoice\InvoiceSum; use App\Models\Client; -use App\Models\ClientContact; -use App\Models\Credit; use App\Models\Invoice; -use App\Models\Payment; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\WithoutEvents; use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Support\Facades\Session; -use Illuminate\Validation\ValidationException; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/Feature/ExpenseApiTest.php b/tests/Feature/ExpenseApiTest.php index a2d3c56a4abe..23877f7c0d99 100644 --- a/tests/Feature/ExpenseApiTest.php +++ b/tests/Feature/ExpenseApiTest.php @@ -43,14 +43,12 @@ class ExpenseApiTest extends TestCase public function testExpenseGetClientStatus() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->get('/api/v1/expenses?client_status=paid'); $response->assertStatus(200); - } public function testExpensePost() diff --git a/tests/Feature/Export/ClientCsvTest.php b/tests/Feature/Export/ClientCsvTest.php index bc59900ae5ff..eba4d1bcd6da 100644 --- a/tests/Feature/Export/ClientCsvTest.php +++ b/tests/Feature/Export/ClientCsvTest.php @@ -11,11 +11,8 @@ namespace Tests\Feature\Export; -use App\Models\Invoice; use App\Utils\Traits\MakesHash; use Illuminate\Routing\Middleware\ThrottleRequests; -use Illuminate\Support\Facades\Storage; -use League\Csv\Writer; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/Feature/Export/ExportCompanyTest.php b/tests/Feature/Export/ExportCompanyTest.php index 307d45f917b8..88696330ff63 100644 --- a/tests/Feature/Export/ExportCompanyTest.php +++ b/tests/Feature/Export/ExportCompanyTest.php @@ -12,11 +12,8 @@ namespace Tests\Feature\Export; use App\Jobs\Company\CompanyExport; -use App\Models\Invoice; use App\Utils\Traits\MakesHash; use Illuminate\Routing\Middleware\ThrottleRequests; -use Illuminate\Support\Facades\Storage; -use League\Csv\Writer; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/Feature/Export/ProductSalesReportTest.php b/tests/Feature/Export/ProductSalesReportTest.php index ff285653a60d..8684533f7a35 100644 --- a/tests/Feature/Export/ProductSalesReportTest.php +++ b/tests/Feature/Export/ProductSalesReportTest.php @@ -11,28 +11,17 @@ namespace Tests\Feature\Export; -use App\DataMapper\ClientSettings; use App\DataMapper\CompanySettings; use App\Export\CSV\ProductSalesExport; -use App\Factory\ExpenseCategoryFactory; -use App\Factory\ExpenseFactory; -use App\Factory\InvoiceFactory; use App\Factory\InvoiceItemFactory; use App\Models\Account; use App\Models\Client; -use App\Models\ClientContact; use App\Models\Company; use App\Models\Expense; -use App\Models\ExpenseCategory; use App\Models\Invoice; use App\Models\User; -use App\Services\Report\ProfitLoss; use App\Utils\Traits\MakesHash; -use Database\Factories\ClientContactFactory; use Illuminate\Routing\Middleware\ThrottleRequests; -use Illuminate\Support\Facades\Storage; -use League\Csv\Writer; -use Tests\MockAccountData; use Tests\TestCase; /** @@ -126,7 +115,6 @@ class ProductSalesReportTest extends TestCase 'company_id' => $this->company->id, 'is_deleted' => 0, ]); - } public function testProductSalesInstance() @@ -140,7 +128,7 @@ class ProductSalesReportTest extends TestCase $this->account->delete(); } - public function testSimpleReport() + public function testSimpleReport() { $this->buildData(); @@ -213,5 +201,4 @@ class ProductSalesReportTest extends TestCase return $line_items; } - -} \ No newline at end of file +} diff --git a/tests/Feature/Export/ProfitAndLossReportTest.php b/tests/Feature/Export/ProfitAndLossReportTest.php index d052b9f091e5..52ba1b37342d 100644 --- a/tests/Feature/Export/ProfitAndLossReportTest.php +++ b/tests/Feature/Export/ProfitAndLossReportTest.php @@ -15,22 +15,16 @@ use App\DataMapper\ClientSettings; use App\DataMapper\CompanySettings; use App\Factory\ExpenseCategoryFactory; use App\Factory\ExpenseFactory; -use App\Factory\InvoiceFactory; use App\Models\Account; use App\Models\Client; use App\Models\ClientContact; use App\Models\Company; use App\Models\Expense; -use App\Models\ExpenseCategory; use App\Models\Invoice; use App\Models\User; use App\Services\Report\ProfitLoss; use App\Utils\Traits\MakesHash; -use Database\Factories\ClientContactFactory; use Illuminate\Routing\Middleware\ThrottleRequests; -use Illuminate\Support\Facades\Storage; -use League\Csv\Writer; -use Tests\MockAccountData; use Tests\TestCase; /** diff --git a/tests/Feature/GoCardlessInstantBankPaymentTest.php b/tests/Feature/GoCardlessInstantBankPaymentTest.php index db7fe3b2e74e..96383eaaec6e 100644 --- a/tests/Feature/GoCardlessInstantBankPaymentTest.php +++ b/tests/Feature/GoCardlessInstantBankPaymentTest.php @@ -33,11 +33,11 @@ class GoCardlessInstantBankPaymentTest extends TestCase use MakesHash; private array $mock = [ - 'events' => + 'events' => [ [ 'id' => 'EV032JF', - 'links' => + 'links' => [ 'customer' => 'CU001ZDX', 'billing_request' => 'BRQ0005', @@ -45,7 +45,7 @@ class GoCardlessInstantBankPaymentTest extends TestCase 'customer_bank_account' => 'BA001V2111PK6J', ], 'action' => 'payer_details_confirmed', - 'details' => + 'details' => [ 'cause' => 'billing_request_payer_details_confirmed', 'origin' => 'api', @@ -57,7 +57,7 @@ class GoCardlessInstantBankPaymentTest extends TestCase ], [ 'id' => 'EV032JF67TF2', - 'links' => + 'links' => [ 'customer' => 'CU001DXYDR3', 'billing_request' => 'BRQ005YJ7GHF', @@ -65,7 +65,7 @@ class GoCardlessInstantBankPaymentTest extends TestCase 'mandate_request_mandate' => 'MD01W5RP7GA', ], 'action' => 'fulfilled', - 'details' => + 'details' => [ 'cause' => 'billing_request_fulfilled', 'origin' => 'api', @@ -77,18 +77,18 @@ class GoCardlessInstantBankPaymentTest extends TestCase ], [ 'id' => 'EV032JF67S0M8', - 'links' => + 'links' => [ 'mandate' => 'MD001W5RP7GA1W', ], 'action' => 'created', - 'details' => + 'details' => [ 'cause' => 'mandate_created', 'origin' => 'api', 'description' => 'Mandate created via the API.', ], - 'metadata' => + 'metadata' => [], 'created_at' => '2022-11-06T08:50:34.667Z', 'resource_type' => 'mandates', @@ -110,42 +110,35 @@ class GoCardlessInstantBankPaymentTest extends TestCase public function testWebhookProcessingWithGoCardless() { + $this->assertIsArray($this->mock); - $this->assertIsArray($this->mock); - - foreach($this->mock['events'] as $event) - { - - if($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) { - - $this->assertEquals('CU001DXYDR3', $event['links']['customer']); - $this->assertEquals('BRQ005YJ7GHF', $event['links']['billing_request']); - $this->assertEquals('BA00V2111PK', $event['links']['customer_bank_account']); - + foreach ($this->mock['events'] as $event) { + if ($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) { + $this->assertEquals('CU001DXYDR3', $event['links']['customer']); + $this->assertEquals('BRQ005YJ7GHF', $event['links']['billing_request']); + $this->assertEquals('BA00V2111PK', $event['links']['customer_bank_account']); } + } - } - - // mock the invoice and the payment hash - + // mock the invoice and the payment hash } public function testInvoiceDelayedNotificationPayment() { - - $gocardlesspayment = new \stdClass; - $links = new \stdClass; - $links->mandate = "my_mandate"; - $gocardlesspayment->links = $links; - $gocardlesspayment->id = "gocardless_payment_id"; + $gocardlesspayment = new \stdClass; + $links = new \stdClass; + $links->mandate = "my_mandate"; + $gocardlesspayment->links = $links; + $gocardlesspayment->id = "gocardless_payment_id"; $invoice = Invoice::factory()->create( - [ - 'user_id' => $this->user->id, - 'company_id' => $this->company->id, - 'client_id' => $this->client->id - ]); + [ + 'user_id' => $this->user->id, + 'company_id' => $this->company->id, + 'client_id' => $this->client->id + ] + ); $invoice->status_id = Invoice::STATUS_SENT; $invoice->calc()->getInvoice()->save(); @@ -171,7 +164,7 @@ class GoCardlessInstantBankPaymentTest extends TestCase $this->assertIsArray($data_object->invoices); $this->assertIsObject(end($data_object->invoices)); - $this->assertEquals(1, count($data_object->invoices)); + $this->assertEquals(1, count($data_object->invoices)); $test_invoice_object = end($data_object->invoices); @@ -191,65 +184,52 @@ class GoCardlessInstantBankPaymentTest extends TestCase $cg->fees_and_limits = ''; $cg->save(); - foreach($this->mock['events'] as $event) - { + foreach ($this->mock['events'] as $event) { + if ($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) { + $hash = PaymentHash::whereJsonContains('data->billing_request', $event['links']['billing_request'])->first(); - if($event['action'] == 'fulfilled' && array_key_exists('billing_request', $event['links'])) { + $this->assertNotNull($hash); + $this->assertEquals('1234567890abc', $hash->hash); - $hash = PaymentHash::whereJsonContains('data->billing_request', $event['links']['billing_request'])->first(); + $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($hash->invoices(), 'invoice_id')))->withTrashed()->get(); - $this->assertNotNull($hash); - $this->assertEquals('1234567890abc', $hash->hash); + $this->assertNotNull($invoices); + $this->assertEquals(1, $invoices->count()); - $invoices = Invoice::whereIn('id', $this->transformKeys(array_column($hash->invoices(), 'invoice_id')))->withTrashed()->get(); + // remove all paid invoices + $invoices->filter(function ($invoice) { + return $invoice->isPayable(); + }); - $this->assertNotNull($invoices); - $this->assertEquals(1, $invoices->count()); - - // remove all paid invoices - $invoices->filter(function ($invoice){ - return $invoice->isPayable(); - }); - - $this->assertEquals(1, $invoices->count()); + $this->assertEquals(1, $invoices->count()); - $data = [ - 'payment_method' => $gocardlesspayment->links->mandate, - 'payment_type' => PaymentType::INSTANT_BANK_PAY, - 'amount' => $hash->data->amount_with_fee, - 'transaction_reference' => $gocardlesspayment->id, - 'gateway_type_id' => GatewayType::INSTANT_BANK_PAY, - ]; + $data = [ + 'payment_method' => $gocardlesspayment->links->mandate, + 'payment_type' => PaymentType::INSTANT_BANK_PAY, + 'amount' => $hash->data->amount_with_fee, + 'transaction_reference' => $gocardlesspayment->id, + 'gateway_type_id' => GatewayType::INSTANT_BANK_PAY, + ]; - $this->assertEquals('my_mandate', $data['payment_method']); - $this->assertEquals('gocardless_payment_id', $data['transaction_reference']); - $this->assertEquals($invoice->balance, $data['amount']); + $this->assertEquals('my_mandate', $data['payment_method']); + $this->assertEquals('gocardless_payment_id', $data['transaction_reference']); + $this->assertEquals($invoice->balance, $data['amount']); - $gocardless_driver = $cg->driver($this->client); - $gocardless_driver->setPaymentHash($hash); + $gocardless_driver = $cg->driver($this->client); + $gocardless_driver->setPaymentHash($hash); - $payment = $gocardless_driver->createPayment($data, Payment::STATUS_COMPLETED); + $payment = $gocardless_driver->createPayment($data, Payment::STATUS_COMPLETED); - $this->assertInstanceOf(Payment::class, $payment); - - $this->assertEquals(round($invoice->amount,2), round($payment->amount,2)); - $this->assertEquals(Payment::STATUS_COMPLETED, $payment->status_id); - $this->assertEquals(1, $payment->invoices()->count()); - $this->assertEquals($invoice->number, $payment->invoices()->first()->number); - $this->assertEquals(Invoice::STATUS_PAID, $payment->invoices()->first()->status_id); - - - - } - - } + $this->assertInstanceOf(Payment::class, $payment); + $this->assertEquals(round($invoice->amount, 2), round($payment->amount, 2)); + $this->assertEquals(Payment::STATUS_COMPLETED, $payment->status_id); + $this->assertEquals(1, $payment->invoices()->count()); + $this->assertEquals($invoice->number, $payment->invoices()->first()->number); + $this->assertEquals(Invoice::STATUS_PAID, $payment->invoices()->first()->status_id); + } + } } - - } - - - diff --git a/tests/Feature/Import/CSV/BaseTransformerTest.php b/tests/Feature/Import/CSV/BaseTransformerTest.php index 812d9b543e46..06f8451fa2bb 100644 --- a/tests/Feature/Import/CSV/BaseTransformerTest.php +++ b/tests/Feature/Import/CSV/BaseTransformerTest.php @@ -14,18 +14,12 @@ namespace Tests\Feature\Import\CSV; use App\Import\Transformer\BaseTransformer; use App\Models\Client; use App\Models\ClientContact; -use App\Models\Expense; use App\Models\Invoice; -use App\Models\Payment; use App\Models\Product; use App\Models\TaxRate; use App\Models\Vendor; use App\Utils\Traits\MakesHash; use Illuminate\Routing\Middleware\ThrottleRequests; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; -use League\Csv\Reader; -use League\Csv\Statement; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/Feature/Import/CSV/CsvImportTest.php b/tests/Feature/Import/CSV/CsvImportTest.php index af78d814a6db..9f8583fbdf3b 100644 --- a/tests/Feature/Import/CSV/CsvImportTest.php +++ b/tests/Feature/Import/CSV/CsvImportTest.php @@ -14,20 +14,13 @@ namespace Tests\Feature\Import\CSV; use App\Import\Providers\Csv; use App\Import\Transformer\BaseTransformer; use App\Models\Client; -use App\Models\ClientContact; -use App\Models\Expense; use App\Models\Invoice; -use App\Models\Payment; -use App\Models\Product; -use App\Models\TaxRate; use App\Models\Vendor; use App\Utils\Traits\MakesHash; use App\Utils\TruthSource; use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Str; -use League\Csv\Reader; -use League\Csv\Statement; use Tests\MockAccountData; use Tests\TestCase; @@ -53,7 +46,6 @@ class CsvImportTest extends TestCase $this->withoutExceptionHandling(); auth()->login($this->user); - } public function testExpenseCsvImport() @@ -324,6 +316,6 @@ class CsvImportTest extends TestCase $this->assertTrue($invoice->payments()->exists()); $this->assertEquals(1, $invoice->payments()->count()); - $this->assertEquals(51.03, round($invoice->payments()->sum('payments.amount'),2)); + $this->assertEquals(51.03, round($invoice->payments()->sum('payments.amount'), 2)); } } diff --git a/tests/Feature/Import/Freshbooks/FreshbooksTest.php b/tests/Feature/Import/Freshbooks/FreshbooksTest.php index a6062b1b3454..8b8e2e7b4971 100644 --- a/tests/Feature/Import/Freshbooks/FreshbooksTest.php +++ b/tests/Feature/Import/Freshbooks/FreshbooksTest.php @@ -11,14 +11,10 @@ namespace Tests\Feature\Import\Freshbooks; -use App\Import\Providers\BaseImport; use App\Import\Providers\Freshbooks; -use App\Import\Providers\Zoho; use App\Import\Transformer\BaseTransformer; use App\Models\Client; use App\Models\Invoice; -use App\Models\Product; -use App\Models\Vendor; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Routing\Middleware\ThrottleRequests; diff --git a/tests/Feature/Import/ImportCompanyTest.php b/tests/Feature/Import/ImportCompanyTest.php index 7860cd063ca9..593f742794b1 100644 --- a/tests/Feature/Import/ImportCompanyTest.php +++ b/tests/Feature/Import/ImportCompanyTest.php @@ -46,16 +46,10 @@ use App\Models\TaskStatus; use App\Models\TaxRate; use App\Models\User; use App\Models\Vendor; -use App\Models\VendorContact; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Support\Facades\Artisan; -use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Str; -use League\Csv\Reader; -use League\Csv\Statement; -use Tests\MockAccountData; use Tests\TestCase; /** @@ -199,9 +193,9 @@ class ImportCompanyTest extends TestCase unset($cu_array['id']); $new_cu = CompanyUser::firstOrNew( - ['user_id' => $user_id, 'company_id' => $this->company->id], - $cu_array, - ); + ['user_id' => $user_id, 'company_id' => $this->company->id], + $cu_array, + ); $new_cu->account_id = $this->account->id; $new_cu->save(['timestamps' => false]); @@ -229,9 +223,9 @@ class ImportCompanyTest extends TestCase unset($ct_array['id']); $new_ct = CompanyToken::firstOrNew( - ['user_id' => $user_id, 'company_id' => $this->company->id], - $ct_array, - ); + ['user_id' => $user_id, 'company_id' => $this->company->id], + $ct_array, + ); $new_ct->account_id = $this->account->id; $new_ct->save(['timestamps' => false]); @@ -258,9 +252,9 @@ class ImportCompanyTest extends TestCase unset($obj_array['id']); $new_obj = PaymentTerm::firstOrNew( - ['num_days' => $obj->num_days, 'company_id' => $this->company->id], - $obj_array, - ); + ['num_days' => $obj->num_days, 'company_id' => $this->company->id], + $obj_array, + ); $new_obj->save(['timestamps' => false]); } @@ -286,9 +280,9 @@ class ImportCompanyTest extends TestCase unset($obj_array['tax_rate_id']); $new_obj = TaxRate::firstOrNew( - ['name' => $obj->name, 'company_id' => $this->company->id, 'rate' => $obj->rate], - $obj_array, - ); + ['name' => $obj->name, 'company_id' => $this->company->id, 'rate' => $obj->rate], + $obj_array, + ); $new_obj->save(['timestamps' => false]); } @@ -313,9 +307,9 @@ class ImportCompanyTest extends TestCase unset($obj_array['id']); $new_obj = ExpenseCategory::firstOrNew( - ['name' => $obj->name, 'company_id' => $this->company->id], - $obj_array, - ); + ['name' => $obj->name, 'company_id' => $this->company->id], + $obj_array, + ); $new_obj->save(['timestamps' => false]); } @@ -340,9 +334,9 @@ class ImportCompanyTest extends TestCase unset($obj_array['id']); $new_obj = TaskStatus::firstOrNew( - ['name' => $obj->name, 'company_id' => $this->company->id], - $obj_array, - ); + ['name' => $obj->name, 'company_id' => $this->company->id], + $obj_array, + ); $new_obj->save(['timestamps' => false]); } @@ -372,9 +366,9 @@ class ImportCompanyTest extends TestCase unset($obj_array['documents']); $new_obj = Client::firstOrNew( - ['number' => $obj->number, 'company_id' => $this->company->id], - $obj_array, - ); + ['number' => $obj->number, 'company_id' => $this->company->id], + $obj_array, + ); $new_obj->save(['timestamps' => false]); @@ -408,9 +402,9 @@ class ImportCompanyTest extends TestCase $obj_array['client_id'] = $client_id; $new_obj = ClientContact::firstOrNew( - ['email' => $obj->email, 'company_id' => $this->company->id], - $obj_array, - ); + ['email' => $obj->email, 'company_id' => $this->company->id], + $obj_array, + ); $new_obj->save(['timestamps' => false]); @@ -426,11 +420,13 @@ class ImportCompanyTest extends TestCase /* Generic */ $this->assertEquals(1, count($this->backup_json_object->vendors)); - $this->genericImport(Vendor::class, + $this->genericImport( + Vendor::class, ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'], [['users' => 'user_id'], ['users' =>'assigned_user_id']], 'vendors', - 'number'); + 'number' + ); $this->assertEquals(1, Vendor::count()); @@ -438,11 +434,13 @@ class ImportCompanyTest extends TestCase $this->assertEquals(1, count($this->backup_json_object->projects)); //$class, $unset, $transforms, $object_property, $match_key - $this->genericImport(Project::class, + $this->genericImport( + Project::class, ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'client_id'], [['users' => 'user_id'], ['users' =>'assigned_user_id'], ['clients' => 'client_id']], 'projects', - 'number'); + 'number' + ); $this->assertEquals(1, Project::count()); @@ -452,7 +450,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(1, count($this->backup_json_object->products)); - $this->genericNewClassImport(Product::class, + $this->genericNewClassImport( + Product::class, ['user_id', 'company_id', 'hashed_id', 'id'], [['users' => 'user_id'], ['users' =>'assigned_user_id'], ['vendors' => 'vendor_id'], ['projects' => 'project_id']], 'products' @@ -463,7 +462,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(1, count($this->backup_json_object->company_gateways)); - $this->genericNewClassImport(CompanyGateway::class, + $this->genericNewClassImport( + CompanyGateway::class, ['user_id', 'company_id', 'hashed_id', 'id'], [['users' => 'user_id']], 'company_gateways' @@ -475,29 +475,35 @@ class ImportCompanyTest extends TestCase //client gateway tokens - $this->genericNewClassImport(ClientGatewayToken::class, + $this->genericNewClassImport( + ClientGatewayToken::class, ['company_id', 'id', 'hashed_id', 'client_id'], [['clients' => 'client_id']], - 'client_gateway_tokens'); + 'client_gateway_tokens' + ); //client gateway tokens //Group Settings - $this->genericImport(GroupSetting::class, + $this->genericImport( + GroupSetting::class, ['user_id', 'company_id', 'id', 'hashed_id'], [['users' => 'user_id']], 'group_settings', - 'name'); + 'name' + ); //Group Settings //Subscriptions $this->assertEquals(1, count($this->backup_json_object->subscriptions)); - $this->genericImport(Subscription::class, + $this->genericImport( + Subscription::class, ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id'], [['group_settings' => 'group_id'], ['users' => 'user_id'], ['users' => 'assigned_user_id']], 'subscriptions', - 'name'); + 'name' + ); $this->assertEquals(1, Subscription::count()); @@ -507,7 +513,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(2, count($this->backup_json_object->recurring_invoices)); - $this->genericImport(RecurringInvoice::class, + $this->genericImport( + RecurringInvoice::class, ['user_id', 'assigned_user_id', 'company_id', 'id', 'hashed_id', 'client_id', 'subscription_id', 'project_id', 'vendor_id', 'status'], [ ['subscriptions' => 'subscription_id'], @@ -519,7 +526,8 @@ class ImportCompanyTest extends TestCase ['clients' => 'client_id'], ], 'recurring_invoices', - 'number'); + 'number' + ); $this->assertEquals(2, RecurringInvoice::count()); @@ -529,7 +537,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(2, count($this->backup_json_object->recurring_invoice_invitations)); - $this->genericImport(RecurringInvoiceInvitation::class, + $this->genericImport( + RecurringInvoiceInvitation::class, ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'recurring_invoice_id'], [ ['users' => 'user_id'], @@ -537,7 +546,8 @@ class ImportCompanyTest extends TestCase ['client_contacts' => 'client_contact_id'], ], 'recurring_invoice_invitations', - 'key'); + 'key' + ); $this->assertEquals(2, RecurringInvoiceInvitation::count()); @@ -547,7 +557,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(2, count($this->backup_json_object->invoices)); - $this->genericImport(Invoice::class, + $this->genericImport( + Invoice::class, ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id', 'status'], [ ['users' => 'user_id'], @@ -559,7 +570,8 @@ class ImportCompanyTest extends TestCase ['vendors' => 'vendor_id'], ], 'invoices', - 'number'); + 'number' + ); $this->assertEquals(2, Invoice::count()); @@ -569,7 +581,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(2, count($this->backup_json_object->invoice_invitations)); - $this->genericImport(InvoiceInvitation::class, + $this->genericImport( + InvoiceInvitation::class, ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'invoice_id'], [ ['users' => 'user_id'], @@ -577,7 +590,8 @@ class ImportCompanyTest extends TestCase ['client_contacts' => 'client_contact_id'], ], 'invoice_invitations', - 'key'); + 'key' + ); $this->assertEquals(2, InvoiceInvitation::count()); @@ -586,7 +600,8 @@ class ImportCompanyTest extends TestCase // Quotes $this->assertEquals(2, count($this->backup_json_object->quotes)); - $this->genericImport(Quote::class, + $this->genericImport( + Quote::class, ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id', 'status'], [ ['users' => 'user_id'], @@ -598,7 +613,8 @@ class ImportCompanyTest extends TestCase ['vendors' => 'vendor_id'], ], 'quotes', - 'number'); + 'number' + ); $this->assertEquals(2, Quote::count()); @@ -608,7 +624,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(2, count($this->backup_json_object->quote_invitations)); - $this->genericImport(QuoteInvitation::class, + $this->genericImport( + QuoteInvitation::class, ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'quote_id'], [ ['users' => 'user_id'], @@ -616,7 +633,8 @@ class ImportCompanyTest extends TestCase ['client_contacts' => 'client_contact_id'], ], 'quote_invitations', - 'key'); + 'key' + ); $this->assertEquals(2, QuoteInvitation::count()); @@ -625,7 +643,8 @@ class ImportCompanyTest extends TestCase // Credits $this->assertEquals(2, count($this->backup_json_object->credits)); - $this->genericImport(Credit::class, + $this->genericImport( + Credit::class, ['user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'recurring_id', 'status'], [ ['users' => 'user_id'], @@ -637,7 +656,8 @@ class ImportCompanyTest extends TestCase ['vendors' => 'vendor_id'], ], 'credits', - 'number'); + 'number' + ); $this->assertEquals(2, Credit::count()); @@ -647,7 +667,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(2, count($this->backup_json_object->credit_invitations)); - $this->genericImport(CreditInvitation::class, + $this->genericImport( + CreditInvitation::class, ['user_id', 'client_contact_id', 'company_id', 'id', 'hashed_id', 'credit_id'], [ ['users' => 'user_id'], @@ -655,7 +676,8 @@ class ImportCompanyTest extends TestCase ['client_contacts' => 'client_contact_id'], ], 'credit_invitations', - 'key'); + 'key' + ); $this->assertEquals(2, CreditInvitation::count()); @@ -665,7 +687,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(2, count($this->backup_json_object->expenses)); - $this->genericImport(Expense::class, + $this->genericImport( + Expense::class, ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'project_id', 'vendor_id'], [ ['users' => 'user_id'], @@ -675,7 +698,8 @@ class ImportCompanyTest extends TestCase ['vendors' => 'vendor_id'], ], 'expenses', - 'number'); + 'number' + ); $this->assertEquals(2, Expense::count()); @@ -685,7 +709,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(3, count($this->backup_json_object->tasks)); - $this->genericImport(Task::class, + $this->genericImport( + Task::class, ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'invoice_id', 'project_id'], [ ['users' => 'user_id'], @@ -695,7 +720,8 @@ class ImportCompanyTest extends TestCase ['invoices' => 'invoice_id'], ], 'tasks', - 'number'); + 'number' + ); $this->assertEquals(3, Task::count()); @@ -705,7 +731,8 @@ class ImportCompanyTest extends TestCase $this->assertEquals(2, count($this->backup_json_object->payments)); - $this->genericImport(Payment::class, + $this->genericImport( + Payment::class, ['assigned_user_id', 'user_id', 'client_id', 'company_id', 'id', 'hashed_id', 'client_contact_id', 'invitation_id', 'vendor_id', 'paymentables'], [ ['users' => 'user_id'], @@ -717,7 +744,8 @@ class ImportCompanyTest extends TestCase ['company_gateways' => 'company_gateway_id'], ], 'payments', - 'number'); + 'number' + ); $this->assertEquals(2, Payment::count()); @@ -743,7 +771,8 @@ class ImportCompanyTest extends TestCase $this->backup_json_object->activities = $activities; - $this->genericNewClassImport(Activity::class, + $this->genericNewClassImport( + Activity::class, [ 'user_id', 'company_id', @@ -780,7 +809,8 @@ class ImportCompanyTest extends TestCase ['recurring_invoices' => 'recurring_invoice_id'], ['invitations' => 'invitation_id'], ], - 'activities'); + 'activities' + ); $this->assertEquals(25, Activity::count()); @@ -790,13 +820,15 @@ class ImportCompanyTest extends TestCase $this->assertEquals(25, count($this->backup_json_object->backups)); - $this->genericImportWithoutCompany(Backup::class, + $this->genericImportWithoutCompany( + Backup::class, ['activity_id', 'hashed_id', 'html_backup'], [ ['activities' => 'activity_id'], ], 'backups', - 'created_at'); + 'created_at' + ); $this->assertEquals(25, Backup::count()); @@ -805,7 +837,8 @@ class ImportCompanyTest extends TestCase // Company Ledger $this->assertEquals(3, count($this->backup_json_object->company_ledger)); - $this->genericImport(CompanyLedger::class, + $this->genericImport( + CompanyLedger::class, ['company_id', 'user_id', 'client_id', 'activity_id', 'id', 'account_id'], [ ['users' => 'user_id'], @@ -813,7 +846,8 @@ class ImportCompanyTest extends TestCase ['activities' => 'activity_id'], ], 'company_ledger', - 'created_at'); + 'created_at' + ); $this->assertEquals(3, CompanyLedger::count()); @@ -821,13 +855,15 @@ class ImportCompanyTest extends TestCase // Designs - $this->genericImport(Design::class, + $this->genericImport( + Design::class, ['company_id', 'user_id'], [ ['users' => 'user_id'], ], 'designs', - 'name'); + 'name' + ); // Designs @@ -1028,9 +1064,9 @@ class ImportCompanyTest extends TestCase } $new_obj = $class::firstOrNew( - [$match_key => $obj->{$match_key}], - $obj_array, - ); + [$match_key => $obj->{$match_key}], + $obj_array, + ); $new_obj->save(['timestamps' => false]); @@ -1068,9 +1104,9 @@ class ImportCompanyTest extends TestCase } $new_obj = $class::firstOrNew( - [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id], - $obj_array, - ); + [$match_key => $obj->{$match_key}, 'company_id' => $this->company->id], + $obj_array, + ); $new_obj->save(['timestamps' => false]); diff --git a/tests/Feature/Import/Invoice2Go/Invoice2GoTest.php b/tests/Feature/Import/Invoice2Go/Invoice2GoTest.php index 9cf62be12b67..d88313f0cf93 100644 --- a/tests/Feature/Import/Invoice2Go/Invoice2GoTest.php +++ b/tests/Feature/Import/Invoice2Go/Invoice2GoTest.php @@ -11,15 +11,10 @@ namespace Tests\Feature\Import\Invoice2Go; -use App\Import\Providers\BaseImport; -use App\Import\Providers\Freshbooks; use App\Import\Providers\Invoice2Go; -use App\Import\Providers\Zoho; use App\Import\Transformer\BaseTransformer; use App\Models\Client; use App\Models\Invoice; -use App\Models\Product; -use App\Models\Vendor; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Routing\Middleware\ThrottleRequests; diff --git a/tests/Feature/Import/Invoicely/InvoicelyTest.php b/tests/Feature/Import/Invoicely/InvoicelyTest.php index 8d4896516817..3358702adb6c 100644 --- a/tests/Feature/Import/Invoicely/InvoicelyTest.php +++ b/tests/Feature/Import/Invoicely/InvoicelyTest.php @@ -11,14 +11,10 @@ namespace Tests\Feature\Import\Invoicely; -use App\Import\Providers\BaseImport; use App\Import\Providers\Invoicely; -use App\Import\Providers\Zoho; use App\Import\Transformer\BaseTransformer; use App\Models\Client; use App\Models\Invoice; -use App\Models\Product; -use App\Models\Vendor; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Routing\Middleware\ThrottleRequests; diff --git a/tests/Feature/Import/Wave/WaveTest.php b/tests/Feature/Import/Wave/WaveTest.php index de984b5b9558..f8f3edf47fc7 100644 --- a/tests/Feature/Import/Wave/WaveTest.php +++ b/tests/Feature/Import/Wave/WaveTest.php @@ -11,7 +11,6 @@ namespace Tests\Feature\Import\Wave; -use App\Import\Providers\BaseImport; use App\Import\Providers\Wave; use App\Import\Transformer\BaseTransformer; use App\Models\Client; diff --git a/tests/Feature/Import/Zoho/ZohoTest.php b/tests/Feature/Import/Zoho/ZohoTest.php index 550abde66002..0ab065f392fd 100644 --- a/tests/Feature/Import/Zoho/ZohoTest.php +++ b/tests/Feature/Import/Zoho/ZohoTest.php @@ -11,13 +11,10 @@ namespace Tests\Feature\Import\Zoho; -use App\Import\Providers\BaseImport; use App\Import\Providers\Zoho; use App\Import\Transformer\BaseTransformer; use App\Models\Client; use App\Models\Invoice; -use App\Models\Product; -use App\Models\Vendor; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Routing\Middleware\ThrottleRequests; diff --git a/tests/Feature/Inventory/InventoryManagementTest.php b/tests/Feature/Inventory/InventoryManagementTest.php index 79e847f5cbb9..ee6556ccd354 100644 --- a/tests/Feature/Inventory/InventoryManagementTest.php +++ b/tests/Feature/Inventory/InventoryManagementTest.php @@ -39,7 +39,7 @@ class InventoryManagementTest extends TestCase ); if (config('ninja.testvars.travis') !== false) { - $this->markTestSkipped('Skip test for Travis'); + $this->markTestSkipped('Skip test for Travis'); } } @@ -90,7 +90,7 @@ class InventoryManagementTest extends TestCase $data = $response->json(); - $invoice = Invoice::find($this->decodePrimaryKey($data['data']['id'])); + $invoice = Invoice::find($this->decodePrimaryKey($data['data']['id'])); $invoice->service()->markDeleted()->save(); $invoice->is_deleted = true; @@ -98,13 +98,10 @@ class InventoryManagementTest extends TestCase $this->assertEquals(100, $product->fresh()->in_stock_quantity); - $invoice = Invoice::withTrashed()->find($this->decodePrimaryKey($data['data']['id'])); + $invoice = Invoice::withTrashed()->find($this->decodePrimaryKey($data['data']['id'])); $invoice->service()->handleRestore()->save(); $this->assertEquals(90, $product->fresh()->in_stock_quantity); - - - } } diff --git a/tests/Feature/InvitationTest.php b/tests/Feature/InvitationTest.php index 02610d5e5418..597f90cee7d8 100644 --- a/tests/Feature/InvitationTest.php +++ b/tests/Feature/InvitationTest.php @@ -21,10 +21,8 @@ use App\Models\Company; use App\Models\Invoice; use App\Models\User; use App\Utils\Traits\MakesHash; -use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Support\Facades\Session; use Tests\TestCase; /** @@ -42,7 +40,6 @@ class InvitationTest extends TestCase parent::setUp(); $this->faker = \Faker\Factory::create(); - } public function testInvoiceCreationAfterInvoiceMarkedSent() diff --git a/tests/Feature/InvoiceTest.php b/tests/Feature/InvoiceTest.php index f41f7f34af5c..60f5db3ae254 100644 --- a/tests/Feature/InvoiceTest.php +++ b/tests/Feature/InvoiceTest.php @@ -49,21 +49,19 @@ class InvoiceTest extends TestCase public function testInvoiceGetPaidInvoices() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, - ])->get('/api/v1/invoices?client_status=paid',) + ])->get('/api/v1/invoices?client_status=paid', ) ->assertStatus(200); } public function testInvoiceArchiveAction() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, - ])->get('/api/v1/invoices/'.$this->invoice->hashed_id.'/archive',) + ])->get('/api/v1/invoices/'.$this->invoice->hashed_id.'/archive', ) ->assertStatus(200); } @@ -312,6 +310,4 @@ class InvoiceTest extends TestCase ])->post('/api/v1/invoices/', $data) ->assertStatus(200); } - - } diff --git a/tests/Feature/LiveDesignTest.php b/tests/Feature/LiveDesignTest.php index 51d6fbfdf3ba..3bf5b0cf8957 100644 --- a/tests/Feature/LiveDesignTest.php +++ b/tests/Feature/LiveDesignTest.php @@ -38,17 +38,16 @@ class LiveDesignTest extends TestCase if (config('ninja.testvars.travis') !== false) { $this->markTestSkipped('Skip test for Travis'); } - } public function testDesignRoute200() { - $data = [ - 'entity' => 'invoice', - 'entity_id' => $this->invoice->hashed_id, - 'settings_type' => 'company', - 'settings' => (array)$this->company->settings, - ]; + $data = [ + 'entity' => 'invoice', + 'entity_id' => $this->invoice->hashed_id, + 'settings_type' => 'company', + 'settings' => (array)$this->company->settings, + ]; $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), @@ -57,6 +56,4 @@ class LiveDesignTest extends TestCase $response->assertStatus(200); } - - } diff --git a/tests/Feature/LoadTest.php b/tests/Feature/LoadTest.php index 38b5c15fa6f2..d884c17824f6 100644 --- a/tests/Feature/LoadTest.php +++ b/tests/Feature/LoadTest.php @@ -20,7 +20,6 @@ use App\Models\Client; use App\Models\ClientContact; use App\Models\Company; use App\Models\CompanyToken; -use App\Models\Country; use App\Models\Credit; use App\Models\Document; use App\Models\Expense; @@ -34,10 +33,7 @@ use App\Models\VendorContact; use App\Repositories\InvoiceRepository; use App\Utils\Traits\GeneratesCounter; use App\Utils\Traits\MakesHash; -use Illuminate\Foundation\Testing\DatabaseTransactions; -use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Support\Str; -use Tests\MockAccountData; use Tests\TestCase; /** diff --git a/tests/Feature/MultiPaymentDeleteTest.php b/tests/Feature/MultiPaymentDeleteTest.php index ee42d5fb4bcb..62df515c697e 100644 --- a/tests/Feature/MultiPaymentDeleteTest.php +++ b/tests/Feature/MultiPaymentDeleteTest.php @@ -11,7 +11,6 @@ namespace Tests\Feature; -use App\Factory\CompanyTokenFactory; use App\Factory\CompanyUserFactory; use App\Factory\InvoiceFactory; use App\Factory\InvoiceItemFactory; @@ -25,7 +24,6 @@ use App\Models\Payment; use App\Models\User; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Testing\DatabaseTransactions; -use Illuminate\Validation\ValidationException; use Tests\TestCase; /** diff --git a/tests/Feature/Notify/NotificationTest.php b/tests/Feature/Notify/NotificationTest.php index 0afee0a28c1a..50818f9299b0 100644 --- a/tests/Feature/Notify/NotificationTest.php +++ b/tests/Feature/Notify/NotificationTest.php @@ -11,7 +11,6 @@ namespace Tests\Feature\Notify; - use App\DataMapper\CompanySettings; use App\Models\CompanyToken; use App\Models\CompanyUser; @@ -51,7 +50,7 @@ class NotificationTest extends TestCase $u = User::factory()->create([ 'account_id' => $this->account->id, 'email' => $this->faker->safeEmail(), - 'confirmation_code' => uniqid("st",true), + 'confirmation_code' => uniqid("st", true), ]); $company_token = new CompanyToken; @@ -81,7 +80,7 @@ class NotificationTest extends TestCase $i = Invoice::factory()->create([ 'user_id' => $u->id, 'company_id' => $this->company->id, - 'number' => uniqid("st",true), + 'number' => uniqid("st", true), 'client_id' => $this->client->id, ]); @@ -99,7 +98,6 @@ class NotificationTest extends TestCase $methods = $this->findUserNotificationTypes($invitation, $company_user, 'invoice', ['all_notifications', 'invoice_viewed', 'invoice_viewed_all']); $this->assertCount(0, $methods); - } @@ -110,7 +108,7 @@ class NotificationTest extends TestCase $this->user->company_users()->where('company_id', $this->company->id)->update(['notifications' => (array)$notifications]); - $this->assertTrue(property_exists($this->cu->notifications,'email')); + $this->assertTrue(property_exists($this->cu->notifications, 'email')); $p = Product::factory()->create([ 'user_id' => $this->user->id, @@ -125,7 +123,6 @@ class NotificationTest extends TestCase $notification_users = $this->filterUsersByPermissions($this->company->company_users, $p, ['inventory_user','invalid notification']); $this->assertCount(0, $notification_users->toArray()); - } public function testAllNotificationsFires() @@ -142,7 +139,6 @@ class NotificationTest extends TestCase $notification_users = $this->filterUsersByPermissions($this->company->company_users, $p, ['inventory_all']); $this->assertCount(1, $notification_users->toArray()); - } public function testAllNotificationsFiresForUser() @@ -159,7 +155,6 @@ class NotificationTest extends TestCase $notification_users = $this->filterUsersByPermissions($this->company->company_users, $p, ['all_user_notifications']); $this->assertCount(1, $notification_users->toArray()); - } public function testAllNotificationsDoesNotFiresForUser() @@ -167,7 +162,7 @@ class NotificationTest extends TestCase $u = User::factory()->create([ 'account_id' => $this->account->id, 'email' => $this->faker->safeEmail(), - 'confirmation_code' => uniqid("st",true), + 'confirmation_code' => uniqid("st", true), ]); $company_token = new CompanyToken; @@ -237,8 +232,5 @@ class NotificationTest extends TestCase $this->assertCount(1, $methods); $this->assertTrue($this->checkNotificationExists($cu, $p, ['inventory_all', 'inventory_user'])); - } - - } diff --git a/tests/Feature/PaymentTest.php b/tests/Feature/PaymentTest.php index 0f95a9d33e65..aa963d7d46b3 100644 --- a/tests/Feature/PaymentTest.php +++ b/tests/Feature/PaymentTest.php @@ -64,14 +64,11 @@ class PaymentTest extends TestCase public function testGetPaymentMatchList() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->get('/api/v1/payments?match_transactions=true') ->assertStatus(200); - - } public function testStorePaymentIdempotencyKeyIllegalLength() @@ -114,12 +111,9 @@ class PaymentTest extends TestCase ])->post('/api/v1/payments/', $data); } catch (ValidationException $e) { // $message = json_decode($e->validator->getMessageBag(), 1); - - } $this->assertFalse($response); - } diff --git a/tests/Feature/Payments/CreditPaymentTest.php b/tests/Feature/Payments/CreditPaymentTest.php index bc031be4a235..2e25dfebe1d3 100644 --- a/tests/Feature/Payments/CreditPaymentTest.php +++ b/tests/Feature/Payments/CreditPaymentTest.php @@ -11,15 +11,9 @@ namespace Tests\Feature\Payments; -use App\DataMapper\ClientSettings; -use App\Factory\ClientFactory; -use App\Factory\CreditFactory; use App\Factory\InvoiceFactory; -use App\Factory\InvoiceItemFactory; -use App\Factory\PaymentFactory; use App\Helpers\Invoice\InvoiceSum; use App\Models\Client; -use App\Models\ClientContact; use App\Models\Credit; use App\Models\Invoice; use App\Models\Payment; @@ -30,7 +24,6 @@ use Illuminate\Foundation\Testing\WithoutEvents; use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Support\Facades\Session; use Illuminate\Validation\ValidationException; -use Tests\MockAccountData; use Tests\MockUnitData; use Tests\TestCase; diff --git a/tests/Feature/Payments/StorePaymentValidationTest.php b/tests/Feature/Payments/StorePaymentValidationTest.php index 1dce4cbd6b5e..72613a0680db 100644 --- a/tests/Feature/Payments/StorePaymentValidationTest.php +++ b/tests/Feature/Payments/StorePaymentValidationTest.php @@ -11,18 +11,6 @@ namespace Tests\Feature\Payments; -use App\DataMapper\ClientSettings; -use App\Factory\ClientFactory; -use App\Factory\CreditFactory; -use App\Factory\InvoiceFactory; -use App\Factory\InvoiceItemFactory; -use App\Factory\PaymentFactory; -use App\Helpers\Invoice\InvoiceSum; -use App\Models\Client; -use App\Models\ClientContact; -use App\Models\Credit; -use App\Models\Invoice; -use App\Models\Payment; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; @@ -31,7 +19,6 @@ use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Support\Facades\Session; use Illuminate\Validation\ValidationException; use Tests\MockAccountData; -use Tests\MockUnitData; use Tests\TestCase; /** @@ -217,6 +204,5 @@ class StorePaymentValidationTest extends TestCase } $response->assertStatus(302); - } } diff --git a/tests/Feature/Payments/UnappliedPaymentDeleteTest.php b/tests/Feature/Payments/UnappliedPaymentDeleteTest.php index c79591a163c2..1803279c9951 100644 --- a/tests/Feature/Payments/UnappliedPaymentDeleteTest.php +++ b/tests/Feature/Payments/UnappliedPaymentDeleteTest.php @@ -20,7 +20,6 @@ use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\WithoutEvents; use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Validation\ValidationException; -use Tests\MockAccountData; use Tests\MockUnitData; use Tests\TestCase; diff --git a/tests/Feature/Payments/UnappliedPaymentRefundTest.php b/tests/Feature/Payments/UnappliedPaymentRefundTest.php index f2b16336bdef..04f4cb63bc13 100644 --- a/tests/Feature/Payments/UnappliedPaymentRefundTest.php +++ b/tests/Feature/Payments/UnappliedPaymentRefundTest.php @@ -17,7 +17,6 @@ use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\WithoutEvents; use Illuminate\Routing\Middleware\ThrottleRequests; use Illuminate\Validation\ValidationException; -use Tests\MockAccountData; use Tests\MockUnitData; use Tests\TestCase; diff --git a/tests/Feature/PurchaseOrderTest.php b/tests/Feature/PurchaseOrderTest.php index 323732774d8a..b3fc1be63519 100644 --- a/tests/Feature/PurchaseOrderTest.php +++ b/tests/Feature/PurchaseOrderTest.php @@ -11,7 +11,6 @@ namespace Tests\Feature; -use App\Models\Client; use App\Models\PurchaseOrder; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; @@ -133,7 +132,6 @@ class PurchaseOrderTest extends TestCase 'X-API-TOKEN' => $this->token, ])->post("/api/v1/purchase_orders/bulk", $data) ->assertStatus(302); - } public function testPurchaseOrderDownloadPDF() @@ -147,7 +145,6 @@ class PurchaseOrderTest extends TestCase $response->assertStatus(200); $this->assertTrue($response->headers->get('content-type') == 'application/pdf'); - } diff --git a/tests/Feature/QuoteTest.php b/tests/Feature/QuoteTest.php index 1550e8ec8206..c324f05f8c30 100644 --- a/tests/Feature/QuoteTest.php +++ b/tests/Feature/QuoteTest.php @@ -11,7 +11,6 @@ namespace Tests\Feature; -use App\Models\Client; use App\Models\ClientContact; use App\Models\Project; use App\Models\Quote; @@ -61,7 +60,6 @@ class QuoteTest extends TestCase $response->assertStatus(200); $this->assertTrue($response->headers->get('content-type') == 'application/pdf'); - } public function testQuoteListApproved() @@ -80,7 +78,7 @@ class QuoteTest extends TestCase $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, - ])->post('/api/v1/quotes/bulk',['action' => 'convert_to_project', 'ids' => [$this->quote->hashed_id]]); + ])->post('/api/v1/quotes/bulk', ['action' => 'convert_to_project', 'ids' => [$this->quote->hashed_id]]); $response->assertStatus(200); @@ -183,5 +181,4 @@ class QuoteTest extends TestCase $response->assertStatus(200); } - } diff --git a/tests/Feature/RecurringInvoiceTest.php b/tests/Feature/RecurringInvoiceTest.php index be9c0e002bb2..f772c5aa714e 100644 --- a/tests/Feature/RecurringInvoiceTest.php +++ b/tests/Feature/RecurringInvoiceTest.php @@ -60,7 +60,6 @@ class RecurringInvoiceTest extends TestCase 'X-API-TOKEN' => $this->token, ])->get('/api/v1/recurring_invoices?client_status=active') ->assertStatus(200); - } diff --git a/tests/Feature/RecurringInvoicesCronTest.php b/tests/Feature/RecurringInvoicesCronTest.php index fe3c45ad0d0f..5a62db9a5dd7 100644 --- a/tests/Feature/RecurringInvoicesCronTest.php +++ b/tests/Feature/RecurringInvoicesCronTest.php @@ -39,7 +39,6 @@ class RecurringInvoicesCronTest extends TestCase public function testCountCorrectNumberOfRecurringInvoicesDue() { - //spin up 5 valid and 1 invalid recurring invoices $recurring_invoices = RecurringInvoice::where('next_send_date', '<=', Carbon::now()->addMinutes(30))->get(); diff --git a/tests/Feature/RecurringQuoteTest.php b/tests/Feature/RecurringQuoteTest.php index 3051f0466100..d795b5cf035a 100644 --- a/tests/Feature/RecurringQuoteTest.php +++ b/tests/Feature/RecurringQuoteTest.php @@ -49,7 +49,6 @@ class RecurringQuoteTest extends TestCase public function testRecurringQuoteListFilter() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, @@ -74,7 +73,7 @@ class RecurringQuoteTest extends TestCase { RecurringQuote::factory()->create(['user_id' => $this->user->id, 'company_id' => $this->company->id, 'client_id' => $this->client->id]); - $RecurringQuote = RecurringQuote::query()->where('user_id', $this->user->id)->orderBy('id','DESC')->first(); + $RecurringQuote = RecurringQuote::query()->where('user_id', $this->user->id)->orderBy('id', 'DESC')->first(); $RecurringQuote->save(); $response = $this->withHeaders([ diff --git a/tests/Feature/ReminderTest.php b/tests/Feature/ReminderTest.php index 2e9a30fe10f5..85d5428f334d 100644 --- a/tests/Feature/ReminderTest.php +++ b/tests/Feature/ReminderTest.php @@ -51,7 +51,6 @@ class ReminderTest extends TestCase public function testForClientTimezoneEdges() { - $this->invoice->next_send_date = null; $this->invoice->date = now()->format('Y-m-d'); $this->invoice->due_date = Carbon::now()->addDays(5)->format('Y-m-d'); @@ -128,7 +127,6 @@ class ReminderTest extends TestCase $this->assertTrue($next_send_date->eq($calculatedReminderDate)); nlog($next_send_date->format('Y-m-d h:i:s')); - } public function testReminderQueryCatchesDate() @@ -272,6 +270,4 @@ class ReminderTest extends TestCase $this->assertNotNull($this->invoice->next_send_date); } - - } diff --git a/tests/Feature/Scheduler/SchedulerTest.php b/tests/Feature/Scheduler/SchedulerTest.php index ebaebbe7a88c..d2ec6eee0931 100644 --- a/tests/Feature/Scheduler/SchedulerTest.php +++ b/tests/Feature/Scheduler/SchedulerTest.php @@ -51,23 +51,21 @@ class SchedulerTest extends TestCase $this->withoutMiddleware( ThrottleRequests::class ); - } public function testClientCountResolution() { - $c = Client::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, - 'number' => rand(1000,100000), + 'number' => rand(1000, 100000), 'name' => 'A fancy client' ]); $c2 = Client::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, - 'number' => rand(1000,100000), + 'number' => rand(1000, 100000), 'name' => 'A fancy client' ]); @@ -82,7 +80,7 @@ class SchedulerTest extends TestCase 'show_aging_table' => true, 'status' => 'paid', 'clients' => [ - $c2->hashed_id, + $c2->hashed_id, $c->hashed_id ], ], @@ -90,12 +88,11 @@ class SchedulerTest extends TestCase $response = false; - try{ + try { $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->postJson('/api/v1/task_schedulers', $data); - } catch (ValidationException $e) { $message = json_decode($e->validator->getMessageBag(), 1); nlog($message); @@ -117,23 +114,21 @@ class SchedulerTest extends TestCase ->cursor(); $this->assertCount(2, $q); - } public function testClientsValidationInScheduledTask() { - $c = Client::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, - 'number' => rand(1000,100000), + 'number' => rand(1000, 100000), 'name' => 'A fancy client' ]); $c2 = Client::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, - 'number' => rand(1000,100000), + 'number' => rand(1000, 100000), 'name' => 'A fancy client' ]); @@ -148,7 +143,7 @@ class SchedulerTest extends TestCase 'show_aging_table' => true, 'status' => 'paid', 'clients' => [ - $c2->hashed_id, + $c2->hashed_id, $c->hashed_id ], ], @@ -156,12 +151,11 @@ class SchedulerTest extends TestCase $response = false; - try{ + try { $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->postJson('/api/v1/task_schedulers', $data); - } catch (ValidationException $e) { $message = json_decode($e->validator->getMessageBag(), 1); nlog($message); @@ -181,7 +175,7 @@ class SchedulerTest extends TestCase 'show_aging_table' => true, 'status' => 'paid', 'clients' => [ - $c2->hashed_id, + $c2->hashed_id, ], ], ]; @@ -205,7 +199,7 @@ class SchedulerTest extends TestCase 'show_aging_table' => true, 'status' => 'paid', 'clients' => [ - 'xx33434', + 'xx33434', ], ], ]; @@ -216,14 +210,11 @@ class SchedulerTest extends TestCase ])->postJson('/api/v1/task_schedulers', $data); $response->assertStatus(422); - - } public function testCalculateNextRun() { - $scheduler = SchedulerFactory::create($this->company->id, $this->user->id); $data = [ @@ -247,13 +238,12 @@ class SchedulerTest extends TestCase $reflectionMethod = new \ReflectionMethod(SchedulerService::class, 'calculateNextRun'); $reflectionMethod->setAccessible(true); - $method = $reflectionMethod->invoke(new SchedulerService($scheduler)); + $method = $reflectionMethod->invoke(new SchedulerService($scheduler)); $scheduler->fresh(); $offset = $this->company->timezone_offset(); $this->assertEquals(now()->startOfDay()->addMonthNoOverflow()->addSeconds($offset)->format('Y-m-d'), $scheduler->next_run->format('Y-m-d')); - } public function testCalculateStartAndEndDates() @@ -283,19 +273,17 @@ class SchedulerTest extends TestCase $reflectionMethod = new \ReflectionMethod(SchedulerService::class, 'calculateStartAndEndDates'); $reflectionMethod->setAccessible(true); - $method = $reflectionMethod->invoke(new SchedulerService($scheduler)); + $method = $reflectionMethod->invoke(new SchedulerService($scheduler)); $this->assertIsArray($method); $this->assertEquals('previous_month', $scheduler->parameters['date_range']); $this->assertEqualsCanonicalizing(['2022-12-01','2022-12-31'], $method); - } public function testCalculateStatementProperties() { - $scheduler = SchedulerFactory::create($this->company->id, $this->user->id); $data = [ @@ -329,12 +317,10 @@ class SchedulerTest extends TestCase $this->assertIsArray($method); $this->assertEquals('paid', $method['status']); - } public function testGetThisMonthRange() { - $this->travelTo(Carbon::parse('2023-01-14')); $this->assertEqualsCanonicalizing(['2023-01-01','2023-01-31'], $this->getDateRange('this_month')); @@ -346,7 +332,6 @@ class SchedulerTest extends TestCase $this->assertEqualsCanonicalizing(['2022-01-01','2022-12-31'], $this->getDateRange('previous_year')); $this->travelBack(); - } private function getDateRange($range) @@ -384,12 +369,10 @@ class SchedulerTest extends TestCase ])->postJson('/api/v1/task_schedulers', $data); $response->assertStatus(200); - } public function testDeleteSchedule() { - $data = [ 'ids' => [$this->scheduler->hashed_id], ]; @@ -410,12 +393,10 @@ class SchedulerTest extends TestCase 'X-API-TOKEN' => $this->token, ])->postJson('/api/v1/task_schedulers/bulk?action=restore', $data) ->assertStatus(200); - - } + } public function testRestoreSchedule() { - $data = [ 'ids' => [$this->scheduler->hashed_id], ]; @@ -436,12 +417,10 @@ class SchedulerTest extends TestCase 'X-API-TOKEN' => $this->token, ])->postJson('/api/v1/task_schedulers/bulk?action=restore', $data) ->assertStatus(200); - - } + } public function testArchiveSchedule() { - $data = [ 'ids' => [$this->scheduler->hashed_id], ]; @@ -451,12 +430,10 @@ class SchedulerTest extends TestCase 'X-API-TOKEN' => $this->token, ])->postJson('/api/v1/task_schedulers/bulk?action=archive', $data) ->assertStatus(200); - } public function testSchedulerPost() { - $data = [ 'name' => 'A different Name', 'frequency_id' => 5, @@ -471,11 +448,10 @@ class SchedulerTest extends TestCase ])->postJson('/api/v1/task_schedulers', $data); $response->assertStatus(200); - } + } public function testSchedulerPut() { - $data = [ 'name' => 'A different Name', 'frequency_id' => 5, @@ -490,7 +466,7 @@ class SchedulerTest extends TestCase ])->putJson('/api/v1/task_schedulers/'.$this->scheduler->hashed_id, $data); $response->assertStatus(200); - } + } public function testSchedulerGet() { diff --git a/tests/Feature/SubscriptionApiTest.php b/tests/Feature/SubscriptionApiTest.php index 46cf797c20e1..61f72e0d6451 100644 --- a/tests/Feature/SubscriptionApiTest.php +++ b/tests/Feature/SubscriptionApiTest.php @@ -12,13 +12,10 @@ namespace Tests\Feature; use App\Models\Product; -use App\Models\RecurringInvoice; use App\Models\Subscription; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Support\Facades\Session; use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; @@ -52,13 +49,11 @@ class SubscriptionApiTest extends TestCase public function testSubscriptionFilter() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->get('/api/v1/subscriptions?filter=xx') ->assertStatus(200); - } public function testSubscriptionsGet() diff --git a/tests/Feature/SystemLogApiTest.php b/tests/Feature/SystemLogApiTest.php index 56985c502a7a..53d57b21073c 100644 --- a/tests/Feature/SystemLogApiTest.php +++ b/tests/Feature/SystemLogApiTest.php @@ -37,13 +37,12 @@ class SystemLogApiTest extends TestCase public function testFilters() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, ])->get('/api/v1/system_logs?type_id=3') - ->assertStatus(200);; - + ->assertStatus(200); + ; } public function testSystemLogRoutes() diff --git a/tests/Feature/TaskApiTest.php b/tests/Feature/TaskApiTest.php index b5f77674024a..24a5de247f58 100644 --- a/tests/Feature/TaskApiTest.php +++ b/tests/Feature/TaskApiTest.php @@ -45,8 +45,9 @@ class TaskApiTest extends TestCase private function checkTimeLog(array $log): bool { - if(count($log) == 0) + if (count($log) == 0) { return true; + } /*Get first value of all arrays*/ $result = array_column($log, 0); @@ -57,57 +58,58 @@ class TaskApiTest extends TestCase $new_array = []; /*Rebuild the array in order*/ - foreach($result as $key => $value) + foreach ($result as $key => $value) { $new_array[] = $log[$key]; + } /*Iterate through the array and perform checks*/ - foreach($new_array as $key => $array) - { + foreach ($new_array as $key => $array) { /*Flag which helps us know if there is a NEXT timelog*/ $next = false; /* If there are more than 1 time log in the array, ensure the last timestamp is not zero*/ - if(count($new_array) >1 && $array[1] == 0) + if (count($new_array) >1 && $array[1] == 0) { return false; + } - /* Check if the start time is greater than the end time */ - /* Ignore the last value for now, we'll do a separate check for this */ - if($array[0] > $array[1] && $array[1] != 0) + /* Check if the start time is greater than the end time */ + /* Ignore the last value for now, we'll do a separate check for this */ + if ($array[0] > $array[1] && $array[1] != 0) { return false; + } /* Find the next time log value - if it exists */ - if(array_key_exists($key+1, $new_array)) + if (array_key_exists($key+1, $new_array)) { $next = $new_array[$key+1]; + } /* check the next time log and ensure the start time is GREATER than the end time of the previous record */ - if($next && $next[0] < $array[1]) + if ($next && $next[0] < $array[1]) { return false; + } /* Get the last row of the timelog*/ $last_row = end($new_array); /*If the last value is NOT zero, ensure start time is not GREATER than the endtime */ - if($last_row[1] != 0 && $last_row[0] > $last_row[1]) + if ($last_row[1] != 0 && $last_row[0] > $last_row[1]) { return false; + } return true; } - } public function testTimeLogChecker1() { - $log = [ [50,0] ]; $this->assertTrue($this->checkTimeLog($log)); - } public function testTimeLogChecker2() { - $log = [ [4,5], [5,1] @@ -115,13 +117,11 @@ class TaskApiTest extends TestCase $this->assertFalse($this->checkTimeLog($log)); - } public function testTimeLogChecker3() { - $log = [ [4,5], [3,50] @@ -129,13 +129,11 @@ class TaskApiTest extends TestCase $this->assertFalse($this->checkTimeLog($log)); - } public function testTimeLogChecker4() { - $log = [ [4,5], [3,0] @@ -143,12 +141,10 @@ class TaskApiTest extends TestCase $this->assertFalse($this->checkTimeLog($log)); - } public function testTimeLogChecker5() { - $log = [ [4,5], [3,1] @@ -156,12 +152,10 @@ class TaskApiTest extends TestCase $this->assertFalse($this->checkTimeLog($log)); - } public function testTimeLogChecker6() { - $log = [ [4,5], [1,3], @@ -169,12 +163,10 @@ class TaskApiTest extends TestCase $this->assertTrue($this->checkTimeLog($log)); - } public function testTimeLogChecker7() { - $log = [ [1,3], [4,5] @@ -182,58 +174,49 @@ class TaskApiTest extends TestCase $this->assertTrue($this->checkTimeLog($log)); - } public function testTimeLogChecker8() { - $log = [ [1,3], [50,0] ]; $this->assertTrue($this->checkTimeLog($log)); - } public function testTimeLogChecker9() { - $log = [ [4,5,'bb'], [50,0,'aa'], ]; $this->assertTrue($this->checkTimeLog($log)); - } public function testTimeLogChecker10() { - $log = [ [4,5,'5'], [50,0,'3'], ]; $this->assertTrue($this->checkTimeLog($log)); - } public function testTimeLogChecker11() { - $log = [ [1,2,'a'], [3,4,'d'], ]; $this->assertTrue($this->checkTimeLog($log)); - } @@ -244,7 +227,6 @@ class TaskApiTest extends TestCase 'X-API-TOKEN' => $this->token, ])->get('/api/v1/tasks?client_status=invoiced') ->assertStatus(200); - } public function testTaskLockingGate() @@ -296,7 +278,6 @@ class TaskApiTest extends TestCase $arr = $response->json(); $response->assertStatus(401); - } @@ -345,7 +326,6 @@ class TaskApiTest extends TestCase } catch (ValidationException $e) { $response->assertStatus(302); } - } public function testTimeLogValidation1() @@ -361,7 +341,6 @@ class TaskApiTest extends TestCase $arr = $response->json(); $response->assertStatus(200); - } @@ -379,8 +358,6 @@ class TaskApiTest extends TestCase $arr = $response->json(); $response->assertStatus(200); - - } public function testTimeLogValidation3() @@ -399,7 +376,6 @@ class TaskApiTest extends TestCase } catch (ValidationException $e) { $response->assertStatus(302); } - } public function testTimeLogValidation4() @@ -415,8 +391,6 @@ class TaskApiTest extends TestCase $arr = $response->json(); $response->assertStatus(200); - - } @@ -513,15 +487,14 @@ class TaskApiTest extends TestCase ]; try { - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->token, - ])->post('/api/v1/tasks', $data); + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->token, + ])->post('/api/v1/tasks', $data); $arr = $response->json(); } catch (ValidationException $e) { $response->assertStatus(302); } - } public function testTaskPostWithActionStart() diff --git a/tests/Feature/UpdatePaymentTest.php b/tests/Feature/UpdatePaymentTest.php index cc53702ed6fa..911b6d68a24b 100644 --- a/tests/Feature/UpdatePaymentTest.php +++ b/tests/Feature/UpdatePaymentTest.php @@ -11,20 +11,12 @@ namespace Tests\Feature; -use App\DataMapper\ClientSettings; -use App\Factory\ClientFactory; -use App\Factory\CreditFactory; use App\Factory\InvoiceFactory; -use App\Factory\InvoiceItemFactory; -use App\Factory\PaymentFactory; use App\Helpers\Invoice\InvoiceSum; use App\Models\Client; -use App\Models\ClientContact; -use App\Models\Credit; use App\Models\Invoice; use App\Models\Payment; use App\Utils\Traits\MakesHash; -use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\WithoutEvents; use Illuminate\Routing\Middleware\ThrottleRequests; @@ -62,7 +54,6 @@ class UpdatePaymentTest extends TestCase public function testUpdatePaymentClientPaidToDate() { - //Create new client $client = Client::factory()->create([ 'user_id' => $this->user->id, diff --git a/tests/Feature/UserTest.php b/tests/Feature/UserTest.php index 39d4dafefc1b..8d6dd7fdc045 100644 --- a/tests/Feature/UserTest.php +++ b/tests/Feature/UserTest.php @@ -12,7 +12,6 @@ namespace Tests\Feature; use App\Factory\CompanyUserFactory; -use App\Factory\UserFactory; use App\Http\Middleware\PasswordProtection; use App\Models\Company; use App\Models\CompanyToken; @@ -55,12 +54,10 @@ class UserTest extends TestCase ThrottleRequests::class, PasswordProtection::class ); - } public function testUserFiltersWith() { - $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, @@ -68,7 +65,6 @@ class UserTest extends TestCase ])->get('/api/v1/users?with='.$this->user->hashed_id); $response->assertStatus(200); - } public function testUserList() @@ -105,7 +101,6 @@ class UserTest extends TestCase ])->post('/api/v1/users?include=company_user', $data); $response->assertStatus(200); - } public function testValidationRulesPhoneIsBlankString() @@ -155,7 +150,6 @@ class UserTest extends TestCase 'X-API-TOKEN' => $this->token, 'X-API-PASSWORD' => 'ALongAndBriliantPassword', ])->putJson('/api/v1/users/'.$user->hashed_id.'?include=company_user', $data); - } public function testUserStore() diff --git a/tests/Feature/WebhookAPITest.php b/tests/Feature/WebhookAPITest.php index 0d1708a2f34a..a2ed5c54f3a3 100644 --- a/tests/Feature/WebhookAPITest.php +++ b/tests/Feature/WebhookAPITest.php @@ -11,14 +11,10 @@ namespace Tests\Feature; -use App\Jobs\Util\WebhookHandler; -use App\Repositories\ClientContactRepository; -use App\Repositories\ClientRepository; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Routing\Middleware\ThrottleRequests; -use Illuminate\Support\Facades\Queue; use Tests\MockAccountData; use Tests\TestCase; @@ -71,7 +67,6 @@ class WebhookAPITest extends TestCase public function testWebhookPostRoute() { - $data = [ 'target_url' => 'http://hook.com', 'event_id' => 1, diff --git a/tests/Integration/CheckRemindersTest.php b/tests/Integration/CheckRemindersTest.php index ab6478a1fdc1..9911349f05bd 100644 --- a/tests/Integration/CheckRemindersTest.php +++ b/tests/Integration/CheckRemindersTest.php @@ -12,7 +12,6 @@ namespace Tests\Integration; use App\Models\Invoice; -use App\Utils\Traits\MakesReminders; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Carbon; use Tests\MockAccountData; diff --git a/tests/Integration/CompanyLedgerTest.php b/tests/Integration/CompanyLedgerTest.php index f07f36b62e00..8a4927886015 100644 --- a/tests/Integration/CompanyLedgerTest.php +++ b/tests/Integration/CompanyLedgerTest.php @@ -23,11 +23,8 @@ use App\Models\Payment; use App\Models\User; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Testing\DatabaseTransactions; -use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Hash; -use Illuminate\Support\Facades\Schema; use Illuminate\Validation\ValidationException; -use Tests\MockAccountData; use Tests\TestCase; /** @test*/ diff --git a/tests/Integration/DownloadHistoricalInvoiceTest.php b/tests/Integration/DownloadHistoricalInvoiceTest.php index 5bd475668f29..acce97b9afa4 100644 --- a/tests/Integration/DownloadHistoricalInvoiceTest.php +++ b/tests/Integration/DownloadHistoricalInvoiceTest.php @@ -57,6 +57,4 @@ class DownloadHistoricalInvoiceTest extends TestCase $this->assertNotNull($this->invoice->activities); } - - } diff --git a/tests/Integration/EventTest.php b/tests/Integration/EventTest.php index ccf565521fd5..8d2323c6e61d 100644 --- a/tests/Integration/EventTest.php +++ b/tests/Integration/EventTest.php @@ -6,7 +6,7 @@ * * @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com) * - * @license https://www.elastic.co/licensing/elastic-license + * @license https://www.elastic.co/licensing/elastic-license */ namespace Tests\Integration; @@ -31,15 +31,15 @@ use App\Events\Invoice\InvoiceWasDeleted; use App\Events\Invoice\InvoiceWasRestored; use App\Events\Invoice\InvoiceWasUpdated; use App\Events\Payment\PaymentWasArchived; -use App\Events\PurchaseOrder\PurchaseOrderWasCreated; -use App\Events\PurchaseOrder\PurchaseOrderWasUpdated; -use App\Events\PurchaseOrder\PurchaseOrderWasArchived; -use App\Events\PurchaseOrder\PurchaseOrderWasRestored; -use App\Events\PurchaseOrder\PurchaseOrderWasDeleted; use App\Events\Payment\PaymentWasCreated; use App\Events\Payment\PaymentWasDeleted; use App\Events\Payment\PaymentWasRestored; use App\Events\Payment\PaymentWasUpdated; +use App\Events\PurchaseOrder\PurchaseOrderWasArchived; +use App\Events\PurchaseOrder\PurchaseOrderWasCreated; +use App\Events\PurchaseOrder\PurchaseOrderWasDeleted; +use App\Events\PurchaseOrder\PurchaseOrderWasRestored; +use App\Events\PurchaseOrder\PurchaseOrderWasUpdated; use App\Events\Quote\QuoteWasApproved; use App\Events\Quote\QuoteWasArchived; use App\Events\Quote\QuoteWasCreated; @@ -167,7 +167,6 @@ class EventTest extends TestCase public function testVendorEvents() { - $this->expectsEvents([ VendorWasCreated::class, VendorWasUpdated::class, @@ -227,7 +226,6 @@ class EventTest extends TestCase public function testTaskEvents() { - /* Test fire new invoice */ $data = [ 'client_id' => $this->client->hashed_id, @@ -288,7 +286,6 @@ class EventTest extends TestCase public function testCreditEvents() { - /* Test fire new invoice */ $data = [ 'client_id' => $this->client->hashed_id, @@ -349,7 +346,6 @@ class EventTest extends TestCase public function testQuoteEvents() { - /* Test fire new invoice */ $data = [ 'client_id' => $this->client->hashed_id, @@ -812,75 +808,72 @@ class EventTest extends TestCase public function PurchaseOrderEvents() - { +{ + /* Test fire new invoice */ + $data = [ + 'client_id' => $this->vendor->hashed_id, + 'number' => 'dude', + ]; - /* Test fire new invoice */ - $data = [ - 'client_id' => $this->vendor->hashed_id, - 'number' => 'dude', - ]; + $this->expectsEvents([ + PurchaseOrderWasCreated::class, + PurchaseOrderWasUpdated::class, + PurchaseOrderWasArchived::class, + PurchaseOrderWasRestored::class, + PurchaseOrderWasDeleted::class, + ]); - $this->expectsEvents([ - PurchaseOrderWasCreated::class, - PurchaseOrderWasUpdated::class, - PurchaseOrderWasArchived::class, - PurchaseOrderWasRestored::class, - PurchaseOrderWasDeleted::class, - ]); - - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->token, - ])->postJson('/api/v1/purchase_orders/', $data) - ->assertStatus(200); + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->token, + ])->postJson('/api/v1/purchase_orders/', $data) + ->assertStatus(200); - $arr = $response->json(); + $arr = $response->json(); - $data = [ - 'client_id' => $this->vendor->hashed_id, - 'number' => 'dude2', - ]; + $data = [ + 'client_id' => $this->vendor->hashed_id, + 'number' => 'dude2', + ]; - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->token, - ])->putJson('/api/v1/purchase_orders/' . $arr['data']['id'], $data) - ->assertStatus(200); + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->token, + ])->putJson('/api/v1/purchase_orders/' . $arr['data']['id'], $data) + ->assertStatus(200); - $data = [ - 'ids' => [$arr['data']['id']], - ]; + $data = [ + 'ids' => [$arr['data']['id']], + ]; - $quote = PurchaseOrder::find($this->decodePrimaryKey($arr['data']['id'])); - $quote->status_id = PurchaseOrder::STATUS_SENT; - $quote->save(); + $quote = PurchaseOrder::find($this->decodePrimaryKey($arr['data']['id'])); + $quote->status_id = PurchaseOrder::STATUS_SENT; + $quote->save(); - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->token, - ])->postJson('/api/v1/purchase_orders/bulk?action=archive', $data) - ->assertStatus(200); + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->token, + ])->postJson('/api/v1/purchase_orders/bulk?action=archive', $data) + ->assertStatus(200); - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->token, - ])->postJson('/api/v1/purchase_orders/bulk?action=restore', $data) - ->assertStatus(200); - - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->token, - ])->postJson('/api/v1/purchase_orders/bulk?action=approve', $data) - ->assertStatus(200); - - $response = $this->withHeaders([ - 'X-API-SECRET' => config('ninja.api_secret'), - 'X-API-TOKEN' => $this->token, - ])->postJson('/api/v1/purchase_orders/bulk?action=delete', $data) - ->assertStatus(200); - } + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->token, + ])->postJson('/api/v1/purchase_orders/bulk?action=restore', $data) + ->assertStatus(200); + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->token, + ])->postJson('/api/v1/purchase_orders/bulk?action=approve', $data) + ->assertStatus(200); + $response = $this->withHeaders([ + 'X-API-SECRET' => config('ninja.api_secret'), + 'X-API-TOKEN' => $this->token, + ])->postJson('/api/v1/purchase_orders/bulk?action=delete', $data) + ->assertStatus(200); +} } diff --git a/tests/Integration/MultiDBUserTest.php b/tests/Integration/MultiDBUserTest.php index b61c0662e6f6..354cae6ded51 100644 --- a/tests/Integration/MultiDBUserTest.php +++ b/tests/Integration/MultiDBUserTest.php @@ -180,8 +180,7 @@ class MultiDBUserTest extends TestCase public function test_cross_db_user_linking_fails_appropriately() { - - //$this->withoutExceptionHandling(); + //$this->withoutExceptionHandling(); $data = [ 'first_name' => 'hey', diff --git a/tests/Integration/PostmarkWebhookTest.php b/tests/Integration/PostmarkWebhookTest.php index 2ad08ff60fb2..f57191cedabc 100644 --- a/tests/Integration/PostmarkWebhookTest.php +++ b/tests/Integration/PostmarkWebhookTest.php @@ -12,7 +12,6 @@ namespace Tests\Integration; use App\Jobs\PostMark\ProcessPostmarkWebhook; -use App\Models\Invoice; use Illuminate\Foundation\Testing\DatabaseTransactions; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/MockAccountData.php b/tests/MockAccountData.php index 8c3160c95b96..b1caf098c759 100644 --- a/tests/MockAccountData.php +++ b/tests/MockAccountData.php @@ -41,7 +41,6 @@ use App\Models\InvoiceInvitation; use App\Models\Payment; use App\Models\Product; use App\Models\Project; -use App\Models\PurchaseOrder; use App\Models\PurchaseOrderInvitation; use App\Models\Quote; use App\Models\QuoteInvitation; @@ -64,7 +63,6 @@ use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Storage; -use Illuminate\Support\Str; /** * Class MockAccountData. @@ -196,7 +194,6 @@ trait MockAccountData $this->artisan('db:seed --force'); foreach ($cached_tables as $name => $class) { - // check that the table exists in case the migration is pending if (! Schema::hasTable((new $class())->getTable())) { continue; @@ -828,7 +825,6 @@ trait MockAccountData ]); $this->scheduler->save(); - } /** diff --git a/tests/Unit/AutoBillInvoiceTest.php b/tests/Unit/AutoBillInvoiceTest.php index aa8ef0281e66..c4a2f5a761b0 100644 --- a/tests/Unit/AutoBillInvoiceTest.php +++ b/tests/Unit/AutoBillInvoiceTest.php @@ -11,7 +11,6 @@ namespace Tests\Unit; -use App\Models\Invoice; use Illuminate\Foundation\Testing\DatabaseTransactions; use Tests\MockAccountData; use Tests\TestCase; @@ -47,5 +46,4 @@ class AutoBillInvoiceTest extends TestCase $this->assertEquals($this->client->fresh()->paid_to_date, 10); $this->assertEquals($this->client->fresh()->credit_balance, 0); } - } diff --git a/tests/Unit/CentConversionTest.php b/tests/Unit/CentConversionTest.php index ec166fd680d6..026cbc97a5f9 100644 --- a/tests/Unit/CentConversionTest.php +++ b/tests/Unit/CentConversionTest.php @@ -11,7 +11,6 @@ namespace Tests\Unit; -use App\DataMapper\ClientSettings; use Tests\TestCase; /** diff --git a/tests/Unit/Chart/ChartCurrencyTest.php b/tests/Unit/Chart/ChartCurrencyTest.php index 2f30dfd57964..888d5c35f0a1 100644 --- a/tests/Unit/Chart/ChartCurrencyTest.php +++ b/tests/Unit/Chart/ChartCurrencyTest.php @@ -15,7 +15,6 @@ use App\DataMapper\ClientSettings; use App\Models\Client; use App\Models\Invoice; use App\Services\Chart\ChartService; -use App\Utils\Ninja; use Illuminate\Foundation\Testing\DatabaseTransactions; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/Unit/ClientSettingsTest.php b/tests/Unit/ClientSettingsTest.php index befc88b2d62b..01e707a70506 100644 --- a/tests/Unit/ClientSettingsTest.php +++ b/tests/Unit/ClientSettingsTest.php @@ -31,7 +31,6 @@ class ClientSettingsTest extends TestCase $this->makeTestData(); $this->faker = \Faker\Factory::create(); - } public function testClientBaseline() @@ -101,7 +100,6 @@ class ClientSettingsTest extends TestCase public function testClientIllegalCurrency() { - $data = [ 'name' => $this->faker->firstName(), 'id_number' => 'Cooliox2', diff --git a/tests/Unit/CollectionMergingTest.php b/tests/Unit/CollectionMergingTest.php index a4afd8993f8e..016c5922b7aa 100644 --- a/tests/Unit/CollectionMergingTest.php +++ b/tests/Unit/CollectionMergingTest.php @@ -13,8 +13,6 @@ namespace Tests\Unit; use App\Factory\ClientContactFactory; use App\Factory\InvoiceItemFactory; -use App\Utils\Traits\UserSessionAttributes; -use Illuminate\Support\Facades\Session; use Tests\TestCase; /** diff --git a/tests/Unit/CompanyDocumentsTest.php b/tests/Unit/CompanyDocumentsTest.php index 49ef1058bc59..0675197caccf 100644 --- a/tests/Unit/CompanyDocumentsTest.php +++ b/tests/Unit/CompanyDocumentsTest.php @@ -50,7 +50,8 @@ class CompanyDocumentsTest extends TestCase UploadFile::IMAGE, $this->user, $this->company, - $this->invoice))->handle(); + $this->invoice + ))->handle(); $this->assertNotNull($document); diff --git a/tests/Unit/CompareCollectionTest.php b/tests/Unit/CompareCollectionTest.php index d51f55b606b4..718a92258e48 100644 --- a/tests/Unit/CompareCollectionTest.php +++ b/tests/Unit/CompareCollectionTest.php @@ -53,19 +53,15 @@ class CompareCollectionTest extends TestCase $invoices = explode(",", $invoice_ids); - if(count($invoices) >= 1) - { - - foreach($invoices as $invoice){ - - if(is_string($invoice) && strlen($invoice) > 1) + if (count($invoices) >= 1) { + foreach ($invoices as $invoice) { + if (is_string($invoice) && strlen($invoice) > 1) { $collection->push($this->decodePrimaryKey($invoice)); + } } - } $this->assertEquals(0, $collection->count()); - } public function testCompareResultOfComparison() diff --git a/tests/Unit/CreditBalanceTest.php b/tests/Unit/CreditBalanceTest.php index 322ce031a311..68122c2739d0 100644 --- a/tests/Unit/CreditBalanceTest.php +++ b/tests/Unit/CreditBalanceTest.php @@ -11,12 +11,7 @@ namespace Tests\Unit; -use App\Models\Account; -use App\Models\Client; -use App\Models\Company; use App\Models\Credit; -use App\Models\CreditInvitation; -use App\Models\User; use App\Utils\Traits\AppSetup; use Tests\MockUnitData; use Tests\TestCase; @@ -86,7 +81,7 @@ class CreditBalanceTest extends TestCase $credit->push(); - //delete invoice + //delete invoice $data = [ 'ids' => [$credit->hashed_id], ]; @@ -101,7 +96,7 @@ class CreditBalanceTest extends TestCase $this->assertEquals(0, $client->credit_balance); - //restore invoice + //restore invoice $response = $this->withHeaders([ 'X-API-SECRET' => config('ninja.api_secret'), 'X-API-TOKEN' => $this->token, diff --git a/tests/Unit/DatesTest.php b/tests/Unit/DatesTest.php index 5045414bc450..0fbaf15987d1 100644 --- a/tests/Unit/DatesTest.php +++ b/tests/Unit/DatesTest.php @@ -11,7 +11,6 @@ namespace Tests\Unit; -use App\Helpers\Invoice\InvoiceSum; use Carbon\Carbon; use Illuminate\Foundation\Testing\DatabaseTransactions; use Tests\MockAccountData; diff --git a/tests/Unit/EntityTranslationTest.php b/tests/Unit/EntityTranslationTest.php index 4922b0e48d10..02942cea3456 100644 --- a/tests/Unit/EntityTranslationTest.php +++ b/tests/Unit/EntityTranslationTest.php @@ -175,7 +175,5 @@ class EntityTranslationTest extends TestCase $this->assertEquals(str_replace(" ", "_", ctrans('texts.invoice')) . "_xxx", $invoice->numberFormatter()); $this->assertEquals(str_replace(" ", "_", ctrans('texts.quote')) . "_xxx", $quote->numberFormatter()); $this->assertEquals(str_replace(" ", "_", ctrans('texts.purchase_order')) . "_xxx", $po->numberFormatter()); - - } } diff --git a/tests/Unit/GeneratesConvertedQuoteCounterTest.php b/tests/Unit/GeneratesConvertedQuoteCounterTest.php index 76470d1aa72c..488fa5aaad19 100644 --- a/tests/Unit/GeneratesConvertedQuoteCounterTest.php +++ b/tests/Unit/GeneratesConvertedQuoteCounterTest.php @@ -11,26 +11,18 @@ namespace Tests\Unit; -use App\DataMapper\ClientSettings; -use App\Factory\ClientFactory; -use App\Factory\QuoteFactory; -use App\Factory\VendorFactory; use App\Models\Account; use App\Models\Client; use App\Models\ClientContact; use App\Models\Company; -use App\Models\Credit; use App\Models\Invoice; use App\Models\Quote; -use App\Models\RecurringInvoice; -use App\Models\Timezone; use App\Models\User; use App\Utils\Traits\GeneratesConvertedQuoteCounter; use App\Utils\Traits\MakesHash; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\Session; -use Tests\MockAccountData; use Tests\TestCase; /** diff --git a/tests/Unit/GeneratesCounterTest.php b/tests/Unit/GeneratesCounterTest.php index 5d6f68c4776f..87f002bd2756 100644 --- a/tests/Unit/GeneratesCounterTest.php +++ b/tests/Unit/GeneratesCounterTest.php @@ -13,7 +13,6 @@ namespace Tests\Unit; use App\DataMapper\ClientSettings; use App\Factory\ClientFactory; -use App\Factory\QuoteFactory; use App\Factory\VendorFactory; use App\Models\Client; use App\Models\Company; diff --git a/tests/Unit/InvitationTest.php b/tests/Unit/InvitationTest.php index 08a84ee35ef0..8ed282052e20 100644 --- a/tests/Unit/InvitationTest.php +++ b/tests/Unit/InvitationTest.php @@ -12,7 +12,6 @@ namespace Tests\Unit; use App\Factory\InvoiceInvitationFactory; -use App\Models\CompanyToken; use App\Utils\Traits\MakesHash; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Routing\Middleware\ThrottleRequests; diff --git a/tests/Unit/InvoiceStatusTest.php b/tests/Unit/InvoiceStatusTest.php index 90d9000492fa..4f2e5835aa34 100644 --- a/tests/Unit/InvoiceStatusTest.php +++ b/tests/Unit/InvoiceStatusTest.php @@ -11,8 +11,6 @@ namespace Tests\Unit; -use App\Factory\InvoiceItemFactory; -use App\Helpers\Invoice\InvoiceSum; use App\Models\Invoice; use Illuminate\Foundation\Testing\DatabaseTransactions; use Tests\MockAccountData; diff --git a/tests/Unit/InvoiceTest.php b/tests/Unit/InvoiceTest.php index 0ed0ebb67085..a289f8f01356 100644 --- a/tests/Unit/InvoiceTest.php +++ b/tests/Unit/InvoiceTest.php @@ -80,7 +80,6 @@ class InvoiceTest extends TestCase // $this->invoice->save(); $this->assertEquals($invoice_calc->getTotalTaxes(), 15.96); - } private function buildLineItems() diff --git a/tests/Unit/LateFeeTest.php b/tests/Unit/LateFeeTest.php index 28ef22a50d4e..66acfdbe742a 100644 --- a/tests/Unit/LateFeeTest.php +++ b/tests/Unit/LateFeeTest.php @@ -34,7 +34,6 @@ class LateFeeTest extends TestCase public function testLateFeeBalances() { - $this->assertEquals(10, $this->client->balance); $this->assertEquals(10, $this->invoice->balance); @@ -42,12 +41,10 @@ class LateFeeTest extends TestCase $this->assertEquals(15, $this->client->fresh()->balance); $this->assertEquals(15, $this->invoice->fresh()->balance); - } private function setLateFee($invoice, $amount, $percent) :Invoice { - $temp_invoice_balance = $invoice->balance; if ($amount <= 0 && $percent <= 0) { @@ -82,5 +79,4 @@ class LateFeeTest extends TestCase return $invoice; } - } diff --git a/tests/Unit/NumberTest.php b/tests/Unit/NumberTest.php index f76e15685bec..8cd7f0ccaff4 100644 --- a/tests/Unit/NumberTest.php +++ b/tests/Unit/NumberTest.php @@ -11,7 +11,6 @@ namespace Tests\Unit; -use App\Models\Currency; use App\Utils\Number; use Tests\TestCase; @@ -21,7 +20,6 @@ use Tests\TestCase; */ class NumberTest extends TestCase { - public function testFloatPrecision() { $value = 1.1; @@ -97,5 +95,4 @@ class NumberTest extends TestCase $this->assertEquals(7.99, $converted_amount); } - } diff --git a/tests/Unit/PermissionsTest.php b/tests/Unit/PermissionsTest.php index 6638967a23ab..bf0386c2a301 100644 --- a/tests/Unit/PermissionsTest.php +++ b/tests/Unit/PermissionsTest.php @@ -20,8 +20,6 @@ use App\Models\CompanyUser; use App\Models\Invoice; use App\Models\RecurringInvoice; use App\Models\User; -use Illuminate\Foundation\Testing\DatabaseTransactions; -use Tests\MockAccountData; use Tests\TestCase; /** @@ -29,7 +27,6 @@ use Tests\TestCase; */ class PermissionsTest extends TestCase { - public User $user; public CompanyUser $cu; @@ -76,12 +73,10 @@ class PermissionsTest extends TestCase $company_token->token = $this->token; $company_token->is_system = true; $company_token->save(); - } public function testIntersectPermissions() { - $low_cu = CompanyUser::where(['company_id' => $this->company->id, 'user_id' => $this->user->id])->first(); $low_cu->permissions = '["view_client"]'; $low_cu->save(); @@ -110,12 +105,10 @@ class PermissionsTest extends TestCase $this->assertFalse($this->user->hasIntersectPermissions(["createbank_transaction"])); $this->assertTrue($this->user->hasIntersectPermissions(["create_bank_transaction"])); $this->assertTrue($this->user->hasIntersectPermissions(['create_bank_transaction','edit_bank_transaction','view_bank_transaction'])); - } public function testViewClientPermission() { - $low_cu = CompanyUser::where(['company_id' => $this->company->id, 'user_id' => $this->user->id])->first(); $low_cu->permissions = '["view_client"]'; $low_cu->save(); @@ -168,7 +161,6 @@ class PermissionsTest extends TestCase $low_cu->save(); $this->assertTrue($this->user->hasPermission('view_recurring_invoice')); - } public function testPermissionResolution() @@ -216,44 +208,36 @@ class PermissionsTest extends TestCase $this->assertEquals('invoice', \Illuminate\Support\Str::snake(class_basename(Invoice::class))); $this->assertEquals('recurring_invoice', \Illuminate\Support\Str::snake(class_basename(RecurringInvoice::class))); - } public function testExactPermissions() { - $this->assertTrue($this->user->hasExactPermission("view_client")); $this->assertFalse($this->user->hasExactPermission("view_all")); - } public function testMissingPermissions() { - $low_cu = CompanyUser::where(['company_id' => $this->company->id, 'user_id' => $this->user->id])->first(); $low_cu->permissions = '[""]'; $low_cu->save(); $this->assertFalse($this->user->hasExactPermission("view_client")); $this->assertFalse($this->user->hasExactPermission("view_all")); - } public function testViewAllValidPermissions() { - $low_cu = CompanyUser::where(['company_id' => $this->company->id, 'user_id' => $this->user->id])->first(); $low_cu->permissions = '["view_all"]'; $low_cu->save(); $this->assertTrue($this->user->hasExactPermission("view_client")); $this->assertTrue($this->user->hasExactPermission("view_all")); - } public function testReturnTypesOfStripos() { - $this->assertEquals(0, stripos("view_client", '')); $all_permission = '[]'; @@ -268,11 +252,11 @@ class PermissionsTest extends TestCase $all_permission = "";//problems are empty strings $this->assertTrue(empty($all_permission)); - $this->assertFalse( stripos($all_permission, "view_client") !== false); - $this->assertFalse( is_int(stripos($all_permission, "view_client"))); + $this->assertFalse(stripos($all_permission, "view_client") !== false); + $this->assertFalse(is_int(stripos($all_permission, "view_client"))); $all_permission = 'view';//will always pass currently - $this->assertFalse( stripos($all_permission, "view_client") !== false); + $this->assertFalse(stripos($all_permission, "view_client") !== false); $this->assertFalse(is_int(stripos($all_permission, "view_client"))); $all_permission = "view_client"; @@ -280,11 +264,5 @@ class PermissionsTest extends TestCase $this->assertTrue(is_int(stripos($all_permission, "view_client")) !== false); $this->assertTrue(is_int(stripos($all_permission, "view_client"))); - - } - - - } - diff --git a/tests/Unit/RangeDetectionTest.php b/tests/Unit/RangeDetectionTest.php index afb9e9c211d9..9aed0da124be 100644 --- a/tests/Unit/RangeDetectionTest.php +++ b/tests/Unit/RangeDetectionTest.php @@ -11,7 +11,6 @@ namespace Tests\Unit; -use Illuminate\Foundation\Testing\DatabaseTransactions; use Tests\TestCase; /** diff --git a/tests/Unit/RecurringDateTest.php b/tests/Unit/RecurringDateTest.php index e8224badb29d..4321031b290f 100644 --- a/tests/Unit/RecurringDateTest.php +++ b/tests/Unit/RecurringDateTest.php @@ -11,7 +11,6 @@ namespace Tests\Unit; -use App\Models\Invoice; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Carbon; use Tests\MockAccountData; @@ -42,5 +41,4 @@ class RecurringDateTest extends TestCase $this->assertequals($trial_ends->format('Y-m-d'), '2021-12-03'); } - } diff --git a/tests/Unit/RecurringExpenseCloneTest.php b/tests/Unit/RecurringExpenseCloneTest.php index 6fc877068ad5..9a20f5c8968c 100644 --- a/tests/Unit/RecurringExpenseCloneTest.php +++ b/tests/Unit/RecurringExpenseCloneTest.php @@ -16,9 +16,7 @@ use App\Factory\RecurringExpenseToExpenseFactory; use App\Models\Account; use App\Models\Client; use App\Models\Company; -use App\Models\RecurringExpense; use App\Models\User; -use App\Utils\Ninja; use Tests\TestCase; /** diff --git a/tests/Unit/RedisVsDatabaseTest.php b/tests/Unit/RedisVsDatabaseTest.php index d53a479d268d..e2b0af1b7015 100644 --- a/tests/Unit/RedisVsDatabaseTest.php +++ b/tests/Unit/RedisVsDatabaseTest.php @@ -12,10 +12,7 @@ namespace Tests\Unit; use App\Models\Currency; -use App\Models\Invoice; -use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\Cache; -use Tests\MockAccountData; use Tests\TestCase; /** diff --git a/tests/Unit/RefundUnitTest.php b/tests/Unit/RefundUnitTest.php index c2a375543124..067eeca9ae77 100644 --- a/tests/Unit/RefundUnitTest.php +++ b/tests/Unit/RefundUnitTest.php @@ -13,7 +13,6 @@ namespace Tests\Unit; use App\Helpers\Invoice\ProRata; use App\Models\RecurringInvoice; -use App\Utils\Ninja; use Illuminate\Support\Carbon; use Tests\TestCase; diff --git a/tests/Unit/RelationExistsTest.php b/tests/Unit/RelationExistsTest.php index 047dc5ec8ce0..dc4ad73189b5 100644 --- a/tests/Unit/RelationExistsTest.php +++ b/tests/Unit/RelationExistsTest.php @@ -11,7 +11,6 @@ namespace Tests\Unit; -use App\Factory\CloneQuoteToInvoiceFactory; use App\Models\Client; use App\Models\Credit; use App\Models\Expense; diff --git a/tests/Unit/S3CleanupTest.php b/tests/Unit/S3CleanupTest.php index c49ed358a184..ba90d1fe89b8 100644 --- a/tests/Unit/S3CleanupTest.php +++ b/tests/Unit/S3CleanupTest.php @@ -11,7 +11,6 @@ namespace Tests\Unit; -use App\DataMapper\ClientSettings; use Tests\TestCase; /** diff --git a/tests/Unit/SettingsSaverTest.php b/tests/Unit/SettingsSaverTest.php index 051bb415ebf5..888972358b55 100644 --- a/tests/Unit/SettingsSaverTest.php +++ b/tests/Unit/SettingsSaverTest.php @@ -11,7 +11,6 @@ namespace Tests\Unit; -use App\DataMapper\CompanySettings; use App\Utils\Traits\SettingsSaver; use Tests\TestCase; diff --git a/tests/Unit/SubscriptionsCalcTest.php b/tests/Unit/SubscriptionsCalcTest.php index a944507c3a32..2e8684743c9e 100644 --- a/tests/Unit/SubscriptionsCalcTest.php +++ b/tests/Unit/SubscriptionsCalcTest.php @@ -105,7 +105,6 @@ class SubscriptionsCalcTest extends TestCase public function testProrataDiscountRatioPercentage() { - $subscription = Subscription::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -157,12 +156,10 @@ class SubscriptionsCalcTest extends TestCase $ratio = $subscription->service()->calculateDiscountRatio($invoice); $this->assertEquals(.1, $ratio); - } public function testProrataDiscountRatioAmount() { - $subscription = Subscription::factory()->create([ 'company_id' => $this->company->id, 'user_id' => $this->user->id, @@ -214,9 +211,5 @@ class SubscriptionsCalcTest extends TestCase $ratio = $subscription->service()->calculateDiscountRatio($invoice); $this->assertEquals(.2, $ratio); - } - - - } diff --git a/tests/Unit/ValidationRules/BlacklistValidationTest.php b/tests/Unit/ValidationRules/BlacklistValidationTest.php index 68a1ba915b15..1a6b54a41435 100644 --- a/tests/Unit/ValidationRules/BlacklistValidationTest.php +++ b/tests/Unit/ValidationRules/BlacklistValidationTest.php @@ -12,9 +12,6 @@ namespace Tests\Unit\ValidationRules; use App\Http\ValidationRules\Account\BlackListRule; -use App\Models\Invoice; -use Illuminate\Foundation\Testing\DatabaseTransactions; -use Tests\MockAccountData; use Tests\TestCase; /** diff --git a/tests/Unit/ValidationRules/EmailBlacklistValidationTest.php b/tests/Unit/ValidationRules/EmailBlacklistValidationTest.php index 57504cc7c107..16aff0d75c31 100644 --- a/tests/Unit/ValidationRules/EmailBlacklistValidationTest.php +++ b/tests/Unit/ValidationRules/EmailBlacklistValidationTest.php @@ -11,11 +11,7 @@ namespace Tests\Unit\ValidationRules; -use App\Http\ValidationRules\Account\BlackListRule; use App\Http\ValidationRules\Account\EmailBlackListRule; -use App\Models\Invoice; -use Illuminate\Foundation\Testing\DatabaseTransactions; -use Tests\MockAccountData; use Tests\TestCase; /** diff --git a/tests/Unit/ValidationRules/UniqueInvoiceNumberValidationTest.php b/tests/Unit/ValidationRules/UniqueInvoiceNumberValidationTest.php index 79782df52c6a..923b092a4c19 100644 --- a/tests/Unit/ValidationRules/UniqueInvoiceNumberValidationTest.php +++ b/tests/Unit/ValidationRules/UniqueInvoiceNumberValidationTest.php @@ -12,10 +12,8 @@ namespace Tests\Unit\ValidationRules; use App\Http\Requests\Invoice\StoreInvoiceRequest; -use App\Http\ValidationRules\Account\BlackListRule; use App\Models\Invoice; use App\Utils\Traits\MakesHash; -use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Support\Facades\Validator; use Tests\MockAccountData; use Tests\TestCase; diff --git a/tests/Unit/ZeroDecimalTest.php b/tests/Unit/ZeroDecimalTest.php index 4efc7864a74f..7327c95214e1 100644 --- a/tests/Unit/ZeroDecimalTest.php +++ b/tests/Unit/ZeroDecimalTest.php @@ -11,13 +11,6 @@ namespace Tests\Unit; -use App\Jobs\Util\UploadFile; -use App\Models\Document; -use Illuminate\Foundation\Testing\DatabaseTransactions; -use Illuminate\Http\UploadedFile; -use Illuminate\Routing\Middleware\ThrottleRequests; -use Illuminate\Support\Facades\Storage; -use Tests\MockAccountData; use Tests\TestCase; class ZeroDecimalTest extends TestCase From 0bc3f6dadb9cd658ac9e26d3994f677a2f4e8329 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 13:10:05 +1100 Subject: [PATCH 36/72] Update for dev dependencie --- composer.json | 1 + composer.lock | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index ca7e50171d8c..afac04841082 100644 --- a/composer.json +++ b/composer.json @@ -106,6 +106,7 @@ "laravel/dusk": "^6.15", "mockery/mockery": "^1.4.4", "nunomaduro/collision": "^6.1", + "phpstan/phpstan": "^1.9", "phpunit/phpunit": "^9.5.10", "spatie/laravel-ignition": "^1.0", "vimeo/psalm": "^4.24" diff --git a/composer.lock b/composer.lock index 399e21c705f2..084682de16b5 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "dfdb363c199d15bed79f289c88ddd67e", + "content-hash": "ef4a5ce05df08ab130a9906db0e69ead", "packages": [ { "name": "afosto/yaac", @@ -14865,6 +14865,65 @@ }, "time": "2022-10-14T12:47:21+00:00" }, + { + "name": "phpstan/phpstan", + "version": "1.9.17", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan.git", + "reference": "204e459e7822f2c586463029f5ecec31bb45a1f2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/204e459e7822f2c586463029f5ecec31bb45a1f2", + "reference": "204e459e7822f2c586463029f5ecec31bb45a1f2", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "keywords": [ + "dev", + "static analysis" + ], + "support": { + "issues": "https://github.com/phpstan/phpstan/issues", + "source": "https://github.com/phpstan/phpstan/tree/1.9.17" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpstan/phpstan", + "type": "tidelift" + } + ], + "time": "2023-02-08T12:25:00+00:00" + }, { "name": "phpunit/php-code-coverage", "version": "9.2.24", From cf1ce9ebd53a242ec23fb9b8953769ce09dfc6ab Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 13:18:12 +1100 Subject: [PATCH 37/72] Updates for .gitignore --- .gitignore | 2 ++ phpstan.neon | 5 +++++ 2 files changed, 7 insertions(+) create mode 100644 phpstan.neon diff --git a/.gitignore b/.gitignore index ae7c715fb449..a860fb777bdf 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,9 @@ /storage/*.key /storage/debugbar /storage/* +/tests/bootstrap/ /vendor +/app/Console/Commands/vendor/ /.idea /.vscode /.vagrant diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 000000000000..6f69d51b9a6b --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,5 @@ +parameters: + level: 6 + paths: + - app + - tests From 4d6cf43a1ec278adae4af764ed21bb18a57dd9ff Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 13:36:49 +1100 Subject: [PATCH 38/72] ide helpers --- _ide_helper.php | 28081 +++++++++++++++++++++++++ _ide_helper_custom.php | 17 + app/Providers/AppServiceProvider.php | 2 +- app/Services/Email/MailEntity.php | 19 +- composer.json | 1 + composer.lock | 221 +- 6 files changed, 28336 insertions(+), 5 deletions(-) create mode 100644 _ide_helper.php create mode 100644 _ide_helper_custom.php diff --git a/_ide_helper.php b/_ide_helper.php new file mode 100644 index 000000000000..c5562d34111d --- /dev/null +++ b/_ide_helper.php @@ -0,0 +1,28081 @@ + + * @see https://github.com/barryvdh/laravel-ide-helper + */ + + namespace Illuminate\Support\Facades { + /** + * + * + * @see \Illuminate\Foundation\Application + */ + class App { + /** + * Get the version number of the application. + * + * @return string + * @static + */ + public static function version() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->version(); + } + /** + * Run the given array of bootstrap classes. + * + * @param string[] $bootstrappers + * @return void + * @static + */ + public static function bootstrapWith($bootstrappers) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->bootstrapWith($bootstrappers); + } + /** + * Register a callback to run after loading the environment. + * + * @param \Closure $callback + * @return void + * @static + */ + public static function afterLoadingEnvironment($callback) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->afterLoadingEnvironment($callback); + } + /** + * Register a callback to run before a bootstrapper. + * + * @param string $bootstrapper + * @param \Closure $callback + * @return void + * @static + */ + public static function beforeBootstrapping($bootstrapper, $callback) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->beforeBootstrapping($bootstrapper, $callback); + } + /** + * Register a callback to run after a bootstrapper. + * + * @param string $bootstrapper + * @param \Closure $callback + * @return void + * @static + */ + public static function afterBootstrapping($bootstrapper, $callback) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->afterBootstrapping($bootstrapper, $callback); + } + /** + * Determine if the application has been bootstrapped before. + * + * @return bool + * @static + */ + public static function hasBeenBootstrapped() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->hasBeenBootstrapped(); + } + /** + * Set the base path for the application. + * + * @param string $basePath + * @return \Illuminate\Foundation\Application + * @static + */ + public static function setBasePath($basePath) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->setBasePath($basePath); + } + /** + * Get the path to the application "app" directory. + * + * @param string $path + * @return string + * @static + */ + public static function path($path = '') + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->path($path); + } + /** + * Set the application directory. + * + * @param string $path + * @return \Illuminate\Foundation\Application + * @static + */ + public static function useAppPath($path) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->useAppPath($path); + } + /** + * Get the base path of the Laravel installation. + * + * @param string $path + * @return string + * @static + */ + public static function basePath($path = '') + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->basePath($path); + } + /** + * Get the path to the bootstrap directory. + * + * @param string $path + * @return string + * @static + */ + public static function bootstrapPath($path = '') + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->bootstrapPath($path); + } + /** + * Get the path to the application configuration files. + * + * @param string $path + * @return string + * @static + */ + public static function configPath($path = '') + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->configPath($path); + } + /** + * Get the path to the database directory. + * + * @param string $path + * @return string + * @static + */ + public static function databasePath($path = '') + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->databasePath($path); + } + /** + * Set the database directory. + * + * @param string $path + * @return \Illuminate\Foundation\Application + * @static + */ + public static function useDatabasePath($path) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->useDatabasePath($path); + } + /** + * Get the path to the language files. + * + * @param string $path + * @return string + * @static + */ + public static function langPath($path = '') + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->langPath($path); + } + /** + * Set the language file directory. + * + * @param string $path + * @return \Illuminate\Foundation\Application + * @static + */ + public static function useLangPath($path) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->useLangPath($path); + } + /** + * Get the path to the public / web directory. + * + * @return string + * @static + */ + public static function publicPath() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->publicPath(); + } + /** + * Get the path to the storage directory. + * + * @param string $path + * @return string + * @static + */ + public static function storagePath($path = '') + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->storagePath($path); + } + /** + * Set the storage directory. + * + * @param string $path + * @return \Illuminate\Foundation\Application + * @static + */ + public static function useStoragePath($path) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->useStoragePath($path); + } + /** + * Get the path to the resources directory. + * + * @param string $path + * @return string + * @static + */ + public static function resourcePath($path = '') + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->resourcePath($path); + } + /** + * Get the path to the views directory. + * + * This method returns the first configured path in the array of view paths. + * + * @param string $path + * @return string + * @static + */ + public static function viewPath($path = '') + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->viewPath($path); + } + /** + * Get the path to the environment file directory. + * + * @return string + * @static + */ + public static function environmentPath() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->environmentPath(); + } + /** + * Set the directory for the environment file. + * + * @param string $path + * @return \Illuminate\Foundation\Application + * @static + */ + public static function useEnvironmentPath($path) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->useEnvironmentPath($path); + } + /** + * Set the environment file to be loaded during bootstrapping. + * + * @param string $file + * @return \Illuminate\Foundation\Application + * @static + */ + public static function loadEnvironmentFrom($file) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->loadEnvironmentFrom($file); + } + /** + * Get the environment file the application is using. + * + * @return string + * @static + */ + public static function environmentFile() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->environmentFile(); + } + /** + * Get the fully qualified path to the environment file. + * + * @return string + * @static + */ + public static function environmentFilePath() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->environmentFilePath(); + } + /** + * Get or check the current application environment. + * + * @param string|array $environments + * @return string|bool + * @static + */ + public static function environment(...$environments) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->environment(...$environments); + } + /** + * Determine if the application is in the local environment. + * + * @return bool + * @static + */ + public static function isLocal() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->isLocal(); + } + /** + * Determine if the application is in the production environment. + * + * @return bool + * @static + */ + public static function isProduction() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->isProduction(); + } + /** + * Detect the application's current environment. + * + * @param \Closure $callback + * @return string + * @static + */ + public static function detectEnvironment($callback) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->detectEnvironment($callback); + } + /** + * Determine if the application is running in the console. + * + * @return bool + * @static + */ + public static function runningInConsole() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->runningInConsole(); + } + /** + * Determine if the application is running unit tests. + * + * @return bool + * @static + */ + public static function runningUnitTests() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->runningUnitTests(); + } + /** + * Determine if the application is running with debug mode enabled. + * + * @return bool + * @static + */ + public static function hasDebugModeEnabled() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->hasDebugModeEnabled(); + } + /** + * Register all of the configured providers. + * + * @return void + * @static + */ + public static function registerConfiguredProviders() + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->registerConfiguredProviders(); + } + /** + * Register a service provider with the application. + * + * @param \Illuminate\Support\ServiceProvider|string $provider + * @param bool $force + * @return \Illuminate\Support\ServiceProvider + * @static + */ + public static function register($provider, $force = false) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->register($provider, $force); + } + /** + * Get the registered service provider instance if it exists. + * + * @param \Illuminate\Support\ServiceProvider|string $provider + * @return \Illuminate\Support\ServiceProvider|null + * @static + */ + public static function getProvider($provider) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getProvider($provider); + } + /** + * Get the registered service provider instances if any exist. + * + * @param \Illuminate\Support\ServiceProvider|string $provider + * @return array + * @static + */ + public static function getProviders($provider) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getProviders($provider); + } + /** + * Resolve a service provider instance from the class name. + * + * @param string $provider + * @return \Illuminate\Support\ServiceProvider + * @static + */ + public static function resolveProvider($provider) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->resolveProvider($provider); + } + /** + * Load and boot all of the remaining deferred providers. + * + * @return void + * @static + */ + public static function loadDeferredProviders() + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->loadDeferredProviders(); + } + /** + * Load the provider for a deferred service. + * + * @param string $service + * @return void + * @static + */ + public static function loadDeferredProvider($service) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->loadDeferredProvider($service); + } + /** + * Register a deferred provider and service. + * + * @param string $provider + * @param string|null $service + * @return void + * @static + */ + public static function registerDeferredProvider($provider, $service = null) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->registerDeferredProvider($provider, $service); + } + /** + * Resolve the given type from the container. + * + * @param string $abstract + * @param array $parameters + * @return mixed + * @static + */ + public static function make($abstract, $parameters = []) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->make($abstract, $parameters); + } + /** + * Determine if the given abstract type has been bound. + * + * @param string $abstract + * @return bool + * @static + */ + public static function bound($abstract) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->bound($abstract); + } + /** + * Determine if the application has booted. + * + * @return bool + * @static + */ + public static function isBooted() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->isBooted(); + } + /** + * Boot the application's service providers. + * + * @return void + * @static + */ + public static function boot() + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->boot(); + } + /** + * Register a new boot listener. + * + * @param callable $callback + * @return void + * @static + */ + public static function booting($callback) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->booting($callback); + } + /** + * Register a new "booted" listener. + * + * @param callable $callback + * @return void + * @static + */ + public static function booted($callback) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->booted($callback); + } + /** + * {@inheritdoc} + * + * @return \Symfony\Component\HttpFoundation\Response + * @static + */ + public static function handle($request, $type = 1, $catch = true) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->handle($request, $type, $catch); + } + /** + * Determine if middleware has been disabled for the application. + * + * @return bool + * @static + */ + public static function shouldSkipMiddleware() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->shouldSkipMiddleware(); + } + /** + * Get the path to the cached services.php file. + * + * @return string + * @static + */ + public static function getCachedServicesPath() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getCachedServicesPath(); + } + /** + * Get the path to the cached packages.php file. + * + * @return string + * @static + */ + public static function getCachedPackagesPath() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getCachedPackagesPath(); + } + /** + * Determine if the application configuration is cached. + * + * @return bool + * @static + */ + public static function configurationIsCached() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->configurationIsCached(); + } + /** + * Get the path to the configuration cache file. + * + * @return string + * @static + */ + public static function getCachedConfigPath() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getCachedConfigPath(); + } + /** + * Determine if the application routes are cached. + * + * @return bool + * @static + */ + public static function routesAreCached() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->routesAreCached(); + } + /** + * Get the path to the routes cache file. + * + * @return string + * @static + */ + public static function getCachedRoutesPath() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getCachedRoutesPath(); + } + /** + * Determine if the application events are cached. + * + * @return bool + * @static + */ + public static function eventsAreCached() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->eventsAreCached(); + } + /** + * Get the path to the events cache file. + * + * @return string + * @static + */ + public static function getCachedEventsPath() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getCachedEventsPath(); + } + /** + * Add new prefix to list of absolute path prefixes. + * + * @param string $prefix + * @return \Illuminate\Foundation\Application + * @static + */ + public static function addAbsoluteCachePathPrefix($prefix) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->addAbsoluteCachePathPrefix($prefix); + } + /** + * Get an instance of the maintenance mode manager implementation. + * + * @return \Illuminate\Contracts\Foundation\MaintenanceMode + * @static + */ + public static function maintenanceMode() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->maintenanceMode(); + } + /** + * Determine if the application is currently down for maintenance. + * + * @return bool + * @static + */ + public static function isDownForMaintenance() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->isDownForMaintenance(); + } + /** + * Throw an HttpException with the given data. + * + * @param int $code + * @param string $message + * @param array $headers + * @return \Illuminate\Foundation\never + * @throws \Symfony\Component\HttpKernel\Exception\HttpException + * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException + * @static + */ + public static function abort($code, $message = '', $headers = []) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->abort($code, $message, $headers); + } + /** + * Register a terminating callback with the application. + * + * @param callable|string $callback + * @return \Illuminate\Foundation\Application + * @static + */ + public static function terminating($callback) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->terminating($callback); + } + /** + * Terminate the application. + * + * @return void + * @static + */ + public static function terminate() + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->terminate(); + } + /** + * Get the service providers that have been loaded. + * + * @return array + * @static + */ + public static function getLoadedProviders() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getLoadedProviders(); + } + /** + * Determine if the given service provider is loaded. + * + * @param string $provider + * @return bool + * @static + */ + public static function providerIsLoaded($provider) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->providerIsLoaded($provider); + } + /** + * Get the application's deferred services. + * + * @return array + * @static + */ + public static function getDeferredServices() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getDeferredServices(); + } + /** + * Set the application's deferred services. + * + * @param array $services + * @return void + * @static + */ + public static function setDeferredServices($services) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->setDeferredServices($services); + } + /** + * Add an array of services to the application's deferred services. + * + * @param array $services + * @return void + * @static + */ + public static function addDeferredServices($services) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->addDeferredServices($services); + } + /** + * Determine if the given service is a deferred service. + * + * @param string $service + * @return bool + * @static + */ + public static function isDeferredService($service) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->isDeferredService($service); + } + /** + * Configure the real-time facade namespace. + * + * @param string $namespace + * @return void + * @static + */ + public static function provideFacades($namespace) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->provideFacades($namespace); + } + /** + * Get the current application locale. + * + * @return string + * @static + */ + public static function getLocale() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getLocale(); + } + /** + * Get the current application locale. + * + * @return string + * @static + */ + public static function currentLocale() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->currentLocale(); + } + /** + * Get the current application fallback locale. + * + * @return string + * @static + */ + public static function getFallbackLocale() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getFallbackLocale(); + } + /** + * Set the current application locale. + * + * @param string $locale + * @return void + * @static + */ + public static function setLocale($locale) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->setLocale($locale); + } + /** + * Set the current application fallback locale. + * + * @param string $fallbackLocale + * @return void + * @static + */ + public static function setFallbackLocale($fallbackLocale) + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->setFallbackLocale($fallbackLocale); + } + /** + * Determine if the application locale is the given locale. + * + * @param string $locale + * @return bool + * @static + */ + public static function isLocale($locale) + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->isLocale($locale); + } + /** + * Register the core class aliases in the container. + * + * @return void + * @static + */ + public static function registerCoreContainerAliases() + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->registerCoreContainerAliases(); + } + /** + * Flush the container of all bindings and resolved instances. + * + * @return void + * @static + */ + public static function flush() + { + /** @var \Illuminate\Foundation\Application $instance */ + $instance->flush(); + } + /** + * Get the application namespace. + * + * @return string + * @throws \RuntimeException + * @static + */ + public static function getNamespace() + { + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getNamespace(); + } + /** + * Define a contextual binding. + * + * @param array|string $concrete + * @return \Illuminate\Contracts\Container\ContextualBindingBuilder + * @static + */ + public static function when($concrete) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->when($concrete); + } + /** + * Returns true if the container can return an entry for the given identifier. + * + * Returns false otherwise. + * + * `has($id)` returning true does not mean that `get($id)` will not throw an exception. + * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`. + * + * @return bool + * @param string $id Identifier of the entry to look for. + * @return bool + * @static + */ + public static function has($id) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->has($id); + } + /** + * Determine if the given abstract type has been resolved. + * + * @param string $abstract + * @return bool + * @static + */ + public static function resolved($abstract) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->resolved($abstract); + } + /** + * Determine if a given type is shared. + * + * @param string $abstract + * @return bool + * @static + */ + public static function isShared($abstract) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->isShared($abstract); + } + /** + * Determine if a given string is an alias. + * + * @param string $name + * @return bool + * @static + */ + public static function isAlias($name) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->isAlias($name); + } + /** + * Register a binding with the container. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @param bool $shared + * @return void + * @throws \TypeError + * @static + */ + public static function bind($abstract, $concrete = null, $shared = false) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->bind($abstract, $concrete, $shared); + } + /** + * Determine if the container has a method binding. + * + * @param string $method + * @return bool + * @static + */ + public static function hasMethodBinding($method) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->hasMethodBinding($method); + } + /** + * Bind a callback to resolve with Container::call. + * + * @param array|string $method + * @param \Closure $callback + * @return void + * @static + */ + public static function bindMethod($method, $callback) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->bindMethod($method, $callback); + } + /** + * Get the method binding for the given method. + * + * @param string $method + * @param mixed $instance + * @return mixed + * @static + */ + public static function callMethodBinding($method, $instance) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->callMethodBinding($method, $instance); + } + /** + * Add a contextual binding to the container. + * + * @param string $concrete + * @param string $abstract + * @param \Closure|string $implementation + * @return void + * @static + */ + public static function addContextualBinding($concrete, $abstract, $implementation) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->addContextualBinding($concrete, $abstract, $implementation); + } + /** + * Register a binding if it hasn't already been registered. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @param bool $shared + * @return void + * @static + */ + public static function bindIf($abstract, $concrete = null, $shared = false) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->bindIf($abstract, $concrete, $shared); + } + /** + * Register a shared binding in the container. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + * @static + */ + public static function singleton($abstract, $concrete = null) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->singleton($abstract, $concrete); + } + /** + * Register a shared binding if it hasn't already been registered. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + * @static + */ + public static function singletonIf($abstract, $concrete = null) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->singletonIf($abstract, $concrete); + } + /** + * Register a scoped binding in the container. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + * @static + */ + public static function scoped($abstract, $concrete = null) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->scoped($abstract, $concrete); + } + /** + * Register a scoped binding if it hasn't already been registered. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + * @static + */ + public static function scopedIf($abstract, $concrete = null) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->scopedIf($abstract, $concrete); + } + /** + * "Extend" an abstract type in the container. + * + * @param string $abstract + * @param \Closure $closure + * @return void + * @throws \InvalidArgumentException + * @static + */ + public static function extend($abstract, $closure) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->extend($abstract, $closure); + } + /** + * Register an existing instance as shared in the container. + * + * @param string $abstract + * @param mixed $instance + * @return mixed + * @static + */ + public static function instance($abstract, $instance) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->instance($abstract, $instance); + } + /** + * Assign a set of tags to a given binding. + * + * @param array|string $abstracts + * @param array|mixed $tags + * @return void + * @static + */ + public static function tag($abstracts, $tags) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->tag($abstracts, $tags); + } + /** + * Resolve all of the bindings for a given tag. + * + * @param string $tag + * @return \Illuminate\Container\iterable + * @static + */ + public static function tagged($tag) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->tagged($tag); + } + /** + * Alias a type to a different name. + * + * @param string $abstract + * @param string $alias + * @return void + * @throws \LogicException + * @static + */ + public static function alias($abstract, $alias) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->alias($abstract, $alias); + } + /** + * Bind a new callback to an abstract's rebind event. + * + * @param string $abstract + * @param \Closure $callback + * @return mixed + * @static + */ + public static function rebinding($abstract, $callback) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->rebinding($abstract, $callback); + } + /** + * Refresh an instance on the given target and method. + * + * @param string $abstract + * @param mixed $target + * @param string $method + * @return mixed + * @static + */ + public static function refresh($abstract, $target, $method) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->refresh($abstract, $target, $method); + } + /** + * Wrap the given closure such that its dependencies will be injected when executed. + * + * @param \Closure $callback + * @param array $parameters + * @return \Closure + * @static + */ + public static function wrap($callback, $parameters = []) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->wrap($callback, $parameters); + } + /** + * Call the given Closure / class@method and inject its dependencies. + * + * @param callable|string $callback + * @param \Illuminate\Container\array $parameters + * @param string|null $defaultMethod + * @return mixed + * @throws \InvalidArgumentException + * @static + */ + public static function call($callback, $parameters = [], $defaultMethod = null) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->call($callback, $parameters, $defaultMethod); + } + /** + * Get a closure to resolve the given type from the container. + * + * @param string $abstract + * @return \Closure + * @static + */ + public static function factory($abstract) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->factory($abstract); + } + /** + * An alias function name for make(). + * + * @param string|callable $abstract + * @param array $parameters + * @return mixed + * @throws \Illuminate\Contracts\Container\BindingResolutionException + * @static + */ + public static function makeWith($abstract, $parameters = []) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->makeWith($abstract, $parameters); + } + /** + * Finds an entry of the container by its identifier and returns it. + * + * @return mixed + * @param string $id Identifier of the entry to look for. + * @throws NotFoundExceptionInterface No entry was found for **this** identifier. + * @throws ContainerExceptionInterface Error while retrieving the entry. + * @return mixed Entry. + * @static + */ + public static function get($id) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->get($id); + } + /** + * Instantiate a concrete instance of the given type. + * + * @param \Closure|string $concrete + * @return mixed + * @throws \Illuminate\Contracts\Container\BindingResolutionException + * @throws \Illuminate\Contracts\Container\CircularDependencyException + * @static + */ + public static function build($concrete) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->build($concrete); + } + /** + * Register a new before resolving callback for all types. + * + * @param \Closure|string $abstract + * @param \Closure|null $callback + * @return void + * @static + */ + public static function beforeResolving($abstract, $callback = null) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->beforeResolving($abstract, $callback); + } + /** + * Register a new resolving callback. + * + * @param \Closure|string $abstract + * @param \Closure|null $callback + * @return void + * @static + */ + public static function resolving($abstract, $callback = null) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->resolving($abstract, $callback); + } + /** + * Register a new after resolving callback for all types. + * + * @param \Closure|string $abstract + * @param \Closure|null $callback + * @return void + * @static + */ + public static function afterResolving($abstract, $callback = null) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->afterResolving($abstract, $callback); + } + /** + * Get the container's bindings. + * + * @return array + * @static + */ + public static function getBindings() + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getBindings(); + } + /** + * Get the alias for an abstract if available. + * + * @param string $abstract + * @return string + * @static + */ + public static function getAlias($abstract) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->getAlias($abstract); + } + /** + * Remove all of the extender callbacks for a given type. + * + * @param string $abstract + * @return void + * @static + */ + public static function forgetExtenders($abstract) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->forgetExtenders($abstract); + } + /** + * Remove a resolved instance from the instance cache. + * + * @param string $abstract + * @return void + * @static + */ + public static function forgetInstance($abstract) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->forgetInstance($abstract); + } + /** + * Clear all of the instances from the container. + * + * @return void + * @static + */ + public static function forgetInstances() + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->forgetInstances(); + } + /** + * Clear all of the scoped instances from the container. + * + * @return void + * @static + */ + public static function forgetScopedInstances() + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->forgetScopedInstances(); + } + /** + * Get the globally available instance of the container. + * + * @return static + * @static + */ + public static function getInstance() + { //Method inherited from \Illuminate\Container\Container + return \Illuminate\Foundation\Application::getInstance(); + } + /** + * Set the shared instance of the container. + * + * @param \Illuminate\Contracts\Container\Container|null $container + * @return \Illuminate\Contracts\Container\Container|static + * @static + */ + public static function setInstance($container = null) + { //Method inherited from \Illuminate\Container\Container + return \Illuminate\Foundation\Application::setInstance($container); + } + /** + * Determine if a given offset exists. + * + * @param string $key + * @return bool + * @static + */ + public static function offsetExists($key) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->offsetExists($key); + } + /** + * Get the value at a given offset. + * + * @param string $key + * @return mixed + * @static + */ + public static function offsetGet($key) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + return $instance->offsetGet($key); + } + /** + * Set the value at a given offset. + * + * @param string $key + * @param mixed $value + * @return void + * @static + */ + public static function offsetSet($key, $value) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->offsetSet($key, $value); + } + /** + * Unset the value at a given offset. + * + * @param string $key + * @return void + * @static + */ + public static function offsetUnset($key) + { //Method inherited from \Illuminate\Container\Container + /** @var \Illuminate\Foundation\Application $instance */ + $instance->offsetUnset($key); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Foundation\Application::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Foundation\Application::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Foundation\Application::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Foundation\Application::flushMacros(); + } + + } + /** + * + * + * @see \Illuminate\Foundation\Console\Kernel + */ + class Artisan { + /** + * Run the console application. + * + * @param \Symfony\Component\Console\Input\InputInterface $input + * @param \Symfony\Component\Console\Output\OutputInterface|null $output + * @return int + * @static + */ + public static function handle($input, $output = null) + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + return $instance->handle($input, $output); + } + /** + * Terminate the application. + * + * @param \Symfony\Component\Console\Input\InputInterface $input + * @param int $status + * @return void + * @static + */ + public static function terminate($input, $status) + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + $instance->terminate($input, $status); + } + /** + * Register a callback to be invoked when the command lifecycle duration exceeds a given amount of time. + * + * @param \DateTimeInterface|\Carbon\CarbonInterval|float|int $threshold + * @param callable $handler + * @return void + * @static + */ + public static function whenCommandLifecycleIsLongerThan($threshold, $handler) + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + $instance->whenCommandLifecycleIsLongerThan($threshold, $handler); + } + /** + * When the command being handled started. + * + * @return \Illuminate\Support\Carbon|null + * @static + */ + public static function commandStartedAt() + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + return $instance->commandStartedAt(); + } + /** + * Register a Closure based command with the application. + * + * @param string $signature + * @param \Closure $callback + * @return \Illuminate\Foundation\Console\ClosureCommand + * @static + */ + public static function command($signature, $callback) + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + return $instance->command($signature, $callback); + } + /** + * Register the given command with the console application. + * + * @param \Symfony\Component\Console\Command\Command $command + * @return void + * @static + */ + public static function registerCommand($command) + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + $instance->registerCommand($command); + } + /** + * Run an Artisan console command by name. + * + * @param string $command + * @param array $parameters + * @param \Symfony\Component\Console\Output\OutputInterface|null $outputBuffer + * @return int + * @throws \Symfony\Component\Console\Exception\CommandNotFoundException + * @static + */ + public static function call($command, $parameters = [], $outputBuffer = null) + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + return $instance->call($command, $parameters, $outputBuffer); + } + /** + * Queue the given console command. + * + * @param string $command + * @param array $parameters + * @return \Illuminate\Foundation\Bus\PendingDispatch + * @static + */ + public static function queue($command, $parameters = []) + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + return $instance->queue($command, $parameters); + } + /** + * Get all of the commands registered with the console. + * + * @return array + * @static + */ + public static function all() + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + return $instance->all(); + } + /** + * Get the output for the last run command. + * + * @return string + * @static + */ + public static function output() + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + return $instance->output(); + } + /** + * Bootstrap the application for artisan commands. + * + * @return void + * @static + */ + public static function bootstrap() + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + $instance->bootstrap(); + } + /** + * Bootstrap the application without booting service providers. + * + * @return void + * @static + */ + public static function bootstrapWithoutBootingProviders() + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + $instance->bootstrapWithoutBootingProviders(); + } + /** + * Set the Artisan application instance. + * + * @param \Illuminate\Console\Application $artisan + * @return void + * @static + */ + public static function setArtisan($artisan) + { //Method inherited from \Illuminate\Foundation\Console\Kernel + /** @var \App\Console\Kernel $instance */ + $instance->setArtisan($artisan); + } + + } + /** + * + * + * @see \Illuminate\Auth\AuthManager + * @see \Illuminate\Auth\SessionGuard + */ + class Auth { + /** + * Attempt to get the guard from the local cache. + * + * @param string|null $name + * @return \Illuminate\Contracts\Auth\Guard|\Illuminate\Contracts\Auth\StatefulGuard + * @static + */ + public static function guard($name = null) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->guard($name); + } + /** + * Create a session based authentication guard. + * + * @param string $name + * @param array $config + * @return \Illuminate\Auth\SessionGuard + * @static + */ + public static function createSessionDriver($name, $config) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->createSessionDriver($name, $config); + } + /** + * Create a token based authentication guard. + * + * @param string $name + * @param array $config + * @return \Illuminate\Auth\TokenGuard + * @static + */ + public static function createTokenDriver($name, $config) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->createTokenDriver($name, $config); + } + /** + * Get the default authentication driver name. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Set the default guard driver the factory should serve. + * + * @param string $name + * @return void + * @static + */ + public static function shouldUse($name) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + $instance->shouldUse($name); + } + /** + * Set the default authentication driver name. + * + * @param string $name + * @return void + * @static + */ + public static function setDefaultDriver($name) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + $instance->setDefaultDriver($name); + } + /** + * Register a new callback based request guard. + * + * @param string $driver + * @param callable $callback + * @return \Illuminate\Auth\AuthManager + * @static + */ + public static function viaRequest($driver, $callback) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->viaRequest($driver, $callback); + } + /** + * Get the user resolver callback. + * + * @return \Closure + * @static + */ + public static function userResolver() + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->userResolver(); + } + /** + * Set the callback to be used to resolve users. + * + * @param \Closure $userResolver + * @return \Illuminate\Auth\AuthManager + * @static + */ + public static function resolveUsersUsing($userResolver) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->resolveUsersUsing($userResolver); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Auth\AuthManager + * @static + */ + public static function extend($driver, $callback) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Register a custom provider creator Closure. + * + * @param string $name + * @param \Closure $callback + * @return \Illuminate\Auth\AuthManager + * @static + */ + public static function provider($name, $callback) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->provider($name, $callback); + } + /** + * Determines if any guards have already been resolved. + * + * @return bool + * @static + */ + public static function hasResolvedGuards() + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->hasResolvedGuards(); + } + /** + * Forget all of the resolved guard instances. + * + * @return \Illuminate\Auth\AuthManager + * @static + */ + public static function forgetGuards() + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->forgetGuards(); + } + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return \Illuminate\Auth\AuthManager + * @static + */ + public static function setApplication($app) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->setApplication($app); + } + /** + * Create the user provider implementation for the driver. + * + * @param string|null $provider + * @return \Illuminate\Contracts\Auth\UserProvider|null + * @throws \InvalidArgumentException + * @static + */ + public static function createUserProvider($provider = null) + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->createUserProvider($provider); + } + /** + * Get the default user provider name. + * + * @return string + * @static + */ + public static function getDefaultUserProvider() + { + /** @var \Illuminate\Auth\AuthManager $instance */ + return $instance->getDefaultUserProvider(); + } + /** + * Get the currently authenticated user. + * + * @return \App\Models\User|null + * @static + */ + public static function user() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->user(); + } + /** + * Get the ID for the currently authenticated user. + * + * @return int|string|null + * @static + */ + public static function id() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->id(); + } + /** + * Log a user into the application without sessions or cookies. + * + * @param array $credentials + * @return bool + * @static + */ + public static function once($credentials = []) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->once($credentials); + } + /** + * Log the given user ID into the application without sessions or cookies. + * + * @param mixed $id + * @return \App\Models\User|false + * @static + */ + public static function onceUsingId($id) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->onceUsingId($id); + } + /** + * Validate a user's credentials. + * + * @param array $credentials + * @return bool + * @static + */ + public static function validate($credentials = []) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->validate($credentials); + } + /** + * Attempt to authenticate using HTTP Basic Auth. + * + * @param string $field + * @param array $extraConditions + * @return \Symfony\Component\HttpFoundation\Response|null + * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException + * @static + */ + public static function basic($field = 'email', $extraConditions = []) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->basic($field, $extraConditions); + } + /** + * Perform a stateless HTTP Basic login attempt. + * + * @param string $field + * @param array $extraConditions + * @return \Symfony\Component\HttpFoundation\Response|null + * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException + * @static + */ + public static function onceBasic($field = 'email', $extraConditions = []) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->onceBasic($field, $extraConditions); + } + /** + * Attempt to authenticate a user using the given credentials. + * + * @param array $credentials + * @param bool $remember + * @return bool + * @static + */ + public static function attempt($credentials = [], $remember = false) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->attempt($credentials, $remember); + } + /** + * Attempt to authenticate a user with credentials and additional callbacks. + * + * @param array $credentials + * @param array|callable|null $callbacks + * @param bool $remember + * @return bool + * @static + */ + public static function attemptWhen($credentials = [], $callbacks = null, $remember = false) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->attemptWhen($credentials, $callbacks, $remember); + } + /** + * Log the given user ID into the application. + * + * @param mixed $id + * @param bool $remember + * @return \App\Models\User|false + * @static + */ + public static function loginUsingId($id, $remember = false) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->loginUsingId($id, $remember); + } + /** + * Log a user into the application. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @param bool $remember + * @return void + * @static + */ + public static function login($user, $remember = false) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + $instance->login($user, $remember); + } + /** + * Log the user out of the application. + * + * @return void + * @static + */ + public static function logout() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + $instance->logout(); + } + /** + * Log the user out of the application on their current device only. + * + * This method does not cycle the "remember" token. + * + * @return void + * @static + */ + public static function logoutCurrentDevice() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + $instance->logoutCurrentDevice(); + } + /** + * Invalidate other sessions for the current user. + * + * The application must be using the AuthenticateSession middleware. + * + * @param string $password + * @param string $attribute + * @return \App\Models\User|null + * @throws \Illuminate\Auth\AuthenticationException + * @static + */ + public static function logoutOtherDevices($password, $attribute = 'password') + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->logoutOtherDevices($password, $attribute); + } + /** + * Register an authentication attempt event listener. + * + * @param mixed $callback + * @return void + * @static + */ + public static function attempting($callback) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + $instance->attempting($callback); + } + /** + * Get the last user we attempted to authenticate. + * + * @return \App\Models\User + * @static + */ + public static function getLastAttempted() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getLastAttempted(); + } + /** + * Get a unique identifier for the auth session value. + * + * @return string + * @static + */ + public static function getName() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getName(); + } + /** + * Get the name of the cookie used to store the "recaller". + * + * @return string + * @static + */ + public static function getRecallerName() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getRecallerName(); + } + /** + * Determine if the user was authenticated via "remember me" cookie. + * + * @return bool + * @static + */ + public static function viaRemember() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->viaRemember(); + } + /** + * Set the number of minutes the remember me cookie should be valid for. + * + * @param int $minutes + * @return \Illuminate\Auth\SessionGuard + * @static + */ + public static function setRememberDuration($minutes) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->setRememberDuration($minutes); + } + /** + * Get the cookie creator instance used by the guard. + * + * @return \Illuminate\Contracts\Cookie\QueueingFactory + * @throws \RuntimeException + * @static + */ + public static function getCookieJar() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getCookieJar(); + } + /** + * Set the cookie creator instance used by the guard. + * + * @param \Illuminate\Contracts\Cookie\QueueingFactory $cookie + * @return void + * @static + */ + public static function setCookieJar($cookie) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + $instance->setCookieJar($cookie); + } + /** + * Get the event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher + * @static + */ + public static function getDispatcher() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getDispatcher(); + } + /** + * Set the event dispatcher instance. + * + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return void + * @static + */ + public static function setDispatcher($events) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + $instance->setDispatcher($events); + } + /** + * Get the session store used by the guard. + * + * @return \Illuminate\Contracts\Session\Session + * @static + */ + public static function getSession() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getSession(); + } + /** + * Return the currently cached user. + * + * @return \App\Models\User|null + * @static + */ + public static function getUser() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getUser(); + } + /** + * Set the current user. + * + * @param \Illuminate\Contracts\Auth\Authenticatable $user + * @return \Illuminate\Auth\SessionGuard + * @static + */ + public static function setUser($user) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->setUser($user); + } + /** + * Get the current request instance. + * + * @return \Symfony\Component\HttpFoundation\Request + * @static + */ + public static function getRequest() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getRequest(); + } + /** + * Set the current request instance. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @return \Illuminate\Auth\SessionGuard + * @static + */ + public static function setRequest($request) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->setRequest($request); + } + /** + * Get the timebox instance used by the guard. + * + * @return \Illuminate\Support\Timebox + * @static + */ + public static function getTimebox() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getTimebox(); + } + /** + * Determine if the current user is authenticated. If not, throw an exception. + * + * @return \App\Models\User + * @throws \Illuminate\Auth\AuthenticationException + * @static + */ + public static function authenticate() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->authenticate(); + } + /** + * Determine if the guard has a user instance. + * + * @return bool + * @static + */ + public static function hasUser() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->hasUser(); + } + /** + * Determine if the current user is authenticated. + * + * @return bool + * @static + */ + public static function check() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->check(); + } + /** + * Determine if the current user is a guest. + * + * @return bool + * @static + */ + public static function guest() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->guest(); + } + /** + * Forget the current user. + * + * @return \Illuminate\Auth\SessionGuard + * @static + */ + public static function forgetUser() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->forgetUser(); + } + /** + * Get the user provider used by the guard. + * + * @return \Illuminate\Contracts\Auth\UserProvider + * @static + */ + public static function getProvider() + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + return $instance->getProvider(); + } + /** + * Set the user provider used by the guard. + * + * @param \Illuminate\Contracts\Auth\UserProvider $provider + * @return void + * @static + */ + public static function setProvider($provider) + { + /** @var \Illuminate\Auth\SessionGuard $instance */ + $instance->setProvider($provider); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Auth\SessionGuard::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Auth\SessionGuard::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Auth\SessionGuard::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Auth\SessionGuard::flushMacros(); + } + + } + /** + * + * + * @see \Illuminate\View\Compilers\BladeCompiler + */ + class Blade { + /** + * Compile the view at the given path. + * + * @param string|null $path + * @return void + * @static + */ + public static function compile($path = null) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->compile($path); + } + /** + * Get the path currently being compiled. + * + * @return string + * @static + */ + public static function getPath() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->getPath(); + } + /** + * Set the path currently being compiled. + * + * @param string $path + * @return void + * @static + */ + public static function setPath($path) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->setPath($path); + } + /** + * Compile the given Blade template contents. + * + * @param string $value + * @return string + * @static + */ + public static function compileString($value) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->compileString($value); + } + /** + * Evaluate and render a Blade string to HTML. + * + * @param string $string + * @param array $data + * @param bool $deleteCachedView + * @return string + * @static + */ + public static function render($string, $data = [], $deleteCachedView = false) + { + return \Illuminate\View\Compilers\BladeCompiler::render($string, $data, $deleteCachedView); + } + /** + * Render a component instance to HTML. + * + * @param \Illuminate\View\Component $component + * @return string + * @static + */ + public static function renderComponent($component) + { + return \Illuminate\View\Compilers\BladeCompiler::renderComponent($component); + } + /** + * Strip the parentheses from the given expression. + * + * @param string $expression + * @return string + * @static + */ + public static function stripParentheses($expression) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->stripParentheses($expression); + } + /** + * Register a custom Blade compiler. + * + * @param callable $compiler + * @return void + * @static + */ + public static function extend($compiler) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->extend($compiler); + } + /** + * Get the extensions used by the compiler. + * + * @return array + * @static + */ + public static function getExtensions() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->getExtensions(); + } + /** + * Register an "if" statement directive. + * + * @param string $name + * @param callable $callback + * @return void + * @static + */ + public static function if($name, $callback) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->if($name, $callback); + } + /** + * Check the result of a condition. + * + * @param string $name + * @param mixed $parameters + * @return bool + * @static + */ + public static function check($name, ...$parameters) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->check($name, ...$parameters); + } + /** + * Register a class-based component alias directive. + * + * @param string $class + * @param string|null $alias + * @param string $prefix + * @return void + * @static + */ + public static function component($class, $alias = null, $prefix = '') + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->component($class, $alias, $prefix); + } + /** + * Register an array of class-based components. + * + * @param array $components + * @param string $prefix + * @return void + * @static + */ + public static function components($components, $prefix = '') + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->components($components, $prefix); + } + /** + * Get the registered class component aliases. + * + * @return array + * @static + */ + public static function getClassComponentAliases() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->getClassComponentAliases(); + } + /** + * Register a new anonymous component path. + * + * @param string $path + * @param string|null $prefix + * @return void + * @static + */ + public static function anonymousComponentPath($path, $prefix = null) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->anonymousComponentPath($path, $prefix); + } + /** + * Register an anonymous component namespace. + * + * @param string $directory + * @param string|null $prefix + * @return void + * @static + */ + public static function anonymousComponentNamespace($directory, $prefix = null) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->anonymousComponentNamespace($directory, $prefix); + } + /** + * Register a class-based component namespace. + * + * @param string $namespace + * @param string $prefix + * @return void + * @static + */ + public static function componentNamespace($namespace, $prefix) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->componentNamespace($namespace, $prefix); + } + /** + * Get the registered anonymous component paths. + * + * @return array + * @static + */ + public static function getAnonymousComponentPaths() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->getAnonymousComponentPaths(); + } + /** + * Get the registered anonymous component namespaces. + * + * @return array + * @static + */ + public static function getAnonymousComponentNamespaces() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->getAnonymousComponentNamespaces(); + } + /** + * Get the registered class component namespaces. + * + * @return array + * @static + */ + public static function getClassComponentNamespaces() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->getClassComponentNamespaces(); + } + /** + * Register a component alias directive. + * + * @param string $path + * @param string|null $alias + * @return void + * @static + */ + public static function aliasComponent($path, $alias = null) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->aliasComponent($path, $alias); + } + /** + * Register an include alias directive. + * + * @param string $path + * @param string|null $alias + * @return void + * @static + */ + public static function include($path, $alias = null) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->include($path, $alias); + } + /** + * Register an include alias directive. + * + * @param string $path + * @param string|null $alias + * @return void + * @static + */ + public static function aliasInclude($path, $alias = null) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->aliasInclude($path, $alias); + } + /** + * Register a handler for custom directives. + * + * @param string $name + * @param callable $handler + * @return void + * @throws \InvalidArgumentException + * @static + */ + public static function directive($name, $handler) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->directive($name, $handler); + } + /** + * Get the list of custom directives. + * + * @return array + * @static + */ + public static function getCustomDirectives() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->getCustomDirectives(); + } + /** + * Register a new precompiler. + * + * @param callable $precompiler + * @return void + * @static + */ + public static function precompiler($precompiler) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->precompiler($precompiler); + } + /** + * Set the echo format to be used by the compiler. + * + * @param string $format + * @return void + * @static + */ + public static function setEchoFormat($format) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->setEchoFormat($format); + } + /** + * Set the "echo" format to double encode entities. + * + * @return void + * @static + */ + public static function withDoubleEncoding() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->withDoubleEncoding(); + } + /** + * Set the "echo" format to not double encode entities. + * + * @return void + * @static + */ + public static function withoutDoubleEncoding() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->withoutDoubleEncoding(); + } + /** + * Indicate that component tags should not be compiled. + * + * @return void + * @static + */ + public static function withoutComponentTags() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->withoutComponentTags(); + } + /** + * Get the path to the compiled version of a view. + * + * @param string $path + * @return string + * @static + */ + public static function getCompiledPath($path) + { //Method inherited from \Illuminate\View\Compilers\Compiler + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->getCompiledPath($path); + } + /** + * Determine if the view at the given path is expired. + * + * @param string $path + * @return bool + * @static + */ + public static function isExpired($path) + { //Method inherited from \Illuminate\View\Compilers\Compiler + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->isExpired($path); + } + /** + * Get a new component hash for a component name. + * + * @param string $component + * @return string + * @static + */ + public static function newComponentHash($component) + { + return \Illuminate\View\Compilers\BladeCompiler::newComponentHash($component); + } + /** + * Compile a class component opening. + * + * @param string $component + * @param string $alias + * @param string $data + * @param string $hash + * @return string + * @static + */ + public static function compileClassComponentOpening($component, $alias, $data, $hash) + { + return \Illuminate\View\Compilers\BladeCompiler::compileClassComponentOpening($component, $alias, $data, $hash); + } + /** + * Compile the end-component statements into valid PHP. + * + * @return string + * @static + */ + public static function compileEndComponentClass() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->compileEndComponentClass(); + } + /** + * Sanitize the given component attribute value. + * + * @param mixed $value + * @return mixed + * @static + */ + public static function sanitizeComponentAttribute($value) + { + return \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($value); + } + /** + * Compile an end-once block into valid PHP. + * + * @return string + * @static + */ + public static function compileEndOnce() + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->compileEndOnce(); + } + /** + * Add a handler to be executed before echoing a given class. + * + * @param string|callable $class + * @param callable|null $handler + * @return void + * @static + */ + public static function stringable($class, $handler = null) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + $instance->stringable($class, $handler); + } + /** + * Compile Blade echos into valid PHP. + * + * @param string $value + * @return string + * @static + */ + public static function compileEchos($value) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->compileEchos($value); + } + /** + * Apply the echo handler for the value if it exists. + * + * @param string $value + * @return string + * @static + */ + public static function applyEchoHandler($value) + { + /** @var \Illuminate\View\Compilers\BladeCompiler $instance */ + return $instance->applyEchoHandler($value); + } + + } + /** + * + * + * @method static mixed auth(\Illuminate\Http\Request $request) + * @method static mixed validAuthenticationResponse(\Illuminate\Http\Request $request, mixed $result) + * @method static void broadcast(array $channels, string $event, array $payload = []) + * @method static array|null resolveAuthenticatedUser(\Illuminate\Http\Request $request) + * @method static void resolveAuthenticatedUserUsing(\Closure $callback) + * @method static \Illuminate\Broadcasting\Broadcasters\Broadcaster channel(\Illuminate\Contracts\Broadcasting\HasBroadcastChannel|string $channel, callable|string $callback, array $options = []) + * @see \Illuminate\Broadcasting\BroadcastManager + * @see \Illuminate\Broadcasting\Broadcasters\Broadcaster + */ + class Broadcast { + /** + * Register the routes for handling broadcast channel authentication and sockets. + * + * @param array|null $attributes + * @return void + * @static + */ + public static function routes($attributes = null) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + $instance->routes($attributes); + } + /** + * Register the routes for handling broadcast user authentication. + * + * @param array|null $attributes + * @return void + * @static + */ + public static function userRoutes($attributes = null) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + $instance->userRoutes($attributes); + } + /** + * Register the routes for handling broadcast authentication and sockets. + * + * Alias of "routes" method. + * + * @param array|null $attributes + * @return void + * @static + */ + public static function channelRoutes($attributes = null) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + $instance->channelRoutes($attributes); + } + /** + * Get the socket ID for the given request. + * + * @param \Illuminate\Http\Request|null $request + * @return string|null + * @static + */ + public static function socket($request = null) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->socket($request); + } + /** + * Begin broadcasting an event. + * + * @param mixed|null $event + * @return \Illuminate\Broadcasting\PendingBroadcast + * @static + */ + public static function event($event = null) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->event($event); + } + /** + * Queue the given event for broadcast. + * + * @param mixed $event + * @return void + * @static + */ + public static function queue($event) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + $instance->queue($event); + } + /** + * Get a driver instance. + * + * @param string|null $driver + * @return mixed + * @static + */ + public static function connection($driver = null) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->connection($driver); + } + /** + * Get a driver instance. + * + * @param string|null $name + * @return mixed + * @static + */ + public static function driver($name = null) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->driver($name); + } + /** + * Get a Pusher instance for the given configuration. + * + * @param array $config + * @return \Pusher\Pusher + * @static + */ + public static function pusher($config) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->pusher($config); + } + /** + * Get an Ably instance for the given configuration. + * + * @param array $config + * @return \Ably\AblyRest + * @static + */ + public static function ably($config) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->ably($config); + } + /** + * Get the default driver name. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Set the default driver name. + * + * @param string $name + * @return void + * @static + */ + public static function setDefaultDriver($name) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + $instance->setDefaultDriver($name); + } + /** + * Disconnect the given disk and remove from local cache. + * + * @param string|null $name + * @return void + * @static + */ + public static function purge($name = null) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + $instance->purge($name); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Broadcasting\BroadcastManager + * @static + */ + public static function extend($driver, $callback) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Get the application instance used by the manager. + * + * @return \Illuminate\Contracts\Foundation\Application + * @static + */ + public static function getApplication() + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->getApplication(); + } + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return \Illuminate\Broadcasting\BroadcastManager + * @static + */ + public static function setApplication($app) + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->setApplication($app); + } + /** + * Forget all of the resolved driver instances. + * + * @return \Illuminate\Broadcasting\BroadcastManager + * @static + */ + public static function forgetDrivers() + { + /** @var \Illuminate\Broadcasting\BroadcastManager $instance */ + return $instance->forgetDrivers(); + } + + } + /** + * + * + * @see \Illuminate\Bus\Dispatcher + * @see \Illuminate\Support\Testing\Fakes\BusFake + */ + class Bus { + /** + * Dispatch a command to its appropriate handler. + * + * @param mixed $command + * @return mixed + * @static + */ + public static function dispatch($command) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->dispatch($command); + } + /** + * Dispatch a command to its appropriate handler in the current process. + * + * Queueable jobs will be dispatched to the "sync" queue. + * + * @param mixed $command + * @param mixed $handler + * @return mixed + * @static + */ + public static function dispatchSync($command, $handler = null) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->dispatchSync($command, $handler); + } + /** + * Dispatch a command to its appropriate handler in the current process without using the synchronous queue. + * + * @param mixed $command + * @param mixed $handler + * @return mixed + * @static + */ + public static function dispatchNow($command, $handler = null) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->dispatchNow($command, $handler); + } + /** + * Attempt to find the batch with the given ID. + * + * @param string $batchId + * @return \Illuminate\Bus\Batch|null + * @static + */ + public static function findBatch($batchId) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->findBatch($batchId); + } + /** + * Create a new batch of queueable jobs. + * + * @param \Illuminate\Support\Collection|array|mixed $jobs + * @return \Illuminate\Bus\PendingBatch + * @static + */ + public static function batch($jobs) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->batch($jobs); + } + /** + * Create a new chain of queueable jobs. + * + * @param \Illuminate\Support\Collection|array $jobs + * @return \Illuminate\Foundation\Bus\PendingChain + * @static + */ + public static function chain($jobs) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->chain($jobs); + } + /** + * Determine if the given command has a handler. + * + * @param mixed $command + * @return bool + * @static + */ + public static function hasCommandHandler($command) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->hasCommandHandler($command); + } + /** + * Retrieve the handler for a command. + * + * @param mixed $command + * @return bool|mixed + * @static + */ + public static function getCommandHandler($command) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->getCommandHandler($command); + } + /** + * Dispatch a command to its appropriate handler behind a queue. + * + * @param mixed $command + * @return mixed + * @throws \RuntimeException + * @static + */ + public static function dispatchToQueue($command) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->dispatchToQueue($command); + } + /** + * Dispatch a command to its appropriate handler after the current process. + * + * @param mixed $command + * @param mixed $handler + * @return void + * @static + */ + public static function dispatchAfterResponse($command, $handler = null) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + $instance->dispatchAfterResponse($command, $handler); + } + /** + * Set the pipes through which commands should be piped before dispatching. + * + * @param array $pipes + * @return \Illuminate\Bus\Dispatcher + * @static + */ + public static function pipeThrough($pipes) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->pipeThrough($pipes); + } + /** + * Map a command to a handler. + * + * @param array $map + * @return \Illuminate\Bus\Dispatcher + * @static + */ + public static function map($map) + { + /** @var \Illuminate\Bus\Dispatcher $instance */ + return $instance->map($map); + } + /** + * Specify the jobs that should be dispatched instead of faked. + * + * @param array|string $jobsToDispatch + * @return void + * @static + */ + public static function except($jobsToDispatch) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->except($jobsToDispatch); + } + /** + * Assert if a job was dispatched based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|int|null $callback + * @return void + * @static + */ + public static function assertDispatched($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertDispatched($command, $callback); + } + /** + * Assert if a job was pushed a number of times. + * + * @param string|\Closure $command + * @param int $times + * @return void + * @static + */ + public static function assertDispatchedTimes($command, $times = 1) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertDispatchedTimes($command, $times); + } + /** + * Determine if a job was dispatched based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|null $callback + * @return void + * @static + */ + public static function assertNotDispatched($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertNotDispatched($command, $callback); + } + /** + * Assert that no jobs were dispatched. + * + * @return void + * @static + */ + public static function assertNothingDispatched() + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertNothingDispatched(); + } + /** + * Assert if a job was explicitly dispatched synchronously based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|int|null $callback + * @return void + * @static + */ + public static function assertDispatchedSync($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertDispatchedSync($command, $callback); + } + /** + * Assert if a job was pushed synchronously a number of times. + * + * @param string|\Closure $command + * @param int $times + * @return void + * @static + */ + public static function assertDispatchedSyncTimes($command, $times = 1) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertDispatchedSyncTimes($command, $times); + } + /** + * Determine if a job was dispatched based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|null $callback + * @return void + * @static + */ + public static function assertNotDispatchedSync($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertNotDispatchedSync($command, $callback); + } + /** + * Assert if a job was dispatched after the response was sent based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|int|null $callback + * @return void + * @static + */ + public static function assertDispatchedAfterResponse($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertDispatchedAfterResponse($command, $callback); + } + /** + * Assert if a job was pushed after the response was sent a number of times. + * + * @param string|\Closure $command + * @param int $times + * @return void + * @static + */ + public static function assertDispatchedAfterResponseTimes($command, $times = 1) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertDispatchedAfterResponseTimes($command, $times); + } + /** + * Determine if a job was dispatched based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|null $callback + * @return void + * @static + */ + public static function assertNotDispatchedAfterResponse($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertNotDispatchedAfterResponse($command, $callback); + } + /** + * Assert if a chain of jobs was dispatched. + * + * @param array $expectedChain + * @return void + * @static + */ + public static function assertChained($expectedChain) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertChained($expectedChain); + } + /** + * Assert if a job was dispatched with an empty chain based on a truth-test callback. + * + * @param string|\Closure $command + * @param callable|null $callback + * @return void + * @static + */ + public static function assertDispatchedWithoutChain($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertDispatchedWithoutChain($command, $callback); + } + /** + * Assert if a batch was dispatched based on a truth-test callback. + * + * @param callable $callback + * @return void + * @static + */ + public static function assertBatched($callback) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertBatched($callback); + } + /** + * Assert the number of batches that have been dispatched. + * + * @param int $count + * @return void + * @static + */ + public static function assertBatchCount($count) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertBatchCount($count); + } + /** + * Assert that no batched jobs were dispatched. + * + * @return void + * @static + */ + public static function assertNothingBatched() + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + $instance->assertNothingBatched(); + } + /** + * Get all of the jobs matching a truth-test callback. + * + * @param string $command + * @param callable|null $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function dispatched($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + return $instance->dispatched($command, $callback); + } + /** + * Get all of the jobs dispatched synchronously matching a truth-test callback. + * + * @param string $command + * @param callable|null $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function dispatchedSync($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + return $instance->dispatchedSync($command, $callback); + } + /** + * Get all of the jobs dispatched after the response was sent matching a truth-test callback. + * + * @param string $command + * @param callable|null $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function dispatchedAfterResponse($command, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + return $instance->dispatchedAfterResponse($command, $callback); + } + /** + * Get all of the pending batches matching a truth-test callback. + * + * @param callable $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function batched($callback) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + return $instance->batched($callback); + } + /** + * Determine if there are any stored commands for a given class. + * + * @param string $command + * @return bool + * @static + */ + public static function hasDispatched($command) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + return $instance->hasDispatched($command); + } + /** + * Determine if there are any stored commands for a given class. + * + * @param string $command + * @return bool + * @static + */ + public static function hasDispatchedSync($command) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + return $instance->hasDispatchedSync($command); + } + /** + * Determine if there are any stored commands for a given class. + * + * @param string $command + * @return bool + * @static + */ + public static function hasDispatchedAfterResponse($command) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + return $instance->hasDispatchedAfterResponse($command); + } + /** + * Dispatch an empty job batch for testing. + * + * @param string $name + * @return \Illuminate\Bus\Batch + * @static + */ + public static function dispatchFakeBatch($name = '') + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + return $instance->dispatchFakeBatch($name); + } + /** + * Record the fake pending batch dispatch. + * + * @param \Illuminate\Bus\PendingBatch $pendingBatch + * @return \Illuminate\Bus\Batch + * @static + */ + public static function recordPendingBatch($pendingBatch) + { + /** @var \Illuminate\Support\Testing\Fakes\BusFake $instance */ + return $instance->recordPendingBatch($pendingBatch); + } + + } + /** + * + * + * @see \Illuminate\Cache\CacheManager + * @mixin \Illuminate\Cache\Repository + */ + class Cache { + /** + * Get a cache store instance by name, wrapped in a repository. + * + * @param string|null $name + * @return \Illuminate\Contracts\Cache\Repository + * @static + */ + public static function store($name = null) + { + /** @var \Illuminate\Cache\CacheManager $instance */ + return $instance->store($name); + } + /** + * Get a cache driver instance. + * + * @param string|null $driver + * @return \Illuminate\Contracts\Cache\Repository + * @static + */ + public static function driver($driver = null) + { + /** @var \Illuminate\Cache\CacheManager $instance */ + return $instance->driver($driver); + } + /** + * Create a new cache repository with the given implementation. + * + * @param \Illuminate\Contracts\Cache\Store $store + * @return \Illuminate\Cache\Repository + * @static + */ + public static function repository($store) + { + /** @var \Illuminate\Cache\CacheManager $instance */ + return $instance->repository($store); + } + /** + * Re-set the event dispatcher on all resolved cache repositories. + * + * @return void + * @static + */ + public static function refreshEventDispatcher() + { + /** @var \Illuminate\Cache\CacheManager $instance */ + $instance->refreshEventDispatcher(); + } + /** + * Get the default cache driver name. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Cache\CacheManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Set the default cache driver name. + * + * @param string $name + * @return void + * @static + */ + public static function setDefaultDriver($name) + { + /** @var \Illuminate\Cache\CacheManager $instance */ + $instance->setDefaultDriver($name); + } + /** + * Unset the given driver instances. + * + * @param array|string|null $name + * @return \Illuminate\Cache\CacheManager + * @static + */ + public static function forgetDriver($name = null) + { + /** @var \Illuminate\Cache\CacheManager $instance */ + return $instance->forgetDriver($name); + } + /** + * Disconnect the given driver and remove from local cache. + * + * @param string|null $name + * @return void + * @static + */ + public static function purge($name = null) + { + /** @var \Illuminate\Cache\CacheManager $instance */ + $instance->purge($name); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Cache\CacheManager + * @static + */ + public static function extend($driver, $callback) + { + /** @var \Illuminate\Cache\CacheManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Determine if an item exists in the cache. + * + * @param array|string $key + * @return bool + * @static + */ + public static function has($key) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->has($key); + } + /** + * Determine if an item doesn't exist in the cache. + * + * @param string $key + * @return bool + * @static + */ + public static function missing($key) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->missing($key); + } + /** + * Retrieve an item from the cache by key. + * + * @template TCacheValue + * @param array|string $key + * @param \Illuminate\Cache\TCacheValue|\Illuminate\Cache\(\Closure(): TCacheValue) $default + * @return \Illuminate\Cache\(TCacheValue is null ? mixed : TCacheValue) + * @static + */ + public static function get($key, $default = null) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->get($key, $default); + } + /** + * Retrieve multiple items from the cache by key. + * + * Items not found in the cache will have a null value. + * + * @param array $keys + * @return array + * @static + */ + public static function many($keys) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->many($keys); + } + /** + * Obtains multiple cache items by their unique keys. + * + * @return \Illuminate\Cache\iterable + * @param \Psr\SimpleCache\iterable $keys A list of keys that can be obtained in a single operation. + * @param mixed $default Default value to return for keys that do not exist. + * @return \Psr\SimpleCache\iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value. + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if $keys is neither an array nor a Traversable, + * or if any of the $keys are not a legal value. + * @static + */ + public static function getMultiple($keys, $default = null) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->getMultiple($keys, $default); + } + /** + * Retrieve an item from the cache and delete it. + * + * @template TCacheValue + * @param array|string $key + * @param \Illuminate\Cache\TCacheValue|\Illuminate\Cache\(\Closure(): TCacheValue) $default + * @return \Illuminate\Cache\(TCacheValue is null ? mixed : TCacheValue) + * @static + */ + public static function pull($key, $default = null) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->pull($key, $default); + } + /** + * Store an item in the cache. + * + * @param array|string $key + * @param mixed $value + * @param \DateTimeInterface|\DateInterval|int|null $ttl + * @return bool + * @static + */ + public static function put($key, $value, $ttl = null) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->put($key, $value, $ttl); + } + /** + * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time. + * + * @return bool + * @param string $key The key of the item to store. + * @param mixed $value The value of the item to store, must be serializable. + * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and + * the driver supports TTL then the library may set a default value + * for it or let the driver take care of that. + * @return bool True on success and false on failure. + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if the $key string is not a legal value. + * @static + */ + public static function set($key, $value, $ttl = null) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->set($key, $value, $ttl); + } + /** + * Store multiple items in the cache for a given number of seconds. + * + * @param array $values + * @param \DateTimeInterface|\DateInterval|int|null $ttl + * @return bool + * @static + */ + public static function putMany($values, $ttl = null) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->putMany($values, $ttl); + } + /** + * Persists a set of key => value pairs in the cache, with an optional TTL. + * + * @return bool + * @param \Psr\SimpleCache\iterable $values A list of key => value pairs for a multiple-set operation. + * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and + * the driver supports TTL then the library may set a default value + * for it or let the driver take care of that. + * @return bool True on success and false on failure. + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if $values is neither an array nor a Traversable, + * or if any of the $values are not a legal value. + * @static + */ + public static function setMultiple($values, $ttl = null) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->setMultiple($values, $ttl); + } + /** + * Store an item in the cache if the key does not exist. + * + * @param string $key + * @param mixed $value + * @param \DateTimeInterface|\DateInterval|int|null $ttl + * @return bool + * @static + */ + public static function add($key, $value, $ttl = null) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->add($key, $value, $ttl); + } + /** + * Increment the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + * @static + */ + public static function increment($key, $value = 1) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->increment($key, $value); + } + /** + * Decrement the value of an item in the cache. + * + * @param string $key + * @param mixed $value + * @return int|bool + * @static + */ + public static function decrement($key, $value = 1) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->decrement($key, $value); + } + /** + * Store an item in the cache indefinitely. + * + * @param string $key + * @param mixed $value + * @return bool + * @static + */ + public static function forever($key, $value) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->forever($key, $value); + } + /** + * Get an item from the cache, or execute the given Closure and store the result. + * + * @template TCacheValue + * @param string $key + * @param \Closure|\DateTimeInterface|\DateInterval|int|null $ttl + * @param \Closure(): TCacheValue $callback + * @return \Illuminate\Cache\TCacheValue + * @static + */ + public static function remember($key, $ttl, $callback) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->remember($key, $ttl, $callback); + } + /** + * Get an item from the cache, or execute the given Closure and store the result forever. + * + * @template TCacheValue + * @param string $key + * @param \Closure(): TCacheValue $callback + * @return \Illuminate\Cache\TCacheValue + * @static + */ + public static function sear($key, $callback) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->sear($key, $callback); + } + /** + * Get an item from the cache, or execute the given Closure and store the result forever. + * + * @template TCacheValue + * @param string $key + * @param \Closure(): TCacheValue $callback + * @return \Illuminate\Cache\TCacheValue + * @static + */ + public static function rememberForever($key, $callback) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->rememberForever($key, $callback); + } + /** + * Remove an item from the cache. + * + * @param string $key + * @return bool + * @static + */ + public static function forget($key) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->forget($key); + } + /** + * Delete an item from the cache by its unique key. + * + * @return bool + * @param string $key The unique cache key of the item to delete. + * @return bool True if the item was successfully removed. False if there was an error. + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if the $key string is not a legal value. + * @static + */ + public static function delete($key) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->delete($key); + } + /** + * Deletes multiple cache items in a single operation. + * + * @return bool + * @param \Psr\SimpleCache\iterable $keys A list of string-based keys to be deleted. + * @return bool True if the items were successfully removed. False if there was an error. + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if $keys is neither an array nor a Traversable, + * or if any of the $keys are not a legal value. + * @static + */ + public static function deleteMultiple($keys) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->deleteMultiple($keys); + } + /** + * Wipes clean the entire cache's keys. + * + * @return bool + * @return bool True on success and false on failure. + * @static + */ + public static function clear() + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->clear(); + } + /** + * Begin executing a new tags operation if the store supports it. + * + * @param array|mixed $names + * @return \Illuminate\Cache\TaggedCache + * @throws \BadMethodCallException + * @static + */ + public static function tags($names) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->tags($names); + } + /** + * Determine if the current store supports tags. + * + * @return bool + * @static + */ + public static function supportsTags() + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->supportsTags(); + } + /** + * Get the default cache time. + * + * @return int|null + * @static + */ + public static function getDefaultCacheTime() + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->getDefaultCacheTime(); + } + /** + * Set the default cache time in seconds. + * + * @param int|null $seconds + * @return \Illuminate\Cache\Repository + * @static + */ + public static function setDefaultCacheTime($seconds) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->setDefaultCacheTime($seconds); + } + /** + * Get the cache store implementation. + * + * @return \Illuminate\Contracts\Cache\Store + * @static + */ + public static function getStore() + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->getStore(); + } + /** + * Get the event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher + * @static + */ + public static function getEventDispatcher() + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->getEventDispatcher(); + } + /** + * Set the event dispatcher instance. + * + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return void + * @static + */ + public static function setEventDispatcher($events) + { + /** @var \Illuminate\Cache\Repository $instance */ + $instance->setEventDispatcher($events); + } + /** + * Determine if a cached value exists. + * + * @param string $key + * @return bool + * @static + */ + public static function offsetExists($key) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->offsetExists($key); + } + /** + * Retrieve an item from the cache by key. + * + * @param string $key + * @return mixed + * @static + */ + public static function offsetGet($key) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->offsetGet($key); + } + /** + * Store an item in the cache for the default time. + * + * @param string $key + * @param mixed $value + * @return void + * @static + */ + public static function offsetSet($key, $value) + { + /** @var \Illuminate\Cache\Repository $instance */ + $instance->offsetSet($key, $value); + } + /** + * Remove an item from the cache. + * + * @param string $key + * @return void + * @static + */ + public static function offsetUnset($key) + { + /** @var \Illuminate\Cache\Repository $instance */ + $instance->offsetUnset($key); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Cache\Repository::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Cache\Repository::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Cache\Repository::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Cache\Repository::flushMacros(); + } + /** + * Dynamically handle calls to the class. + * + * @param string $method + * @param array $parameters + * @return mixed + * @throws \BadMethodCallException + * @static + */ + public static function macroCall($method, $parameters) + { + /** @var \Illuminate\Cache\Repository $instance */ + return $instance->macroCall($method, $parameters); + } + /** + * Get a lock instance. + * + * @param string $name + * @param int $seconds + * @param string|null $owner + * @return \Illuminate\Contracts\Cache\Lock + * @static + */ + public static function lock($name, $seconds = 0, $owner = null) + { + /** @var \Illuminate\Cache\RedisStore $instance */ + return $instance->lock($name, $seconds, $owner); + } + /** + * Restore a lock instance using the owner identifier. + * + * @param string $name + * @param string $owner + * @return \Illuminate\Contracts\Cache\Lock + * @static + */ + public static function restoreLock($name, $owner) + { + /** @var \Illuminate\Cache\RedisStore $instance */ + return $instance->restoreLock($name, $owner); + } + /** + * Remove all items from the cache. + * + * @return bool + * @static + */ + public static function flush() + { + /** @var \Illuminate\Cache\RedisStore $instance */ + return $instance->flush(); + } + /** + * Get the Redis connection instance. + * + * @return \Illuminate\Redis\Connections\Connection + * @static + */ + public static function connection() + { + /** @var \Illuminate\Cache\RedisStore $instance */ + return $instance->connection(); + } + /** + * Get the Redis connection instance that should be used to manage locks. + * + * @return \Illuminate\Redis\Connections\Connection + * @static + */ + public static function lockConnection() + { + /** @var \Illuminate\Cache\RedisStore $instance */ + return $instance->lockConnection(); + } + /** + * Specify the name of the connection that should be used to store data. + * + * @param string $connection + * @return void + * @static + */ + public static function setConnection($connection) + { + /** @var \Illuminate\Cache\RedisStore $instance */ + $instance->setConnection($connection); + } + /** + * Specify the name of the connection that should be used to manage locks. + * + * @param string $connection + * @return \Illuminate\Cache\RedisStore + * @static + */ + public static function setLockConnection($connection) + { + /** @var \Illuminate\Cache\RedisStore $instance */ + return $instance->setLockConnection($connection); + } + /** + * Get the Redis database instance. + * + * @return \Illuminate\Contracts\Redis\Factory + * @static + */ + public static function getRedis() + { + /** @var \Illuminate\Cache\RedisStore $instance */ + return $instance->getRedis(); + } + /** + * Get the cache key prefix. + * + * @return string + * @static + */ + public static function getPrefix() + { + /** @var \Illuminate\Cache\RedisStore $instance */ + return $instance->getPrefix(); + } + /** + * Set the cache key prefix. + * + * @param string $prefix + * @return void + * @static + */ + public static function setPrefix($prefix) + { + /** @var \Illuminate\Cache\RedisStore $instance */ + $instance->setPrefix($prefix); + } + + } + /** + * + * + * @see \Illuminate\Config\Repository + */ + class Config { + /** + * Determine if the given configuration value exists. + * + * @param string $key + * @return bool + * @static + */ + public static function has($key) + { + /** @var \Illuminate\Config\Repository $instance */ + return $instance->has($key); + } + /** + * Get the specified configuration value. + * + * @param array|string $key + * @param mixed $default + * @return mixed + * @static + */ + public static function get($key, $default = null) + { + /** @var \Illuminate\Config\Repository $instance */ + return $instance->get($key, $default); + } + /** + * Get many configuration values. + * + * @param array $keys + * @return array + * @static + */ + public static function getMany($keys) + { + /** @var \Illuminate\Config\Repository $instance */ + return $instance->getMany($keys); + } + /** + * Set a given configuration value. + * + * @param array|string $key + * @param mixed $value + * @return void + * @static + */ + public static function set($key, $value = null) + { + /** @var \Illuminate\Config\Repository $instance */ + $instance->set($key, $value); + } + /** + * Prepend a value onto an array configuration value. + * + * @param string $key + * @param mixed $value + * @return void + * @static + */ + public static function prepend($key, $value) + { + /** @var \Illuminate\Config\Repository $instance */ + $instance->prepend($key, $value); + } + /** + * Push a value onto an array configuration value. + * + * @param string $key + * @param mixed $value + * @return void + * @static + */ + public static function push($key, $value) + { + /** @var \Illuminate\Config\Repository $instance */ + $instance->push($key, $value); + } + /** + * Get all of the configuration items for the application. + * + * @return array + * @static + */ + public static function all() + { + /** @var \Illuminate\Config\Repository $instance */ + return $instance->all(); + } + /** + * Determine if the given configuration option exists. + * + * @param string $key + * @return bool + * @static + */ + public static function offsetExists($key) + { + /** @var \Illuminate\Config\Repository $instance */ + return $instance->offsetExists($key); + } + /** + * Get a configuration option. + * + * @param string $key + * @return mixed + * @static + */ + public static function offsetGet($key) + { + /** @var \Illuminate\Config\Repository $instance */ + return $instance->offsetGet($key); + } + /** + * Set a configuration option. + * + * @param string $key + * @param mixed $value + * @return void + * @static + */ + public static function offsetSet($key, $value) + { + /** @var \Illuminate\Config\Repository $instance */ + $instance->offsetSet($key, $value); + } + /** + * Unset a configuration option. + * + * @param string $key + * @return void + * @static + */ + public static function offsetUnset($key) + { + /** @var \Illuminate\Config\Repository $instance */ + $instance->offsetUnset($key); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Config\Repository::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Config\Repository::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Config\Repository::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Config\Repository::flushMacros(); + } + + } + /** + * + * + * @see \Illuminate\Cookie\CookieJar + */ + class Cookie { + /** + * Create a new cookie instance. + * + * @param string $name + * @param string $value + * @param int $minutes + * @param string|null $path + * @param string|null $domain + * @param bool|null $secure + * @param bool $httpOnly + * @param bool $raw + * @param string|null $sameSite + * @return \Symfony\Component\HttpFoundation\Cookie + * @static + */ + public static function make($name, $value, $minutes = 0, $path = null, $domain = null, $secure = null, $httpOnly = true, $raw = false, $sameSite = null) + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + return $instance->make($name, $value, $minutes, $path, $domain, $secure, $httpOnly, $raw, $sameSite); + } + /** + * Create a cookie that lasts "forever" (400 days). + * + * @param string $name + * @param string $value + * @param string|null $path + * @param string|null $domain + * @param bool|null $secure + * @param bool $httpOnly + * @param bool $raw + * @param string|null $sameSite + * @return \Symfony\Component\HttpFoundation\Cookie + * @static + */ + public static function forever($name, $value, $path = null, $domain = null, $secure = null, $httpOnly = true, $raw = false, $sameSite = null) + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + return $instance->forever($name, $value, $path, $domain, $secure, $httpOnly, $raw, $sameSite); + } + /** + * Expire the given cookie. + * + * @param string $name + * @param string|null $path + * @param string|null $domain + * @return \Symfony\Component\HttpFoundation\Cookie + * @static + */ + public static function forget($name, $path = null, $domain = null) + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + return $instance->forget($name, $path, $domain); + } + /** + * Determine if a cookie has been queued. + * + * @param string $key + * @param string|null $path + * @return bool + * @static + */ + public static function hasQueued($key, $path = null) + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + return $instance->hasQueued($key, $path); + } + /** + * Get a queued cookie instance. + * + * @param string $key + * @param mixed $default + * @param string|null $path + * @return \Symfony\Component\HttpFoundation\Cookie|null + * @static + */ + public static function queued($key, $default = null, $path = null) + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + return $instance->queued($key, $default, $path); + } + /** + * Queue a cookie to send with the next response. + * + * @param mixed $parameters + * @return void + * @static + */ + public static function queue(...$parameters) + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + $instance->queue(...$parameters); + } + /** + * Queue a cookie to expire with the next response. + * + * @param string $name + * @param string|null $path + * @param string|null $domain + * @return void + * @static + */ + public static function expire($name, $path = null, $domain = null) + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + $instance->expire($name, $path, $domain); + } + /** + * Remove a cookie from the queue. + * + * @param string $name + * @param string|null $path + * @return void + * @static + */ + public static function unqueue($name, $path = null) + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + $instance->unqueue($name, $path); + } + /** + * Set the default path and domain for the jar. + * + * @param string $path + * @param string|null $domain + * @param bool|null $secure + * @param string|null $sameSite + * @return \Illuminate\Cookie\CookieJar + * @static + */ + public static function setDefaultPathAndDomain($path, $domain, $secure = false, $sameSite = null) + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + return $instance->setDefaultPathAndDomain($path, $domain, $secure, $sameSite); + } + /** + * Get the cookies which have been queued for the next request. + * + * @return \Symfony\Component\HttpFoundation\Cookie[] + * @static + */ + public static function getQueuedCookies() + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + return $instance->getQueuedCookies(); + } + /** + * Flush the cookies which have been queued for the next request. + * + * @return \Illuminate\Cookie\CookieJar + * @static + */ + public static function flushQueuedCookies() + { + /** @var \Illuminate\Cookie\CookieJar $instance */ + return $instance->flushQueuedCookies(); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Cookie\CookieJar::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Cookie\CookieJar::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Cookie\CookieJar::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Cookie\CookieJar::flushMacros(); + } + + } + /** + * + * + * @see \Illuminate\Encryption\Encrypter + */ + class Crypt { + /** + * Determine if the given key and cipher combination is valid. + * + * @param string $key + * @param string $cipher + * @return bool + * @static + */ + public static function supported($key, $cipher) + { + return \Illuminate\Encryption\Encrypter::supported($key, $cipher); + } + /** + * Create a new encryption key for the given cipher. + * + * @param string $cipher + * @return string + * @static + */ + public static function generateKey($cipher) + { + return \Illuminate\Encryption\Encrypter::generateKey($cipher); + } + /** + * Encrypt the given value. + * + * @param mixed $value + * @param bool $serialize + * @return string + * @throws \Illuminate\Contracts\Encryption\EncryptException + * @static + */ + public static function encrypt($value, $serialize = true) + { + /** @var \Illuminate\Encryption\Encrypter $instance */ + return $instance->encrypt($value, $serialize); + } + /** + * Encrypt a string without serialization. + * + * @param string $value + * @return string + * @throws \Illuminate\Contracts\Encryption\EncryptException + * @static + */ + public static function encryptString($value) + { + /** @var \Illuminate\Encryption\Encrypter $instance */ + return $instance->encryptString($value); + } + /** + * Decrypt the given value. + * + * @param string $payload + * @param bool $unserialize + * @return mixed + * @throws \Illuminate\Contracts\Encryption\DecryptException + * @static + */ + public static function decrypt($payload, $unserialize = true) + { + /** @var \Illuminate\Encryption\Encrypter $instance */ + return $instance->decrypt($payload, $unserialize); + } + /** + * Decrypt the given string without unserialization. + * + * @param string $payload + * @return string + * @throws \Illuminate\Contracts\Encryption\DecryptException + * @static + */ + public static function decryptString($payload) + { + /** @var \Illuminate\Encryption\Encrypter $instance */ + return $instance->decryptString($payload); + } + /** + * Get the encryption key that the encrypter is currently using. + * + * @return string + * @static + */ + public static function getKey() + { + /** @var \Illuminate\Encryption\Encrypter $instance */ + return $instance->getKey(); + } + + } + /** + * + * + * @see https://carbon.nesbot.com/docs/ + * @see https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Factory.php + * @method static \Illuminate\Support\Carbon create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null) + * @method static \Illuminate\Support\Carbon createFromDate($year = null, $month = null, $day = null, $tz = null) + * @method static \Illuminate\Support\Carbon|false createFromFormat($format, $time, $tz = null) + * @method static \Illuminate\Support\Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null) + * @method static \Illuminate\Support\Carbon createFromTimeString($time, $tz = null) + * @method static \Illuminate\Support\Carbon createFromTimestamp($timestamp, $tz = null) + * @method static \Illuminate\Support\Carbon createFromTimestampMs($timestamp, $tz = null) + * @method static \Illuminate\Support\Carbon createFromTimestampUTC($timestamp) + * @method static \Illuminate\Support\Carbon createMidnightDate($year = null, $month = null, $day = null, $tz = null) + * @method static \Illuminate\Support\Carbon|false createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null) + * @method static void disableHumanDiffOption($humanDiffOption) + * @method static void enableHumanDiffOption($humanDiffOption) + * @method static mixed executeWithLocale($locale, $func) + * @method static \Illuminate\Support\Carbon fromSerialized($value) + * @method static array getAvailableLocales() + * @method static array getDays() + * @method static int getHumanDiffOptions() + * @method static array getIsoUnits() + * @method static array getLastErrors() + * @method static string getLocale() + * @method static int getMidDayAt() + * @method static \Illuminate\Support\Carbon|null getTestNow() + * @method static \Symfony\Component\Translation\TranslatorInterface getTranslator() + * @method static int getWeekEndsAt() + * @method static int getWeekStartsAt() + * @method static array getWeekendDays() + * @method static bool hasFormat($date, $format) + * @method static bool hasMacro($name) + * @method static bool hasRelativeKeywords($time) + * @method static bool hasTestNow() + * @method static \Illuminate\Support\Carbon instance($date) + * @method static bool isImmutable() + * @method static bool isModifiableUnit($unit) + * @method static bool isMutable() + * @method static bool isStrictModeEnabled() + * @method static bool localeHasDiffOneDayWords($locale) + * @method static bool localeHasDiffSyntax($locale) + * @method static bool localeHasDiffTwoDayWords($locale) + * @method static bool localeHasPeriodSyntax($locale) + * @method static bool localeHasShortUnits($locale) + * @method static void macro($name, $macro) + * @method static \Illuminate\Support\Carbon|null make($var) + * @method static \Illuminate\Support\Carbon maxValue() + * @method static \Illuminate\Support\Carbon minValue() + * @method static void mixin($mixin) + * @method static \Illuminate\Support\Carbon now($tz = null) + * @method static \Illuminate\Support\Carbon parse($time = null, $tz = null) + * @method static string pluralUnit(string $unit) + * @method static void resetMonthsOverflow() + * @method static void resetToStringFormat() + * @method static void resetYearsOverflow() + * @method static void serializeUsing($callback) + * @method static void setHumanDiffOptions($humanDiffOptions) + * @method static bool setLocale($locale) + * @method static void setMidDayAt($hour) + * @method static void setTestNow($testNow = null) + * @method static void setToStringFormat($format) + * @method static void setTranslator(\Symfony\Component\Translation\TranslatorInterface $translator) + * @method static void setUtf8($utf8) + * @method static void setWeekEndsAt($day) + * @method static void setWeekStartsAt($day) + * @method static void setWeekendDays($days) + * @method static bool shouldOverflowMonths() + * @method static bool shouldOverflowYears() + * @method static string singularUnit(string $unit) + * @method static \Illuminate\Support\Carbon today($tz = null) + * @method static \Illuminate\Support\Carbon tomorrow($tz = null) + * @method static void useMonthsOverflow($monthsOverflow = true) + * @method static void useStrictMode($strictModeEnabled = true) + * @method static void useYearsOverflow($yearsOverflow = true) + * @method static \Illuminate\Support\Carbon yesterday($tz = null) + * @see \Illuminate\Support\DateFactory + */ + class Date { + /** + * Use the given handler when generating dates (class name, callable, or factory). + * + * @param mixed $handler + * @return mixed + * @throws \InvalidArgumentException + * @static + */ + public static function use($handler) + { + return \Illuminate\Support\DateFactory::use($handler); + } + /** + * Use the default date class when generating dates. + * + * @return void + * @static + */ + public static function useDefault() + { + \Illuminate\Support\DateFactory::useDefault(); + } + /** + * Execute the given callable on each date creation. + * + * @param callable $callable + * @return void + * @static + */ + public static function useCallable($callable) + { + \Illuminate\Support\DateFactory::useCallable($callable); + } + /** + * Use the given date type (class) when generating dates. + * + * @param string $dateClass + * @return void + * @static + */ + public static function useClass($dateClass) + { + \Illuminate\Support\DateFactory::useClass($dateClass); + } + /** + * Use the given Carbon factory when generating dates. + * + * @param object $factory + * @return void + * @static + */ + public static function useFactory($factory) + { + \Illuminate\Support\DateFactory::useFactory($factory); + } + + } + /** + * + * + * @see \Illuminate\Database\DatabaseManager + */ + class DB { + /** + * Get a database connection instance. + * + * @param string|null $name + * @return \Illuminate\Database\Connection + * @static + */ + public static function connection($name = null) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + return $instance->connection($name); + } + /** + * Register a custom Doctrine type. + * + * @param string $class + * @param string $name + * @param string $type + * @return void + * @throws \Doctrine\DBAL\DBALException + * @throws \RuntimeException + * @static + */ + public static function registerDoctrineType($class, $name, $type) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + $instance->registerDoctrineType($class, $name, $type); + } + /** + * Disconnect from the given database and remove from local cache. + * + * @param string|null $name + * @return void + * @static + */ + public static function purge($name = null) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + $instance->purge($name); + } + /** + * Disconnect from the given database. + * + * @param string|null $name + * @return void + * @static + */ + public static function disconnect($name = null) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + $instance->disconnect($name); + } + /** + * Reconnect to the given database. + * + * @param string|null $name + * @return \Illuminate\Database\Connection + * @static + */ + public static function reconnect($name = null) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + return $instance->reconnect($name); + } + /** + * Set the default database connection for the callback execution. + * + * @param string $name + * @param callable $callback + * @return mixed + * @static + */ + public static function usingConnection($name, $callback) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + return $instance->usingConnection($name, $callback); + } + /** + * Get the default connection name. + * + * @return string + * @static + */ + public static function getDefaultConnection() + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + return $instance->getDefaultConnection(); + } + /** + * Set the default connection name. + * + * @param string $name + * @return void + * @static + */ + public static function setDefaultConnection($name) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + $instance->setDefaultConnection($name); + } + /** + * Get all of the support drivers. + * + * @return string[] + * @static + */ + public static function supportedDrivers() + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + return $instance->supportedDrivers(); + } + /** + * Get all of the drivers that are actually available. + * + * @return string[] + * @static + */ + public static function availableDrivers() + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + return $instance->availableDrivers(); + } + /** + * Register an extension connection resolver. + * + * @param string $name + * @param callable $resolver + * @return void + * @static + */ + public static function extend($name, $resolver) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + $instance->extend($name, $resolver); + } + /** + * Remove an extension connection resolver. + * + * @param string $name + * @return void + * @static + */ + public static function forgetExtension($name) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + $instance->forgetExtension($name); + } + /** + * Return all of the created connections. + * + * @return array + * @static + */ + public static function getConnections() + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + return $instance->getConnections(); + } + /** + * Set the database reconnector callback. + * + * @param callable $reconnector + * @return void + * @static + */ + public static function setReconnector($reconnector) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + $instance->setReconnector($reconnector); + } + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return \Illuminate\Database\DatabaseManager + * @static + */ + public static function setApplication($app) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + return $instance->setApplication($app); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Database\DatabaseManager::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Database\DatabaseManager::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Database\DatabaseManager::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Database\DatabaseManager::flushMacros(); + } + /** + * Dynamically handle calls to the class. + * + * @param string $method + * @param array $parameters + * @return mixed + * @throws \BadMethodCallException + * @static + */ + public static function macroCall($method, $parameters) + { + /** @var \Illuminate\Database\DatabaseManager $instance */ + return $instance->macroCall($method, $parameters); + } + /** + * Determine if the connected database is a MariaDB database. + * + * @return bool + * @static + */ + public static function isMaria() + { + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->isMaria(); + } + /** + * Get a schema builder instance for the connection. + * + * @return \Illuminate\Database\Schema\MySqlBuilder + * @static + */ + public static function getSchemaBuilder() + { + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getSchemaBuilder(); + } + /** + * Get the schema state for the connection. + * + * @param \Illuminate\Filesystem\Filesystem|null $files + * @param callable|null $processFactory + * @return \Illuminate\Database\Schema\MySqlSchemaState + * @static + */ + public static function getSchemaState($files = null, $processFactory = null) + { + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getSchemaState($files, $processFactory); + } + /** + * Set the query grammar to the default implementation. + * + * @return void + * @static + */ + public static function useDefaultQueryGrammar() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->useDefaultQueryGrammar(); + } + /** + * Set the schema grammar to the default implementation. + * + * @return void + * @static + */ + public static function useDefaultSchemaGrammar() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->useDefaultSchemaGrammar(); + } + /** + * Set the query post processor to the default implementation. + * + * @return void + * @static + */ + public static function useDefaultPostProcessor() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->useDefaultPostProcessor(); + } + /** + * Begin a fluent query against a database table. + * + * @param \Closure|\Illuminate\Database\Query\Builder|string $table + * @param string|null $as + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function table($table, $as = null) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->table($table, $as); + } + /** + * Get a new query builder instance. + * + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function query() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->query(); + } + /** + * Run a select statement and return a single result. + * + * @param string $query + * @param array $bindings + * @param bool $useReadPdo + * @return mixed + * @static + */ + public static function selectOne($query, $bindings = [], $useReadPdo = true) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->selectOne($query, $bindings, $useReadPdo); + } + /** + * Run a select statement and return the first column of the first row. + * + * @param string $query + * @param array $bindings + * @param bool $useReadPdo + * @return mixed + * @throws \Illuminate\Database\MultipleColumnsSelectedException + * @static + */ + public static function scalar($query, $bindings = [], $useReadPdo = true) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->scalar($query, $bindings, $useReadPdo); + } + /** + * Run a select statement against the database. + * + * @param string $query + * @param array $bindings + * @return array + * @static + */ + public static function selectFromWriteConnection($query, $bindings = []) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->selectFromWriteConnection($query, $bindings); + } + /** + * Run a select statement against the database. + * + * @param string $query + * @param array $bindings + * @param bool $useReadPdo + * @return array + * @static + */ + public static function select($query, $bindings = [], $useReadPdo = true) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->select($query, $bindings, $useReadPdo); + } + /** + * Run a select statement against the database and returns a generator. + * + * @param string $query + * @param array $bindings + * @param bool $useReadPdo + * @return \Generator + * @static + */ + public static function cursor($query, $bindings = [], $useReadPdo = true) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->cursor($query, $bindings, $useReadPdo); + } + /** + * Run an insert statement against the database. + * + * @param string $query + * @param array $bindings + * @return bool + * @static + */ + public static function insert($query, $bindings = []) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->insert($query, $bindings); + } + /** + * Run an update statement against the database. + * + * @param string $query + * @param array $bindings + * @return int + * @static + */ + public static function update($query, $bindings = []) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->update($query, $bindings); + } + /** + * Run a delete statement against the database. + * + * @param string $query + * @param array $bindings + * @return int + * @static + */ + public static function delete($query, $bindings = []) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->delete($query, $bindings); + } + /** + * Execute an SQL statement and return the boolean result. + * + * @param string $query + * @param array $bindings + * @return bool + * @static + */ + public static function statement($query, $bindings = []) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->statement($query, $bindings); + } + /** + * Run an SQL statement and get the number of rows affected. + * + * @param string $query + * @param array $bindings + * @return int + * @static + */ + public static function affectingStatement($query, $bindings = []) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->affectingStatement($query, $bindings); + } + /** + * Run a raw, unprepared query against the PDO connection. + * + * @param string $query + * @return bool + * @static + */ + public static function unprepared($query) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->unprepared($query); + } + /** + * Execute the given callback in "dry run" mode. + * + * @param \Closure $callback + * @return array + * @static + */ + public static function pretend($callback) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->pretend($callback); + } + /** + * Bind values to their parameters in the given statement. + * + * @param \PDOStatement $statement + * @param array $bindings + * @return void + * @static + */ + public static function bindValues($statement, $bindings) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->bindValues($statement, $bindings); + } + /** + * Prepare the query bindings for execution. + * + * @param array $bindings + * @return array + * @static + */ + public static function prepareBindings($bindings) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->prepareBindings($bindings); + } + /** + * Log a query in the connection's query log. + * + * @param string $query + * @param array $bindings + * @param float|null $time + * @return void + * @static + */ + public static function logQuery($query, $bindings, $time = null) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->logQuery($query, $bindings, $time); + } + /** + * Register a callback to be invoked when the connection queries for longer than a given amount of time. + * + * @param \DateTimeInterface|\Carbon\CarbonInterval|float|int $threshold + * @param callable $handler + * @return void + * @static + */ + public static function whenQueryingForLongerThan($threshold, $handler) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->whenQueryingForLongerThan($threshold, $handler); + } + /** + * Allow all the query duration handlers to run again, even if they have already run. + * + * @return void + * @static + */ + public static function allowQueryDurationHandlersToRunAgain() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->allowQueryDurationHandlersToRunAgain(); + } + /** + * Get the duration of all run queries in milliseconds. + * + * @return float + * @static + */ + public static function totalQueryDuration() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->totalQueryDuration(); + } + /** + * Reset the duration of all run queries. + * + * @return void + * @static + */ + public static function resetTotalQueryDuration() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->resetTotalQueryDuration(); + } + /** + * Register a hook to be run just before a database query is executed. + * + * @param \Closure $callback + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function beforeExecuting($callback) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->beforeExecuting($callback); + } + /** + * Register a database query listener with the connection. + * + * @param \Closure $callback + * @return void + * @static + */ + public static function listen($callback) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->listen($callback); + } + /** + * Get a new raw query expression. + * + * @param mixed $value + * @return \Illuminate\Database\Query\Expression + * @static + */ + public static function raw($value) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->raw($value); + } + /** + * Determine if the database connection has modified any database records. + * + * @return bool + * @static + */ + public static function hasModifiedRecords() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->hasModifiedRecords(); + } + /** + * Indicate if any records have been modified. + * + * @param bool $value + * @return void + * @static + */ + public static function recordsHaveBeenModified($value = true) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->recordsHaveBeenModified($value); + } + /** + * Set the record modification state. + * + * @param bool $value + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setRecordModificationState($value) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setRecordModificationState($value); + } + /** + * Reset the record modification state. + * + * @return void + * @static + */ + public static function forgetRecordModificationState() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->forgetRecordModificationState(); + } + /** + * Indicate that the connection should use the write PDO connection for reads. + * + * @param bool $value + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function useWriteConnectionWhenReading($value = true) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->useWriteConnectionWhenReading($value); + } + /** + * Is Doctrine available? + * + * @return bool + * @static + */ + public static function isDoctrineAvailable() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->isDoctrineAvailable(); + } + /** + * Indicates whether native alter operations will be used when dropping or renaming columns, even if Doctrine DBAL is installed. + * + * @return bool + * @static + */ + public static function usingNativeSchemaOperations() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->usingNativeSchemaOperations(); + } + /** + * Get a Doctrine Schema Column instance. + * + * @param string $table + * @param string $column + * @return \Doctrine\DBAL\Schema\Column + * @static + */ + public static function getDoctrineColumn($table, $column) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getDoctrineColumn($table, $column); + } + /** + * Get the Doctrine DBAL schema manager for the connection. + * + * @return \Doctrine\DBAL\Schema\AbstractSchemaManager + * @static + */ + public static function getDoctrineSchemaManager() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getDoctrineSchemaManager(); + } + /** + * Get the Doctrine DBAL database connection instance. + * + * @return \Doctrine\DBAL\Connection + * @static + */ + public static function getDoctrineConnection() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getDoctrineConnection(); + } + /** + * Get the current PDO connection. + * + * @return \PDO + * @static + */ + public static function getPdo() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getPdo(); + } + /** + * Get the current PDO connection parameter without executing any reconnect logic. + * + * @return \PDO|\Closure|null + * @static + */ + public static function getRawPdo() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getRawPdo(); + } + /** + * Get the current PDO connection used for reading. + * + * @return \PDO + * @static + */ + public static function getReadPdo() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getReadPdo(); + } + /** + * Get the current read PDO connection parameter without executing any reconnect logic. + * + * @return \PDO|\Closure|null + * @static + */ + public static function getRawReadPdo() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getRawReadPdo(); + } + /** + * Set the PDO connection. + * + * @param \PDO|\Closure|null $pdo + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setPdo($pdo) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setPdo($pdo); + } + /** + * Set the PDO connection used for reading. + * + * @param \PDO|\Closure|null $pdo + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setReadPdo($pdo) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setReadPdo($pdo); + } + /** + * Get the database connection name. + * + * @return string|null + * @static + */ + public static function getName() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getName(); + } + /** + * Get the database connection full name. + * + * @return string|null + * @static + */ + public static function getNameWithReadWriteType() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getNameWithReadWriteType(); + } + /** + * Get an option from the configuration options. + * + * @param string|null $option + * @return mixed + * @static + */ + public static function getConfig($option = null) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getConfig($option); + } + /** + * Get the PDO driver name. + * + * @return string + * @static + */ + public static function getDriverName() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getDriverName(); + } + /** + * Get the query grammar used by the connection. + * + * @return \Illuminate\Database\Query\Grammars\Grammar + * @static + */ + public static function getQueryGrammar() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getQueryGrammar(); + } + /** + * Set the query grammar used by the connection. + * + * @param \Illuminate\Database\Query\Grammars\Grammar $grammar + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setQueryGrammar($grammar) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setQueryGrammar($grammar); + } + /** + * Get the schema grammar used by the connection. + * + * @return \Illuminate\Database\Schema\Grammars\Grammar + * @static + */ + public static function getSchemaGrammar() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getSchemaGrammar(); + } + /** + * Set the schema grammar used by the connection. + * + * @param \Illuminate\Database\Schema\Grammars\Grammar $grammar + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setSchemaGrammar($grammar) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setSchemaGrammar($grammar); + } + /** + * Get the query post processor used by the connection. + * + * @return \Illuminate\Database\Query\Processors\Processor + * @static + */ + public static function getPostProcessor() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getPostProcessor(); + } + /** + * Set the query post processor used by the connection. + * + * @param \Illuminate\Database\Query\Processors\Processor $processor + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setPostProcessor($processor) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setPostProcessor($processor); + } + /** + * Get the event dispatcher used by the connection. + * + * @return \Illuminate\Contracts\Events\Dispatcher + * @static + */ + public static function getEventDispatcher() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getEventDispatcher(); + } + /** + * Set the event dispatcher instance on the connection. + * + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setEventDispatcher($events) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setEventDispatcher($events); + } + /** + * Unset the event dispatcher for this connection. + * + * @return void + * @static + */ + public static function unsetEventDispatcher() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->unsetEventDispatcher(); + } + /** + * Set the transaction manager instance on the connection. + * + * @param \Illuminate\Database\DatabaseTransactionsManager $manager + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setTransactionManager($manager) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setTransactionManager($manager); + } + /** + * Unset the transaction manager for this connection. + * + * @return void + * @static + */ + public static function unsetTransactionManager() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->unsetTransactionManager(); + } + /** + * Determine if the connection is in a "dry run". + * + * @return bool + * @static + */ + public static function pretending() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->pretending(); + } + /** + * Get the connection query log. + * + * @return array + * @static + */ + public static function getQueryLog() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getQueryLog(); + } + /** + * Clear the query log. + * + * @return void + * @static + */ + public static function flushQueryLog() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->flushQueryLog(); + } + /** + * Enable the query log on the connection. + * + * @return void + * @static + */ + public static function enableQueryLog() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->enableQueryLog(); + } + /** + * Disable the query log on the connection. + * + * @return void + * @static + */ + public static function disableQueryLog() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->disableQueryLog(); + } + /** + * Determine whether we're logging queries. + * + * @return bool + * @static + */ + public static function logging() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->logging(); + } + /** + * Get the name of the connected database. + * + * @return string + * @static + */ + public static function getDatabaseName() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getDatabaseName(); + } + /** + * Set the name of the connected database. + * + * @param string $database + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setDatabaseName($database) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setDatabaseName($database); + } + /** + * Set the read / write type of the connection. + * + * @param string|null $readWriteType + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setReadWriteType($readWriteType) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setReadWriteType($readWriteType); + } + /** + * Get the table prefix for the connection. + * + * @return string + * @static + */ + public static function getTablePrefix() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->getTablePrefix(); + } + /** + * Set the table prefix in use by the connection. + * + * @param string $prefix + * @return \Illuminate\Database\MySqlConnection + * @static + */ + public static function setTablePrefix($prefix) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->setTablePrefix($prefix); + } + /** + * Set the table prefix and return the grammar. + * + * @param \Illuminate\Database\Grammar $grammar + * @return \Illuminate\Database\Grammar + * @static + */ + public static function withTablePrefix($grammar) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->withTablePrefix($grammar); + } + /** + * Register a connection resolver. + * + * @param string $driver + * @param \Closure $callback + * @return void + * @static + */ + public static function resolverFor($driver, $callback) + { //Method inherited from \Illuminate\Database\Connection + \Illuminate\Database\MySqlConnection::resolverFor($driver, $callback); + } + /** + * Get the connection resolver for the given driver. + * + * @param string $driver + * @return mixed + * @static + */ + public static function getResolver($driver) + { //Method inherited from \Illuminate\Database\Connection + return \Illuminate\Database\MySqlConnection::getResolver($driver); + } + /** + * Execute a Closure within a transaction. + * + * @param \Closure $callback + * @param int $attempts + * @return mixed + * @throws \Throwable + * @static + */ + public static function transaction($callback, $attempts = 1) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->transaction($callback, $attempts); + } + /** + * Start a new database transaction. + * + * @return void + * @throws \Throwable + * @static + */ + public static function beginTransaction() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->beginTransaction(); + } + /** + * Commit the active database transaction. + * + * @return void + * @throws \Throwable + * @static + */ + public static function commit() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->commit(); + } + /** + * Rollback the active database transaction. + * + * @param int|null $toLevel + * @return void + * @throws \Throwable + * @static + */ + public static function rollBack($toLevel = null) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->rollBack($toLevel); + } + /** + * Get the number of active transactions. + * + * @return int + * @static + */ + public static function transactionLevel() + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + return $instance->transactionLevel(); + } + /** + * Execute the callback after a transaction commits. + * + * @param callable $callback + * @return void + * @throws \RuntimeException + * @static + */ + public static function afterCommit($callback) + { //Method inherited from \Illuminate\Database\Connection + /** @var \Illuminate\Database\MySqlConnection $instance */ + $instance->afterCommit($callback); + } + + } + /** + * + * + * @see \Illuminate\Events\Dispatcher + * @see \Illuminate\Support\Testing\Fakes\EventFake + */ + class Event { + /** + * Register an event listener with the dispatcher. + * + * @param \Closure|string|array $events + * @param \Closure|string|array|null $listener + * @return void + * @static + */ + public static function listen($events, $listener = null) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + $instance->listen($events, $listener); + } + /** + * Determine if a given event has listeners. + * + * @param string $eventName + * @return bool + * @static + */ + public static function hasListeners($eventName) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + return $instance->hasListeners($eventName); + } + /** + * Determine if the given event has any wildcard listeners. + * + * @param string $eventName + * @return bool + * @static + */ + public static function hasWildcardListeners($eventName) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + return $instance->hasWildcardListeners($eventName); + } + /** + * Register an event and payload to be fired later. + * + * @param string $event + * @param object|array $payload + * @return void + * @static + */ + public static function push($event, $payload = []) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + $instance->push($event, $payload); + } + /** + * Flush a set of pushed events. + * + * @param string $event + * @return void + * @static + */ + public static function flush($event) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + $instance->flush($event); + } + /** + * Register an event subscriber with the dispatcher. + * + * @param object|string $subscriber + * @return void + * @static + */ + public static function subscribe($subscriber) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + $instance->subscribe($subscriber); + } + /** + * Fire an event until the first non-null response is returned. + * + * @param string|object $event + * @param mixed $payload + * @return array|null + * @static + */ + public static function until($event, $payload = []) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + return $instance->until($event, $payload); + } + /** + * Fire an event and call the listeners. + * + * @param string|object $event + * @param mixed $payload + * @param bool $halt + * @return array|null + * @static + */ + public static function dispatch($event, $payload = [], $halt = false) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + return $instance->dispatch($event, $payload, $halt); + } + /** + * Get all of the listeners for a given event name. + * + * @param string $eventName + * @return array + * @static + */ + public static function getListeners($eventName) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + return $instance->getListeners($eventName); + } + /** + * Register an event listener with the dispatcher. + * + * @param \Closure|string|array $listener + * @param bool $wildcard + * @return \Closure + * @static + */ + public static function makeListener($listener, $wildcard = false) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + return $instance->makeListener($listener, $wildcard); + } + /** + * Create a class based listener using the IoC container. + * + * @param string $listener + * @param bool $wildcard + * @return \Closure + * @static + */ + public static function createClassListener($listener, $wildcard = false) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + return $instance->createClassListener($listener, $wildcard); + } + /** + * Remove a set of listeners from the dispatcher. + * + * @param string $event + * @return void + * @static + */ + public static function forget($event) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + $instance->forget($event); + } + /** + * Forget all of the pushed listeners. + * + * @return void + * @static + */ + public static function forgetPushed() + { + /** @var \Illuminate\Events\Dispatcher $instance */ + $instance->forgetPushed(); + } + /** + * Set the queue resolver implementation. + * + * @param callable $resolver + * @return \Illuminate\Events\Dispatcher + * @static + */ + public static function setQueueResolver($resolver) + { + /** @var \Illuminate\Events\Dispatcher $instance */ + return $instance->setQueueResolver($resolver); + } + /** + * Gets the raw, unprepared listeners. + * + * @return array + * @static + */ + public static function getRawListeners() + { + /** @var \Illuminate\Events\Dispatcher $instance */ + return $instance->getRawListeners(); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Events\Dispatcher::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Events\Dispatcher::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Events\Dispatcher::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Events\Dispatcher::flushMacros(); + } + /** + * Specify the events that should be dispatched instead of faked. + * + * @param array|string $eventsToDispatch + * @return \Illuminate\Support\Testing\Fakes\EventFake + * @static + */ + public static function except($eventsToDispatch) + { + /** @var \Illuminate\Support\Testing\Fakes\EventFake $instance */ + return $instance->except($eventsToDispatch); + } + /** + * Assert if an event has a listener attached to it. + * + * @param string $expectedEvent + * @param string|array $expectedListener + * @return void + * @static + */ + public static function assertListening($expectedEvent, $expectedListener) + { + /** @var \Illuminate\Support\Testing\Fakes\EventFake $instance */ + $instance->assertListening($expectedEvent, $expectedListener); + } + /** + * Assert if an event was dispatched based on a truth-test callback. + * + * @param string|\Closure $event + * @param callable|int|null $callback + * @return void + * @static + */ + public static function assertDispatched($event, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\EventFake $instance */ + $instance->assertDispatched($event, $callback); + } + /** + * Assert if an event was dispatched a number of times. + * + * @param string $event + * @param int $times + * @return void + * @static + */ + public static function assertDispatchedTimes($event, $times = 1) + { + /** @var \Illuminate\Support\Testing\Fakes\EventFake $instance */ + $instance->assertDispatchedTimes($event, $times); + } + /** + * Determine if an event was dispatched based on a truth-test callback. + * + * @param string|\Closure $event + * @param callable|null $callback + * @return void + * @static + */ + public static function assertNotDispatched($event, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\EventFake $instance */ + $instance->assertNotDispatched($event, $callback); + } + /** + * Assert that no events were dispatched. + * + * @return void + * @static + */ + public static function assertNothingDispatched() + { + /** @var \Illuminate\Support\Testing\Fakes\EventFake $instance */ + $instance->assertNothingDispatched(); + } + /** + * Get all of the events matching a truth-test callback. + * + * @param string $event + * @param callable|null $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function dispatched($event, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\EventFake $instance */ + return $instance->dispatched($event, $callback); + } + /** + * Determine if the given event has been dispatched. + * + * @param string $event + * @return bool + * @static + */ + public static function hasDispatched($event) + { + /** @var \Illuminate\Support\Testing\Fakes\EventFake $instance */ + return $instance->hasDispatched($event); + } + + } + /** + * + * + * @see \Illuminate\Filesystem\Filesystem + */ + class File { + /** + * Determine if a file or directory exists. + * + * @param string $path + * @return bool + * @static + */ + public static function exists($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->exists($path); + } + /** + * Determine if a file or directory is missing. + * + * @param string $path + * @return bool + * @static + */ + public static function missing($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->missing($path); + } + /** + * Get the contents of a file. + * + * @param string $path + * @param bool $lock + * @return string + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + * @static + */ + public static function get($path, $lock = false) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->get($path, $lock); + } + /** + * Get contents of a file with shared access. + * + * @param string $path + * @return string + * @static + */ + public static function sharedGet($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->sharedGet($path); + } + /** + * Get the returned value of a file. + * + * @param string $path + * @param array $data + * @return mixed + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + * @static + */ + public static function getRequire($path, $data = []) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->getRequire($path, $data); + } + /** + * Require the given file once. + * + * @param string $path + * @param array $data + * @return mixed + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + * @static + */ + public static function requireOnce($path, $data = []) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->requireOnce($path, $data); + } + /** + * Get the contents of a file one line at a time. + * + * @param string $path + * @return \Illuminate\Support\LazyCollection + * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException + * @static + */ + public static function lines($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->lines($path); + } + /** + * Get the hash of the file at the given path. + * + * @param string $path + * @param string $algorithm + * @return string + * @static + */ + public static function hash($path, $algorithm = 'md5') + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->hash($path, $algorithm); + } + /** + * Write the contents of a file. + * + * @param string $path + * @param string $contents + * @param bool $lock + * @return int|bool + * @static + */ + public static function put($path, $contents, $lock = false) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->put($path, $contents, $lock); + } + /** + * Write the contents of a file, replacing it atomically if it already exists. + * + * @param string $path + * @param string $content + * @param int|null $mode + * @return void + * @static + */ + public static function replace($path, $content, $mode = null) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + $instance->replace($path, $content, $mode); + } + /** + * Replace a given string within a given file. + * + * @param array|string $search + * @param array|string $replace + * @param string $path + * @return void + * @static + */ + public static function replaceInFile($search, $replace, $path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + $instance->replaceInFile($search, $replace, $path); + } + /** + * Prepend to a file. + * + * @param string $path + * @param string $data + * @return int + * @static + */ + public static function prepend($path, $data) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->prepend($path, $data); + } + /** + * Append to a file. + * + * @param string $path + * @param string $data + * @return int + * @static + */ + public static function append($path, $data) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->append($path, $data); + } + /** + * Get or set UNIX mode of a file or directory. + * + * @param string $path + * @param int|null $mode + * @return mixed + * @static + */ + public static function chmod($path, $mode = null) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->chmod($path, $mode); + } + /** + * Delete the file at a given path. + * + * @param string|array $paths + * @return bool + * @static + */ + public static function delete($paths) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->delete($paths); + } + /** + * Move a file to a new location. + * + * @param string $path + * @param string $target + * @return bool + * @static + */ + public static function move($path, $target) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->move($path, $target); + } + /** + * Copy a file to a new location. + * + * @param string $path + * @param string $target + * @return bool + * @static + */ + public static function copy($path, $target) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->copy($path, $target); + } + /** + * Create a symlink to the target file or directory. On Windows, a hard link is created if the target is a file. + * + * @param string $target + * @param string $link + * @return void + * @static + */ + public static function link($target, $link) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + $instance->link($target, $link); + } + /** + * Create a relative symlink to the target file or directory. + * + * @param string $target + * @param string $link + * @return void + * @throws \RuntimeException + * @static + */ + public static function relativeLink($target, $link) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + $instance->relativeLink($target, $link); + } + /** + * Extract the file name from a file path. + * + * @param string $path + * @return string + * @static + */ + public static function name($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->name($path); + } + /** + * Extract the trailing name component from a file path. + * + * @param string $path + * @return string + * @static + */ + public static function basename($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->basename($path); + } + /** + * Extract the parent directory from a file path. + * + * @param string $path + * @return string + * @static + */ + public static function dirname($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->dirname($path); + } + /** + * Extract the file extension from a file path. + * + * @param string $path + * @return string + * @static + */ + public static function extension($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->extension($path); + } + /** + * Guess the file extension from the mime-type of a given file. + * + * @param string $path + * @return string|null + * @throws \RuntimeException + * @static + */ + public static function guessExtension($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->guessExtension($path); + } + /** + * Get the file type of a given file. + * + * @param string $path + * @return string + * @static + */ + public static function type($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->type($path); + } + /** + * Get the mime-type of a given file. + * + * @param string $path + * @return string|false + * @static + */ + public static function mimeType($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->mimeType($path); + } + /** + * Get the file size of a given file. + * + * @param string $path + * @return int + * @static + */ + public static function size($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->size($path); + } + /** + * Get the file's last modification time. + * + * @param string $path + * @return int + * @static + */ + public static function lastModified($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->lastModified($path); + } + /** + * Determine if the given path is a directory. + * + * @param string $directory + * @return bool + * @static + */ + public static function isDirectory($directory) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->isDirectory($directory); + } + /** + * Determine if the given path is a directory that does not contain any other files or directories. + * + * @param string $directory + * @param bool $ignoreDotFiles + * @return bool + * @static + */ + public static function isEmptyDirectory($directory, $ignoreDotFiles = false) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->isEmptyDirectory($directory, $ignoreDotFiles); + } + /** + * Determine if the given path is readable. + * + * @param string $path + * @return bool + * @static + */ + public static function isReadable($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->isReadable($path); + } + /** + * Determine if the given path is writable. + * + * @param string $path + * @return bool + * @static + */ + public static function isWritable($path) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->isWritable($path); + } + /** + * Determine if two files are the same by comparing their hashes. + * + * @param string $firstFile + * @param string $secondFile + * @return bool + * @static + */ + public static function hasSameHash($firstFile, $secondFile) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->hasSameHash($firstFile, $secondFile); + } + /** + * Determine if the given path is a file. + * + * @param string $file + * @return bool + * @static + */ + public static function isFile($file) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->isFile($file); + } + /** + * Find path names matching a given pattern. + * + * @param string $pattern + * @param int $flags + * @return array + * @static + */ + public static function glob($pattern, $flags = 0) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->glob($pattern, $flags); + } + /** + * Get an array of all files in a directory. + * + * @param string $directory + * @param bool $hidden + * @return \Symfony\Component\Finder\SplFileInfo[] + * @static + */ + public static function files($directory, $hidden = false) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->files($directory, $hidden); + } + /** + * Get all of the files from the given directory (recursive). + * + * @param string $directory + * @param bool $hidden + * @return \Symfony\Component\Finder\SplFileInfo[] + * @static + */ + public static function allFiles($directory, $hidden = false) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->allFiles($directory, $hidden); + } + /** + * Get all of the directories within a given directory. + * + * @param string $directory + * @return array + * @static + */ + public static function directories($directory) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->directories($directory); + } + /** + * Ensure a directory exists. + * + * @param string $path + * @param int $mode + * @param bool $recursive + * @return void + * @static + */ + public static function ensureDirectoryExists($path, $mode = 493, $recursive = true) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + $instance->ensureDirectoryExists($path, $mode, $recursive); + } + /** + * Create a directory. + * + * @param string $path + * @param int $mode + * @param bool $recursive + * @param bool $force + * @return bool + * @static + */ + public static function makeDirectory($path, $mode = 493, $recursive = false, $force = false) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->makeDirectory($path, $mode, $recursive, $force); + } + /** + * Move a directory. + * + * @param string $from + * @param string $to + * @param bool $overwrite + * @return bool + * @static + */ + public static function moveDirectory($from, $to, $overwrite = false) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->moveDirectory($from, $to, $overwrite); + } + /** + * Copy a directory from one location to another. + * + * @param string $directory + * @param string $destination + * @param int|null $options + * @return bool + * @static + */ + public static function copyDirectory($directory, $destination, $options = null) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->copyDirectory($directory, $destination, $options); + } + /** + * Recursively delete a directory. + * + * The directory itself may be optionally preserved. + * + * @param string $directory + * @param bool $preserve + * @return bool + * @static + */ + public static function deleteDirectory($directory, $preserve = false) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->deleteDirectory($directory, $preserve); + } + /** + * Remove all of the directories within a given directory. + * + * @param string $directory + * @return bool + * @static + */ + public static function deleteDirectories($directory) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->deleteDirectories($directory); + } + /** + * Empty the specified directory of all files and folders. + * + * @param string $directory + * @return bool + * @static + */ + public static function cleanDirectory($directory) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->cleanDirectory($directory); + } + /** + * Apply the callback if the given "value" is (or resolves to) truthy. + * + * @template TWhenParameter + * @template TWhenReturnType + * @param \Illuminate\Filesystem\(\Closure($this): TWhenParameter)|TWhenParameter|null $value + * @param \Illuminate\Filesystem\(callable($this, TWhenParameter): TWhenReturnType)|null $callback + * @param \Illuminate\Filesystem\(callable($this, TWhenParameter): TWhenReturnType)|null $default + * @return $this|\Illuminate\Filesystem\TWhenReturnType + * @static + */ + public static function when($value = null, $callback = null, $default = null) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->when($value, $callback, $default); + } + /** + * Apply the callback if the given "value" is (or resolves to) falsy. + * + * @template TUnlessParameter + * @template TUnlessReturnType + * @param \Illuminate\Filesystem\(\Closure($this): TUnlessParameter)|TUnlessParameter|null $value + * @param \Illuminate\Filesystem\(callable($this, TUnlessParameter): TUnlessReturnType)|null $callback + * @param \Illuminate\Filesystem\(callable($this, TUnlessParameter): TUnlessReturnType)|null $default + * @return $this|\Illuminate\Filesystem\TUnlessReturnType + * @static + */ + public static function unless($value = null, $callback = null, $default = null) + { + /** @var \Illuminate\Filesystem\Filesystem $instance */ + return $instance->unless($value, $callback, $default); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Filesystem\Filesystem::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Filesystem\Filesystem::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Filesystem\Filesystem::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Filesystem\Filesystem::flushMacros(); + } + + } + /** + * + * + * @see \Illuminate\Auth\Access\Gate + */ + class Gate { + /** + * Determine if a given ability has been defined. + * + * @param string|array $ability + * @return bool + * @static + */ + public static function has($ability) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->has($ability); + } + /** + * Perform an on-demand authorization check. Throw an authorization exception if the condition or callback is false. + * + * @param \Illuminate\Auth\Access\Response|\Closure|bool $condition + * @param string|null $message + * @param string|null $code + * @return \Illuminate\Auth\Access\Response + * @throws \Illuminate\Auth\Access\AuthorizationException + * @static + */ + public static function allowIf($condition, $message = null, $code = null) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->allowIf($condition, $message, $code); + } + /** + * Perform an on-demand authorization check. Throw an authorization exception if the condition or callback is true. + * + * @param \Illuminate\Auth\Access\Response|\Closure|bool $condition + * @param string|null $message + * @param string|null $code + * @return \Illuminate\Auth\Access\Response + * @throws \Illuminate\Auth\Access\AuthorizationException + * @static + */ + public static function denyIf($condition, $message = null, $code = null) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->denyIf($condition, $message, $code); + } + /** + * Define a new ability. + * + * @param string $ability + * @param callable|array|string $callback + * @return \Illuminate\Auth\Access\Gate + * @throws \InvalidArgumentException + * @static + */ + public static function define($ability, $callback) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->define($ability, $callback); + } + /** + * Define abilities for a resource. + * + * @param string $name + * @param string $class + * @param array|null $abilities + * @return \Illuminate\Auth\Access\Gate + * @static + */ + public static function resource($name, $class, $abilities = null) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->resource($name, $class, $abilities); + } + /** + * Define a policy class for a given class type. + * + * @param string $class + * @param string $policy + * @return \Illuminate\Auth\Access\Gate + * @static + */ + public static function policy($class, $policy) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->policy($class, $policy); + } + /** + * Register a callback to run before all Gate checks. + * + * @param callable $callback + * @return \Illuminate\Auth\Access\Gate + * @static + */ + public static function before($callback) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->before($callback); + } + /** + * Register a callback to run after all Gate checks. + * + * @param callable $callback + * @return \Illuminate\Auth\Access\Gate + * @static + */ + public static function after($callback) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->after($callback); + } + /** + * Determine if the given ability should be granted for the current user. + * + * @param string $ability + * @param array|mixed $arguments + * @return bool + * @static + */ + public static function allows($ability, $arguments = []) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->allows($ability, $arguments); + } + /** + * Determine if the given ability should be denied for the current user. + * + * @param string $ability + * @param array|mixed $arguments + * @return bool + * @static + */ + public static function denies($ability, $arguments = []) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->denies($ability, $arguments); + } + /** + * Determine if all of the given abilities should be granted for the current user. + * + * @param \Illuminate\Auth\Access\iterable|string $abilities + * @param array|mixed $arguments + * @return bool + * @static + */ + public static function check($abilities, $arguments = []) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->check($abilities, $arguments); + } + /** + * Determine if any one of the given abilities should be granted for the current user. + * + * @param \Illuminate\Auth\Access\iterable|string $abilities + * @param array|mixed $arguments + * @return bool + * @static + */ + public static function any($abilities, $arguments = []) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->any($abilities, $arguments); + } + /** + * Determine if all of the given abilities should be denied for the current user. + * + * @param \Illuminate\Auth\Access\iterable|string $abilities + * @param array|mixed $arguments + * @return bool + * @static + */ + public static function none($abilities, $arguments = []) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->none($abilities, $arguments); + } + /** + * Determine if the given ability should be granted for the current user. + * + * @param string $ability + * @param array|mixed $arguments + * @return \Illuminate\Auth\Access\Response + * @throws \Illuminate\Auth\Access\AuthorizationException + * @static + */ + public static function authorize($ability, $arguments = []) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->authorize($ability, $arguments); + } + /** + * Inspect the user for the given ability. + * + * @param string $ability + * @param array|mixed $arguments + * @return \Illuminate\Auth\Access\Response + * @static + */ + public static function inspect($ability, $arguments = []) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->inspect($ability, $arguments); + } + /** + * Get the raw result from the authorization callback. + * + * @param string $ability + * @param array|mixed $arguments + * @return mixed + * @throws \Illuminate\Auth\Access\AuthorizationException + * @static + */ + public static function raw($ability, $arguments = []) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->raw($ability, $arguments); + } + /** + * Get a policy instance for a given class. + * + * @param object|string $class + * @return mixed + * @static + */ + public static function getPolicyFor($class) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->getPolicyFor($class); + } + /** + * Specify a callback to be used to guess policy names. + * + * @param callable $callback + * @return \Illuminate\Auth\Access\Gate + * @static + */ + public static function guessPolicyNamesUsing($callback) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->guessPolicyNamesUsing($callback); + } + /** + * Build a policy class instance of the given type. + * + * @param object|string $class + * @return mixed + * @throws \Illuminate\Contracts\Container\BindingResolutionException + * @static + */ + public static function resolvePolicy($class) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->resolvePolicy($class); + } + /** + * Get a gate instance for the given user. + * + * @param \Illuminate\Contracts\Auth\Authenticatable|mixed $user + * @return static + * @static + */ + public static function forUser($user) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->forUser($user); + } + /** + * Get all of the defined abilities. + * + * @return array + * @static + */ + public static function abilities() + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->abilities(); + } + /** + * Get all of the defined policies. + * + * @return array + * @static + */ + public static function policies() + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->policies(); + } + /** + * Set the container instance used by the gate. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return \Illuminate\Auth\Access\Gate + * @static + */ + public static function setContainer($container) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->setContainer($container); + } + /** + * Deny with a HTTP status code. + * + * @param int $status + * @param string|null $message + * @param int|null $code + * @return \Illuminate\Auth\Access\Response + * @static + */ + public static function denyWithStatus($status, $message = null, $code = null) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->denyWithStatus($status, $message, $code); + } + /** + * Deny with a 404 HTTP status code. + * + * @param string|null $message + * @param int|null $code + * @return \Illuminate\Auth\Access\Response + * @static + */ + public static function denyAsNotFound($message = null, $code = null) + { + /** @var \Illuminate\Auth\Access\Gate $instance */ + return $instance->denyAsNotFound($message, $code); + } + + } + /** + * + * + * @see \Illuminate\Hashing\HashManager + * @see \Illuminate\Hashing\AbstractHasher + */ + class Hash { + /** + * Create an instance of the Bcrypt hash Driver. + * + * @return \Illuminate\Hashing\BcryptHasher + * @static + */ + public static function createBcryptDriver() + { + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->createBcryptDriver(); + } + /** + * Create an instance of the Argon2i hash Driver. + * + * @return \Illuminate\Hashing\ArgonHasher + * @static + */ + public static function createArgonDriver() + { + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->createArgonDriver(); + } + /** + * Create an instance of the Argon2id hash Driver. + * + * @return \Illuminate\Hashing\Argon2IdHasher + * @static + */ + public static function createArgon2idDriver() + { + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->createArgon2idDriver(); + } + /** + * Get information about the given hashed value. + * + * @param string $hashedValue + * @return array + * @static + */ + public static function info($hashedValue) + { + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->info($hashedValue); + } + /** + * Hash the given value. + * + * @param string $value + * @param array $options + * @return string + * @static + */ + public static function make($value, $options = []) + { + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->make($value, $options); + } + /** + * Check the given plain value against a hash. + * + * @param string $value + * @param string $hashedValue + * @param array $options + * @return bool + * @static + */ + public static function check($value, $hashedValue, $options = []) + { + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->check($value, $hashedValue, $options); + } + /** + * Check if the given hash has been hashed using the given options. + * + * @param string $hashedValue + * @param array $options + * @return bool + * @static + */ + public static function needsRehash($hashedValue, $options = []) + { + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->needsRehash($hashedValue, $options); + } + /** + * Get the default driver name. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Get a driver instance. + * + * @param string|null $driver + * @return mixed + * @throws \InvalidArgumentException + * @static + */ + public static function driver($driver = null) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->driver($driver); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Hashing\HashManager + * @static + */ + public static function extend($driver, $callback) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Get all of the created "drivers". + * + * @return array + * @static + */ + public static function getDrivers() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->getDrivers(); + } + /** + * Get the container instance used by the manager. + * + * @return \Illuminate\Contracts\Container\Container + * @static + */ + public static function getContainer() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->getContainer(); + } + /** + * Set the container instance used by the manager. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return \Illuminate\Hashing\HashManager + * @static + */ + public static function setContainer($container) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->setContainer($container); + } + /** + * Forget all of the resolved driver instances. + * + * @return \Illuminate\Hashing\HashManager + * @static + */ + public static function forgetDrivers() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Hashing\HashManager $instance */ + return $instance->forgetDrivers(); + } + + } + /** + * + * + * @method static \Illuminate\Http\Client\PendingRequest baseUrl(string $url) + * @method static \Illuminate\Http\Client\PendingRequest withBody(string $content, string $contentType) + * @method static \Illuminate\Http\Client\PendingRequest asJson() + * @method static \Illuminate\Http\Client\PendingRequest asForm() + * @method static \Illuminate\Http\Client\PendingRequest attach(string|array $name, string|resource $contents = '', string|null $filename = null, array $headers = []) + * @method static \Illuminate\Http\Client\PendingRequest asMultipart() + * @method static \Illuminate\Http\Client\PendingRequest bodyFormat(string $format) + * @method static \Illuminate\Http\Client\PendingRequest contentType(string $contentType) + * @method static \Illuminate\Http\Client\PendingRequest acceptJson() + * @method static \Illuminate\Http\Client\PendingRequest accept(string $contentType) + * @method static \Illuminate\Http\Client\PendingRequest withHeaders(array $headers) + * @method static \Illuminate\Http\Client\PendingRequest withBasicAuth(string $username, string $password) + * @method static \Illuminate\Http\Client\PendingRequest withDigestAuth(string $username, string $password) + * @method static \Illuminate\Http\Client\PendingRequest withToken(string $token, string $type = 'Bearer') + * @method static \Illuminate\Http\Client\PendingRequest withUserAgent(string $userAgent) + * @method static \Illuminate\Http\Client\PendingRequest withUrlParameters(array $parameters = []) + * @method static \Illuminate\Http\Client\PendingRequest withCookies(array $cookies, string $domain) + * @method static \Illuminate\Http\Client\PendingRequest maxRedirects(int $max) + * @method static \Illuminate\Http\Client\PendingRequest withoutRedirecting() + * @method static \Illuminate\Http\Client\PendingRequest withoutVerifying() + * @method static \Illuminate\Http\Client\PendingRequest sink(string|resource $to) + * @method static \Illuminate\Http\Client\PendingRequest timeout(int $seconds) + * @method static \Illuminate\Http\Client\PendingRequest connectTimeout(int $seconds) + * @method static \Illuminate\Http\Client\PendingRequest retry(int $times, int $sleepMilliseconds = 0, callable|null $when = null, bool $throw = true) + * @method static \Illuminate\Http\Client\PendingRequest withOptions(array $options) + * @method static \Illuminate\Http\Client\PendingRequest withMiddleware(callable $middleware) + * @method static \Illuminate\Http\Client\PendingRequest beforeSending(callable $callback) + * @method static \Illuminate\Http\Client\PendingRequest throw(callable|null $callback = null) + * @method static \Illuminate\Http\Client\PendingRequest throwIf(callable|bool $condition, callable|null $throwCallback = null) + * @method static \Illuminate\Http\Client\PendingRequest throwUnless(bool $condition) + * @method static \Illuminate\Http\Client\PendingRequest dump() + * @method static \Illuminate\Http\Client\PendingRequest dd() + * @method static \Illuminate\Http\Client\Response get(string $url, array|string|null $query = null) + * @method static \Illuminate\Http\Client\Response head(string $url, array|string|null $query = null) + * @method static \Illuminate\Http\Client\Response post(string $url, array $data = []) + * @method static \Illuminate\Http\Client\Response patch(string $url, array $data = []) + * @method static \Illuminate\Http\Client\Response put(string $url, array $data = []) + * @method static \Illuminate\Http\Client\Response delete(string $url, array $data = []) + * @method static array pool(callable $callback) + * @method static \Illuminate\Http\Client\Response send(string $method, string $url, array $options = []) + * @method static \GuzzleHttp\Client buildClient() + * @method static \GuzzleHttp\Client createClient(\GuzzleHttp\HandlerStack $handlerStack) + * @method static \GuzzleHttp\HandlerStack buildHandlerStack() + * @method static \GuzzleHttp\HandlerStack pushHandlers(\GuzzleHttp\HandlerStack $handlerStack) + * @method static \Closure buildBeforeSendingHandler() + * @method static \Closure buildRecorderHandler() + * @method static \Closure buildStubHandler() + * @method static \GuzzleHttp\Psr7\RequestInterface runBeforeSendingCallbacks(\GuzzleHttp\Psr7\RequestInterface $request, array $options) + * @method static array mergeOptions(array ...$options) + * @method static \Illuminate\Http\Client\PendingRequest stub(callable $callback) + * @method static \Illuminate\Http\Client\PendingRequest async(bool $async = true) + * @method static \GuzzleHttp\Promise\PromiseInterface|null getPromise() + * @method static \Illuminate\Http\Client\PendingRequest setClient(\GuzzleHttp\Client $client) + * @method static \Illuminate\Http\Client\PendingRequest setHandler(callable $handler) + * @method static array getOptions() + * @method static \Illuminate\Http\Client\PendingRequest|mixed when(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) + * @method static \Illuminate\Http\Client\PendingRequest|mixed unless(\Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) + * @see \Illuminate\Http\Client\Factory + */ + class Http { + /** + * Create a new response instance for use during stubbing. + * + * @param array|string|null $body + * @param int $status + * @param array $headers + * @return \GuzzleHttp\Promise\PromiseInterface + * @static + */ + public static function response($body = null, $status = 200, $headers = []) + { + return \Illuminate\Http\Client\Factory::response($body, $status, $headers); + } + /** + * Get an invokable object that returns a sequence of responses in order for use during stubbing. + * + * @param array $responses + * @return \Illuminate\Http\Client\ResponseSequence + * @static + */ + public static function sequence($responses = []) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + return $instance->sequence($responses); + } + /** + * Register a stub callable that will intercept requests and be able to return stub responses. + * + * @param callable|array|null $callback + * @return \Illuminate\Http\Client\Factory + * @static + */ + public static function fake($callback = null) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + return $instance->fake($callback); + } + /** + * Register a response sequence for the given URL pattern. + * + * @param string $url + * @return \Illuminate\Http\Client\ResponseSequence + * @static + */ + public static function fakeSequence($url = '*') + { + /** @var \Illuminate\Http\Client\Factory $instance */ + return $instance->fakeSequence($url); + } + /** + * Stub the given URL using the given callback. + * + * @param string $url + * @param \Illuminate\Http\Client\Response|\GuzzleHttp\Promise\PromiseInterface|callable $callback + * @return \Illuminate\Http\Client\Factory + * @static + */ + public static function stubUrl($url, $callback) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + return $instance->stubUrl($url, $callback); + } + /** + * Indicate that an exception should be thrown if any request is not faked. + * + * @param bool $prevent + * @return \Illuminate\Http\Client\Factory + * @static + */ + public static function preventStrayRequests($prevent = true) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + return $instance->preventStrayRequests($prevent); + } + /** + * Indicate that an exception should not be thrown if any request is not faked. + * + * @return \Illuminate\Http\Client\Factory + * @static + */ + public static function allowStrayRequests() + { + /** @var \Illuminate\Http\Client\Factory $instance */ + return $instance->allowStrayRequests(); + } + /** + * Record a request response pair. + * + * @param \Illuminate\Http\Client\Request $request + * @param \Illuminate\Http\Client\Response $response + * @return void + * @static + */ + public static function recordRequestResponsePair($request, $response) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + $instance->recordRequestResponsePair($request, $response); + } + /** + * Assert that a request / response pair was recorded matching a given truth test. + * + * @param callable $callback + * @return void + * @static + */ + public static function assertSent($callback) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + $instance->assertSent($callback); + } + /** + * Assert that the given request was sent in the given order. + * + * @param array $callbacks + * @return void + * @static + */ + public static function assertSentInOrder($callbacks) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + $instance->assertSentInOrder($callbacks); + } + /** + * Assert that a request / response pair was not recorded matching a given truth test. + * + * @param callable $callback + * @return void + * @static + */ + public static function assertNotSent($callback) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + $instance->assertNotSent($callback); + } + /** + * Assert that no request / response pair was recorded. + * + * @return void + * @static + */ + public static function assertNothingSent() + { + /** @var \Illuminate\Http\Client\Factory $instance */ + $instance->assertNothingSent(); + } + /** + * Assert how many requests have been recorded. + * + * @param int $count + * @return void + * @static + */ + public static function assertSentCount($count) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + $instance->assertSentCount($count); + } + /** + * Assert that every created response sequence is empty. + * + * @return void + * @static + */ + public static function assertSequencesAreEmpty() + { + /** @var \Illuminate\Http\Client\Factory $instance */ + $instance->assertSequencesAreEmpty(); + } + /** + * Get a collection of the request / response pairs matching the given truth test. + * + * @param callable $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function recorded($callback = null) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + return $instance->recorded($callback); + } + /** + * Get the current event dispatcher implementation. + * + * @return \Illuminate\Contracts\Events\Dispatcher|null + * @static + */ + public static function getDispatcher() + { + /** @var \Illuminate\Http\Client\Factory $instance */ + return $instance->getDispatcher(); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Http\Client\Factory::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Http\Client\Factory::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Http\Client\Factory::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Http\Client\Factory::flushMacros(); + } + /** + * Dynamically handle calls to the class. + * + * @param string $method + * @param array $parameters + * @return mixed + * @throws \BadMethodCallException + * @static + */ + public static function macroCall($method, $parameters) + { + /** @var \Illuminate\Http\Client\Factory $instance */ + return $instance->macroCall($method, $parameters); + } + + } + /** + * + * + * @see \Illuminate\Translation\Translator + */ + class Lang { + /** + * Set translation. + * + * @param string $key + * @param mixed $value + * @param null $locale + * @return void + * @static + */ + public static function set($key, $value, $locale = null) + { + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->set($key, $value, $locale); + } + /** + * + * + * @static + */ + public static function replace($items, $locale = null) + { + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->replace($items, $locale); + } + /** + * Determine if a translation exists for a given locale. + * + * @param string $key + * @param string|null $locale + * @return bool + * @static + */ + public static function hasForLocale($key, $locale = null) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->hasForLocale($key, $locale); + } + /** + * Determine if a translation exists. + * + * @param string $key + * @param string|null $locale + * @param bool $fallback + * @return bool + * @static + */ + public static function has($key, $locale = null, $fallback = true) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->has($key, $locale, $fallback); + } + /** + * Get the translation for the given key. + * + * @param string $key + * @param array $replace + * @param string|null $locale + * @param bool $fallback + * @return string|array + * @static + */ + public static function get($key, $replace = [], $locale = null, $fallback = true) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->get($key, $replace, $locale, $fallback); + } + /** + * Get a translation according to an integer value. + * + * @param string $key + * @param \Countable|int|array $number + * @param array $replace + * @param string|null $locale + * @return string + * @static + */ + public static function choice($key, $number, $replace = [], $locale = null) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->choice($key, $number, $replace, $locale); + } + /** + * Add translation lines to the given locale. + * + * @param array $lines + * @param string $locale + * @param string $namespace + * @return void + * @static + */ + public static function addLines($lines, $locale, $namespace = '*') + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->addLines($lines, $locale, $namespace); + } + /** + * Load the specified language group. + * + * @param string $namespace + * @param string $group + * @param string $locale + * @return void + * @static + */ + public static function load($namespace, $group, $locale) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->load($namespace, $group, $locale); + } + /** + * Add a new namespace to the loader. + * + * @param string $namespace + * @param string $hint + * @return void + * @static + */ + public static function addNamespace($namespace, $hint) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->addNamespace($namespace, $hint); + } + /** + * Add a new JSON path to the loader. + * + * @param string $path + * @return void + * @static + */ + public static function addJsonPath($path) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->addJsonPath($path); + } + /** + * Parse a key into namespace, group, and item. + * + * @param string $key + * @return array + * @static + */ + public static function parseKey($key) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->parseKey($key); + } + /** + * Specify a callback that should be invoked to determined the applicable locale array. + * + * @param callable $callback + * @return void + * @static + */ + public static function determineLocalesUsing($callback) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->determineLocalesUsing($callback); + } + /** + * Get the message selector instance. + * + * @return \Illuminate\Translation\MessageSelector + * @static + */ + public static function getSelector() + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->getSelector(); + } + /** + * Set the message selector instance. + * + * @param \Illuminate\Translation\MessageSelector $selector + * @return void + * @static + */ + public static function setSelector($selector) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->setSelector($selector); + } + /** + * Get the language line loader implementation. + * + * @return \Illuminate\Contracts\Translation\Loader + * @static + */ + public static function getLoader() + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->getLoader(); + } + /** + * Get the default locale being used. + * + * @return string + * @static + */ + public static function locale() + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->locale(); + } + /** + * Get the default locale being used. + * + * @return string + * @static + */ + public static function getLocale() + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->getLocale(); + } + /** + * Set the default locale. + * + * @param string $locale + * @return void + * @throws \InvalidArgumentException + * @static + */ + public static function setLocale($locale) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->setLocale($locale); + } + /** + * Get the fallback locale being used. + * + * @return string + * @static + */ + public static function getFallback() + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + return $instance->getFallback(); + } + /** + * Set the fallback locale being used. + * + * @param string $fallback + * @return void + * @static + */ + public static function setFallback($fallback) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->setFallback($fallback); + } + /** + * Set the loaded translation groups. + * + * @param array $loaded + * @return void + * @static + */ + public static function setLoaded($loaded) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->setLoaded($loaded); + } + /** + * Add a handler to be executed in order to format a given class to a string during translation replacements. + * + * @param callable|string $class + * @param callable|null $handler + * @return void + * @static + */ + public static function stringable($class, $handler = null) + { //Method inherited from \Illuminate\Translation\Translator + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->stringable($class, $handler); + } + /** + * Set the parsed value of a key. + * + * @param string $key + * @param array $parsed + * @return void + * @static + */ + public static function setParsedKey($key, $parsed) + { //Method inherited from \Illuminate\Support\NamespacedItemResolver + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->setParsedKey($key, $parsed); + } + /** + * Flush the cache of parsed keys. + * + * @return void + * @static + */ + public static function flushParsedKeys() + { //Method inherited from \Illuminate\Support\NamespacedItemResolver + /** @var \App\Helpers\Language\NinjaTranslator $instance */ + $instance->flushParsedKeys(); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { //Method inherited from \Illuminate\Translation\Translator + \App\Helpers\Language\NinjaTranslator::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { //Method inherited from \Illuminate\Translation\Translator + \App\Helpers\Language\NinjaTranslator::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { //Method inherited from \Illuminate\Translation\Translator + return \App\Helpers\Language\NinjaTranslator::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { //Method inherited from \Illuminate\Translation\Translator + \App\Helpers\Language\NinjaTranslator::flushMacros(); + } + + } + /** + * + * + * @method static void write(string $level, \Illuminate\Contracts\Support\Arrayable|\Illuminate\Contracts\Support\Jsonable|\Illuminate\Support\Stringable|array|string $message, array $context = []) + * @method static \Illuminate\Log\Logger withContext(array $context = []) + * @method static \Illuminate\Log\Logger withoutContext() + * @method static void listen(\Closure $callback) + * @method static \Psr\Log\LoggerInterface getLogger() + * @method static \Illuminate\Contracts\Events\Dispatcher getEventDispatcher() + * @method static void setEventDispatcher(\Illuminate\Contracts\Events\Dispatcher $dispatcher) + * @see \Illuminate\Log\LogManager + */ + class Log { + /** + * Build an on-demand log channel. + * + * @param array $config + * @return \Psr\Log\LoggerInterface + * @static + */ + public static function build($config) + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->build($config); + } + /** + * Create a new, on-demand aggregate logger instance. + * + * @param array $channels + * @param string|null $channel + * @return \Psr\Log\LoggerInterface + * @static + */ + public static function stack($channels, $channel = null) + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->stack($channels, $channel); + } + /** + * Get a log channel instance. + * + * @param string|null $channel + * @return \Psr\Log\LoggerInterface + * @static + */ + public static function channel($channel = null) + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->channel($channel); + } + /** + * Get a log driver instance. + * + * @param string|null $driver + * @return \Psr\Log\LoggerInterface + * @static + */ + public static function driver($driver = null) + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->driver($driver); + } + /** + * Share context across channels and stacks. + * + * @param array $context + * @return \Illuminate\Log\LogManager + * @static + */ + public static function shareContext($context) + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->shareContext($context); + } + /** + * The context shared across channels and stacks. + * + * @return array + * @static + */ + public static function sharedContext() + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->sharedContext(); + } + /** + * Flush the shared context. + * + * @return \Illuminate\Log\LogManager + * @static + */ + public static function flushSharedContext() + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->flushSharedContext(); + } + /** + * Get the default log driver name. + * + * @return string|null + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Set the default log driver name. + * + * @param string $name + * @return void + * @static + */ + public static function setDefaultDriver($name) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->setDefaultDriver($name); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Log\LogManager + * @static + */ + public static function extend($driver, $callback) + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Unset the given channel instance. + * + * @param string|null $driver + * @return void + * @static + */ + public static function forgetChannel($driver = null) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->forgetChannel($driver); + } + /** + * Get all of the resolved log channels. + * + * @return array + * @static + */ + public static function getChannels() + { + /** @var \Illuminate\Log\LogManager $instance */ + return $instance->getChannels(); + } + /** + * System is unusable. + * + * @param string $message + * @param array $context + * @return void + * @static + */ + public static function emergency($message, $context = []) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->emergency($message, $context); + } + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string $message + * @param array $context + * @return void + * @static + */ + public static function alert($message, $context = []) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->alert($message, $context); + } + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string $message + * @param array $context + * @return void + * @static + */ + public static function critical($message, $context = []) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->critical($message, $context); + } + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string $message + * @param array $context + * @return void + * @static + */ + public static function error($message, $context = []) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->error($message, $context); + } + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string $message + * @param array $context + * @return void + * @static + */ + public static function warning($message, $context = []) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->warning($message, $context); + } + /** + * Normal but significant events. + * + * @param string $message + * @param array $context + * @return void + * @static + */ + public static function notice($message, $context = []) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->notice($message, $context); + } + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string $message + * @param array $context + * @return void + * @static + */ + public static function info($message, $context = []) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->info($message, $context); + } + /** + * Detailed debug information. + * + * @param string $message + * @param array $context + * @return void + * @static + */ + public static function debug($message, $context = []) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->debug($message, $context); + } + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string $message + * @param array $context + * @return void + * @static + */ + public static function log($level, $message, $context = []) + { + /** @var \Illuminate\Log\LogManager $instance */ + $instance->log($level, $message, $context); + } + + } + /** + * + * + * @method static void alwaysFrom(string $address, string|null $name = null) + * @method static void alwaysReplyTo(string $address, string|null $name = null) + * @method static void alwaysReturnPath(string $address) + * @method static void alwaysTo(string $address, string|null $name = null) + * @method static \Illuminate\Mail\SentMessage|null html(string $html, mixed $callback) + * @method static \Illuminate\Mail\SentMessage|null plain(string $view, array $data, mixed $callback) + * @method static string render(string|array $view, array $data = []) + * @method static mixed onQueue(string $queue, \Illuminate\Contracts\Mail\Mailable $view) + * @method static mixed queueOn(string $queue, \Illuminate\Contracts\Mail\Mailable $view) + * @method static mixed laterOn(string $queue, \DateTimeInterface|\DateInterval|int $delay, \Illuminate\Contracts\Mail\Mailable $view) + * @method static \Symfony\Component\Mailer\Transport\TransportInterface getSymfonyTransport() + * @method static \Illuminate\Contracts\View\Factory getViewFactory() + * @method static void setSymfonyTransport(\Symfony\Component\Mailer\Transport\TransportInterface $transport) + * @method static \Illuminate\Mail\Mailer setQueue(\Illuminate\Contracts\Queue\Factory $queue) + * @method static void macro(string $name, object|callable $macro) + * @method static void mixin(object $mixin, bool $replace = true) + * @method static bool hasMacro(string $name) + * @method static void flushMacros() + * @see \Illuminate\Mail\MailManager + * @see \Illuminate\Support\Testing\Fakes\MailFake + */ + class Mail { + /** + * Get a mailer instance by name. + * + * @param string|null $name + * @return \Illuminate\Contracts\Mail\Mailer + * @static + */ + public static function mailer($name = null) + { + /** @var \Illuminate\Mail\MailManager $instance */ + return $instance->mailer($name); + } + /** + * Get a mailer driver instance. + * + * @param string|null $driver + * @return \Illuminate\Mail\Mailer + * @static + */ + public static function driver($driver = null) + { + /** @var \Illuminate\Mail\MailManager $instance */ + return $instance->driver($driver); + } + /** + * Create a new transport instance. + * + * @param array $config + * @return \Symfony\Component\Mailer\Transport\TransportInterface + * @throws \InvalidArgumentException + * @static + */ + public static function createSymfonyTransport($config) + { + /** @var \Illuminate\Mail\MailManager $instance */ + return $instance->createSymfonyTransport($config); + } + /** + * Get the default mail driver name. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Mail\MailManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Set the default mail driver name. + * + * @param string $name + * @return void + * @static + */ + public static function setDefaultDriver($name) + { + /** @var \Illuminate\Mail\MailManager $instance */ + $instance->setDefaultDriver($name); + } + /** + * Disconnect the given mailer and remove from local cache. + * + * @param string|null $name + * @return void + * @static + */ + public static function purge($name = null) + { + /** @var \Illuminate\Mail\MailManager $instance */ + $instance->purge($name); + } + /** + * Register a custom transport creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Mail\MailManager + * @static + */ + public static function extend($driver, $callback) + { + /** @var \Illuminate\Mail\MailManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Get the application instance used by the manager. + * + * @return \Illuminate\Contracts\Foundation\Application + * @static + */ + public static function getApplication() + { + /** @var \Illuminate\Mail\MailManager $instance */ + return $instance->getApplication(); + } + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return \Illuminate\Mail\MailManager + * @static + */ + public static function setApplication($app) + { + /** @var \Illuminate\Mail\MailManager $instance */ + return $instance->setApplication($app); + } + /** + * Forget all of the resolved mailer instances. + * + * @return \Illuminate\Mail\MailManager + * @static + */ + public static function forgetMailers() + { + /** @var \Illuminate\Mail\MailManager $instance */ + return $instance->forgetMailers(); + } + /** + * Assert if a mailable was sent based on a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|int|null $callback + * @return void + * @static + */ + public static function assertSent($mailable, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->assertSent($mailable, $callback); + } + /** + * Determine if a mailable was not sent or queued to be sent based on a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return void + * @static + */ + public static function assertNotOutgoing($mailable, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->assertNotOutgoing($mailable, $callback); + } + /** + * Determine if a mailable was not sent based on a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return void + * @static + */ + public static function assertNotSent($mailable, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->assertNotSent($mailable, $callback); + } + /** + * Assert that no mailables were sent or queued to be sent. + * + * @return void + * @static + */ + public static function assertNothingOutgoing() + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->assertNothingOutgoing(); + } + /** + * Assert that no mailables were sent. + * + * @return void + * @static + */ + public static function assertNothingSent() + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->assertNothingSent(); + } + /** + * Assert if a mailable was queued based on a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|int|null $callback + * @return void + * @static + */ + public static function assertQueued($mailable, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->assertQueued($mailable, $callback); + } + /** + * Determine if a mailable was not queued based on a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return void + * @static + */ + public static function assertNotQueued($mailable, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->assertNotQueued($mailable, $callback); + } + /** + * Assert that no mailables were queued. + * + * @return void + * @static + */ + public static function assertNothingQueued() + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->assertNothingQueued(); + } + /** + * Get all of the mailables matching a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function sent($mailable, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->sent($mailable, $callback); + } + /** + * Determine if the given mailable has been sent. + * + * @param string $mailable + * @return bool + * @static + */ + public static function hasSent($mailable) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->hasSent($mailable); + } + /** + * Get all of the queued mailables matching a truth-test callback. + * + * @param string|\Closure $mailable + * @param callable|null $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function queued($mailable, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->queued($mailable, $callback); + } + /** + * Determine if the given mailable has been queued. + * + * @param string $mailable + * @return bool + * @static + */ + public static function hasQueued($mailable) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->hasQueued($mailable); + } + /** + * Begin the process of mailing a mailable class instance. + * + * @param mixed $users + * @return \Illuminate\Mail\PendingMail + * @static + */ + public static function to($users) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->to($users); + } + /** + * Begin the process of mailing a mailable class instance. + * + * @param mixed $users + * @return \Illuminate\Mail\PendingMail + * @static + */ + public static function cc($users) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->cc($users); + } + /** + * Begin the process of mailing a mailable class instance. + * + * @param mixed $users + * @return \Illuminate\Mail\PendingMail + * @static + */ + public static function bcc($users) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->bcc($users); + } + /** + * Send a new message with only a raw text part. + * + * @param string $text + * @param \Closure|string $callback + * @return void + * @static + */ + public static function raw($text, $callback) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->raw($text, $callback); + } + /** + * Send a new message using a view. + * + * @param \Illuminate\Contracts\Mail\Mailable|string|array $view + * @param array $data + * @param \Closure|string|null $callback + * @return void + * @static + */ + public static function send($view, $data = [], $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + $instance->send($view, $data, $callback); + } + /** + * Queue a new e-mail message for sending. + * + * @param \Illuminate\Contracts\Mail\Mailable|string|array $view + * @param string|null $queue + * @return mixed + * @static + */ + public static function queue($view, $queue = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->queue($view, $queue); + } + /** + * Queue a new e-mail message for sending after (n) seconds. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param \Illuminate\Contracts\Mail\Mailable|string|array $view + * @param string|null $queue + * @return mixed + * @static + */ + public static function later($delay, $view, $queue = null) + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->later($delay, $view, $queue); + } + /** + * Get the array of failed recipients. + * + * @return array + * @static + */ + public static function failures() + { + /** @var \Illuminate\Support\Testing\Fakes\MailFake $instance */ + return $instance->failures(); + } + + } + /** + * + * + * @see \Illuminate\Notifications\ChannelManager + * @see \Illuminate\Support\Testing\Fakes\NotificationFake + */ + class Notification { + /** + * Send the given notification to the given notifiable entities. + * + * @param \Illuminate\Support\Collection|array|mixed $notifiables + * @param mixed $notification + * @return void + * @static + */ + public static function send($notifiables, $notification) + { + /** @var \Illuminate\Notifications\ChannelManager $instance */ + $instance->send($notifiables, $notification); + } + /** + * Send the given notification immediately. + * + * @param \Illuminate\Support\Collection|array|mixed $notifiables + * @param mixed $notification + * @param array|null $channels + * @return void + * @static + */ + public static function sendNow($notifiables, $notification, $channels = null) + { + /** @var \Illuminate\Notifications\ChannelManager $instance */ + $instance->sendNow($notifiables, $notification, $channels); + } + /** + * Get a channel instance. + * + * @param string|null $name + * @return mixed + * @static + */ + public static function channel($name = null) + { + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->channel($name); + } + /** + * Get the default channel driver name. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Get the default channel driver name. + * + * @return string + * @static + */ + public static function deliversVia() + { + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->deliversVia(); + } + /** + * Set the default channel driver name. + * + * @param string $channel + * @return void + * @static + */ + public static function deliverVia($channel) + { + /** @var \Illuminate\Notifications\ChannelManager $instance */ + $instance->deliverVia($channel); + } + /** + * Set the locale of notifications. + * + * @param string $locale + * @return \Illuminate\Notifications\ChannelManager + * @static + */ + public static function locale($locale) + { + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->locale($locale); + } + /** + * Get a driver instance. + * + * @param string|null $driver + * @return mixed + * @throws \InvalidArgumentException + * @static + */ + public static function driver($driver = null) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->driver($driver); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Notifications\ChannelManager + * @static + */ + public static function extend($driver, $callback) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Get all of the created "drivers". + * + * @return array + * @static + */ + public static function getDrivers() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->getDrivers(); + } + /** + * Get the container instance used by the manager. + * + * @return \Illuminate\Contracts\Container\Container + * @static + */ + public static function getContainer() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->getContainer(); + } + /** + * Set the container instance used by the manager. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return \Illuminate\Notifications\ChannelManager + * @static + */ + public static function setContainer($container) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->setContainer($container); + } + /** + * Forget all of the resolved driver instances. + * + * @return \Illuminate\Notifications\ChannelManager + * @static + */ + public static function forgetDrivers() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Notifications\ChannelManager $instance */ + return $instance->forgetDrivers(); + } + /** + * Assert if a notification was sent on-demand based on a truth-test callback. + * + * @param string|\Closure $notification + * @param callable|null $callback + * @return void + * @throws \Exception + * @static + */ + public static function assertSentOnDemand($notification, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertSentOnDemand($notification, $callback); + } + /** + * Assert if a notification was sent based on a truth-test callback. + * + * @param mixed $notifiable + * @param string|\Closure $notification + * @param callable|null $callback + * @return void + * @throws \Exception + * @static + */ + public static function assertSentTo($notifiable, $notification, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertSentTo($notifiable, $notification, $callback); + } + /** + * Assert if a notification was sent on-demand a number of times. + * + * @param string $notification + * @param int $times + * @return void + * @static + */ + public static function assertSentOnDemandTimes($notification, $times = 1) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertSentOnDemandTimes($notification, $times); + } + /** + * Assert if a notification was sent a number of times. + * + * @param mixed $notifiable + * @param string $notification + * @param int $times + * @return void + * @static + */ + public static function assertSentToTimes($notifiable, $notification, $times = 1) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertSentToTimes($notifiable, $notification, $times); + } + /** + * Determine if a notification was sent based on a truth-test callback. + * + * @param mixed $notifiable + * @param string|\Closure $notification + * @param callable|null $callback + * @return void + * @throws \Exception + * @static + */ + public static function assertNotSentTo($notifiable, $notification, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertNotSentTo($notifiable, $notification, $callback); + } + /** + * Assert that no notifications were sent. + * + * @return void + * @static + */ + public static function assertNothingSent() + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertNothingSent(); + } + /** + * Assert that no notifications were sent to the given notifiable. + * + * @param mixed $notifiable + * @return void + * @throws \Exception + * @static + */ + public static function assertNothingSentTo($notifiable) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertNothingSentTo($notifiable); + } + /** + * Assert the total amount of times a notification was sent. + * + * @param string $notification + * @param int $expectedCount + * @return void + * @static + */ + public static function assertSentTimes($notification, $expectedCount) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertSentTimes($notification, $expectedCount); + } + /** + * Assert the total count of notification that were sent. + * + * @param int $expectedCount + * @return void + * @static + */ + public static function assertCount($expectedCount) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertCount($expectedCount); + } + /** + * Assert the total amount of times a notification was sent. + * + * @param int $expectedCount + * @param string $notification + * @return void + * @deprecated Use the assertSentTimes method instead + * @static + */ + public static function assertTimesSent($expectedCount, $notification) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + $instance->assertTimesSent($expectedCount, $notification); + } + /** + * Get all of the notifications matching a truth-test callback. + * + * @param mixed $notifiable + * @param string $notification + * @param callable|null $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function sent($notifiable, $notification, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + return $instance->sent($notifiable, $notification, $callback); + } + /** + * Determine if there are more notifications left to inspect. + * + * @param mixed $notifiable + * @param string $notification + * @return bool + * @static + */ + public static function hasSent($notifiable, $notification) + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + return $instance->hasSent($notifiable, $notification); + } + /** + * Get the notifications that have been sent. + * + * @return array + * @static + */ + public static function sentNotifications() + { + /** @var \Illuminate\Support\Testing\Fakes\NotificationFake $instance */ + return $instance->sentNotifications(); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Support\Testing\Fakes\NotificationFake::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Support\Testing\Fakes\NotificationFake::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Support\Testing\Fakes\NotificationFake::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Support\Testing\Fakes\NotificationFake::flushMacros(); + } + + } + /** + * + * + * @method static string sendResetLink(array $credentials, \Closure|null $callback = null) + * @method static mixed reset(array $credentials, \Closure $callback) + * @method static \Illuminate\Contracts\Auth\CanResetPassword|null getUser(array $credentials) + * @method static string createToken(\Illuminate\Contracts\Auth\CanResetPassword $user) + * @method static void deleteToken(\Illuminate\Contracts\Auth\CanResetPassword $user) + * @method static bool tokenExists(\Illuminate\Contracts\Auth\CanResetPassword $user, string $token) + * @method static \Illuminate\Auth\Passwords\TokenRepositoryInterface getRepository() + * @see \Illuminate\Auth\Passwords\PasswordBrokerManager + * @see \Illuminate\Auth\Passwords\PasswordBroker + */ + class Password { + /** + * Attempt to get the broker from the local cache. + * + * @param string|null $name + * @return \Illuminate\Contracts\Auth\PasswordBroker + * @static + */ + public static function broker($name = null) + { + /** @var \Illuminate\Auth\Passwords\PasswordBrokerManager $instance */ + return $instance->broker($name); + } + /** + * Get the default password broker name. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Auth\Passwords\PasswordBrokerManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Set the default password broker name. + * + * @param string $name + * @return void + * @static + */ + public static function setDefaultDriver($name) + { + /** @var \Illuminate\Auth\Passwords\PasswordBrokerManager $instance */ + $instance->setDefaultDriver($name); + } + + } + /** + * + * + * @see \Illuminate\Queue\QueueManager + * @see \Illuminate\Queue\Queue + * @see \Illuminate\Support\Testing\Fakes\QueueFake + */ + class Queue { + /** + * Register an event listener for the before job event. + * + * @param mixed $callback + * @return void + * @static + */ + public static function before($callback) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + $instance->before($callback); + } + /** + * Register an event listener for the after job event. + * + * @param mixed $callback + * @return void + * @static + */ + public static function after($callback) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + $instance->after($callback); + } + /** + * Register an event listener for the exception occurred job event. + * + * @param mixed $callback + * @return void + * @static + */ + public static function exceptionOccurred($callback) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + $instance->exceptionOccurred($callback); + } + /** + * Register an event listener for the daemon queue loop. + * + * @param mixed $callback + * @return void + * @static + */ + public static function looping($callback) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + $instance->looping($callback); + } + /** + * Register an event listener for the failed job event. + * + * @param mixed $callback + * @return void + * @static + */ + public static function failing($callback) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + $instance->failing($callback); + } + /** + * Register an event listener for the daemon queue stopping. + * + * @param mixed $callback + * @return void + * @static + */ + public static function stopping($callback) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + $instance->stopping($callback); + } + /** + * Determine if the driver is connected. + * + * @param string|null $name + * @return bool + * @static + */ + public static function connected($name = null) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + return $instance->connected($name); + } + /** + * Resolve a queue connection instance. + * + * @param string|null $name + * @return \Illuminate\Contracts\Queue\Queue + * @static + */ + public static function connection($name = null) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + return $instance->connection($name); + } + /** + * Add a queue connection resolver. + * + * @param string $driver + * @param \Closure $resolver + * @return void + * @static + */ + public static function extend($driver, $resolver) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + $instance->extend($driver, $resolver); + } + /** + * Add a queue connection resolver. + * + * @param string $driver + * @param \Closure $resolver + * @return void + * @static + */ + public static function addConnector($driver, $resolver) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + $instance->addConnector($driver, $resolver); + } + /** + * Get the name of the default queue connection. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Queue\QueueManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Set the name of the default queue connection. + * + * @param string $name + * @return void + * @static + */ + public static function setDefaultDriver($name) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + $instance->setDefaultDriver($name); + } + /** + * Get the full name for the given connection. + * + * @param string|null $connection + * @return string + * @static + */ + public static function getName($connection = null) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + return $instance->getName($connection); + } + /** + * Get the application instance used by the manager. + * + * @return \Illuminate\Contracts\Foundation\Application + * @static + */ + public static function getApplication() + { + /** @var \Illuminate\Queue\QueueManager $instance */ + return $instance->getApplication(); + } + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return \Illuminate\Queue\QueueManager + * @static + */ + public static function setApplication($app) + { + /** @var \Illuminate\Queue\QueueManager $instance */ + return $instance->setApplication($app); + } + /** + * Specify the jobs that should be queued instead of faked. + * + * @param array|string $jobsToBeQueued + * @return \Illuminate\Support\Testing\Fakes\QueueFake + * @static + */ + public static function except($jobsToBeQueued) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->except($jobsToBeQueued); + } + /** + * Assert if a job was pushed based on a truth-test callback. + * + * @param string|\Closure $job + * @param callable|int|null $callback + * @return void + * @static + */ + public static function assertPushed($job, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + $instance->assertPushed($job, $callback); + } + /** + * Assert if a job was pushed based on a truth-test callback. + * + * @param string $queue + * @param string|\Closure $job + * @param callable|null $callback + * @return void + * @static + */ + public static function assertPushedOn($queue, $job, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + $instance->assertPushedOn($queue, $job, $callback); + } + /** + * Assert if a job was pushed with chained jobs based on a truth-test callback. + * + * @param string $job + * @param array $expectedChain + * @param callable|null $callback + * @return void + * @static + */ + public static function assertPushedWithChain($job, $expectedChain = [], $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + $instance->assertPushedWithChain($job, $expectedChain, $callback); + } + /** + * Assert if a job was pushed with an empty chain based on a truth-test callback. + * + * @param string $job + * @param callable|null $callback + * @return void + * @static + */ + public static function assertPushedWithoutChain($job, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + $instance->assertPushedWithoutChain($job, $callback); + } + /** + * Determine if a job was pushed based on a truth-test callback. + * + * @param string|\Closure $job + * @param callable|null $callback + * @return void + * @static + */ + public static function assertNotPushed($job, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + $instance->assertNotPushed($job, $callback); + } + /** + * Assert that no jobs were pushed. + * + * @return void + * @static + */ + public static function assertNothingPushed() + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + $instance->assertNothingPushed(); + } + /** + * Get all of the jobs matching a truth-test callback. + * + * @param string $job + * @param callable|null $callback + * @return \Illuminate\Support\Collection + * @static + */ + public static function pushed($job, $callback = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->pushed($job, $callback); + } + /** + * Determine if there are any stored jobs for a given class. + * + * @param string $job + * @return bool + * @static + */ + public static function hasPushed($job) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->hasPushed($job); + } + /** + * Get the size of the queue. + * + * @param string|null $queue + * @return int + * @static + */ + public static function size($queue = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->size($queue); + } + /** + * Push a new job onto the queue. + * + * @param string|object $job + * @param mixed $data + * @param string|null $queue + * @return mixed + * @static + */ + public static function push($job, $data = '', $queue = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->push($job, $data, $queue); + } + /** + * Determine if a job should be faked or actually dispatched. + * + * @param object $job + * @return bool + * @static + */ + public static function shouldFakeJob($job) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->shouldFakeJob($job); + } + /** + * Push a raw payload onto the queue. + * + * @param string $payload + * @param string|null $queue + * @param array $options + * @return mixed + * @static + */ + public static function pushRaw($payload, $queue = null, $options = []) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->pushRaw($payload, $queue, $options); + } + /** + * Push a new job onto the queue after (n) seconds. + * + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string|object $job + * @param mixed $data + * @param string|null $queue + * @return mixed + * @static + */ + public static function later($delay, $job, $data = '', $queue = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->later($delay, $job, $data, $queue); + } + /** + * Push a new job onto the queue. + * + * @param string $queue + * @param string|object $job + * @param mixed $data + * @return mixed + * @static + */ + public static function pushOn($queue, $job, $data = '') + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->pushOn($queue, $job, $data); + } + /** + * Push a new job onto a specific queue after (n) seconds. + * + * @param string $queue + * @param \DateTimeInterface|\DateInterval|int $delay + * @param string|object $job + * @param mixed $data + * @return mixed + * @static + */ + public static function laterOn($queue, $delay, $job, $data = '') + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->laterOn($queue, $delay, $job, $data); + } + /** + * Pop the next job off of the queue. + * + * @param string|null $queue + * @return \Illuminate\Contracts\Queue\Job|null + * @static + */ + public static function pop($queue = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->pop($queue); + } + /** + * Push an array of jobs onto the queue. + * + * @param array $jobs + * @param mixed $data + * @param string|null $queue + * @return mixed + * @static + */ + public static function bulk($jobs, $data = '', $queue = null) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->bulk($jobs, $data, $queue); + } + /** + * Get the jobs that have been pushed. + * + * @return array + * @static + */ + public static function pushedJobs() + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->pushedJobs(); + } + /** + * Get the connection name for the queue. + * + * @return string + * @static + */ + public static function getConnectionName() + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->getConnectionName(); + } + /** + * Set the connection name for the queue. + * + * @param string $name + * @return \Illuminate\Support\Testing\Fakes\QueueFake + * @static + */ + public static function setConnectionName($name) + { + /** @var \Illuminate\Support\Testing\Fakes\QueueFake $instance */ + return $instance->setConnectionName($name); + } + /** + * Migrate the delayed jobs that are ready to the regular queue. + * + * @param string $from + * @param string $to + * @param int $limit + * @return array + * @static + */ + public static function migrateExpiredJobs($from, $to) + { + /** @var \Illuminate\Queue\RedisQueue $instance */ + return $instance->migrateExpiredJobs($from, $to); + } + /** + * Delete a reserved job from the queue. + * + * @param string $queue + * @param \Illuminate\Queue\Jobs\RedisJob $job + * @return void + * @static + */ + public static function deleteReserved($queue, $job) + { + /** @var \Illuminate\Queue\RedisQueue $instance */ + $instance->deleteReserved($queue, $job); + } + /** + * Delete a reserved job from the reserved queue and release it. + * + * @param string $queue + * @param \Illuminate\Queue\Jobs\RedisJob $job + * @param int $delay + * @return void + * @static + */ + public static function deleteAndRelease($queue, $job, $delay) + { + /** @var \Illuminate\Queue\RedisQueue $instance */ + $instance->deleteAndRelease($queue, $job, $delay); + } + /** + * Delete all of the jobs from the queue. + * + * @param string $queue + * @return int + * @static + */ + public static function clear($queue) + { + /** @var \Illuminate\Queue\RedisQueue $instance */ + return $instance->clear($queue); + } + /** + * Get the queue or return the default. + * + * @param string|null $queue + * @return string + * @static + */ + public static function getQueue($queue) + { + /** @var \Illuminate\Queue\RedisQueue $instance */ + return $instance->getQueue($queue); + } + /** + * Get the connection for the queue. + * + * @return \Illuminate\Redis\Connections\Connection + * @static + */ + public static function getConnection() + { + /** @var \Illuminate\Queue\RedisQueue $instance */ + return $instance->getConnection(); + } + /** + * Get the underlying Redis instance. + * + * @return \Illuminate\Contracts\Redis\Factory + * @static + */ + public static function getRedis() + { + /** @var \Illuminate\Queue\RedisQueue $instance */ + return $instance->getRedis(); + } + /** + * Get the backoff for an object-based queue handler. + * + * @param mixed $job + * @return mixed + * @static + */ + public static function getJobBackoff($job) + { //Method inherited from \Illuminate\Queue\Queue + /** @var \Illuminate\Queue\RedisQueue $instance */ + return $instance->getJobBackoff($job); + } + /** + * Get the expiration timestamp for an object-based queue handler. + * + * @param mixed $job + * @return mixed + * @static + */ + public static function getJobExpiration($job) + { //Method inherited from \Illuminate\Queue\Queue + /** @var \Illuminate\Queue\RedisQueue $instance */ + return $instance->getJobExpiration($job); + } + /** + * Register a callback to be executed when creating job payloads. + * + * @param callable|null $callback + * @return void + * @static + */ + public static function createPayloadUsing($callback) + { //Method inherited from \Illuminate\Queue\Queue + \Illuminate\Queue\RedisQueue::createPayloadUsing($callback); + } + /** + * Get the container instance being used by the connection. + * + * @return \Illuminate\Container\Container + * @static + */ + public static function getContainer() + { //Method inherited from \Illuminate\Queue\Queue + /** @var \Illuminate\Queue\RedisQueue $instance */ + return $instance->getContainer(); + } + /** + * Set the IoC container instance. + * + * @param \Illuminate\Container\Container $container + * @return void + * @static + */ + public static function setContainer($container) + { //Method inherited from \Illuminate\Queue\Queue + /** @var \Illuminate\Queue\RedisQueue $instance */ + $instance->setContainer($container); + } + + } + /** + * + * + * @see \Illuminate\Cache\RateLimiter + */ + class RateLimiter { + /** + * Register a named limiter configuration. + * + * @param string $name + * @param \Closure $callback + * @return \Illuminate\Cache\RateLimiter + * @static + */ + public static function for($name, $callback) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->for($name, $callback); + } + /** + * Get the given named rate limiter. + * + * @param string $name + * @return \Closure + * @static + */ + public static function limiter($name) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->limiter($name); + } + /** + * Attempts to execute a callback if it's not limited. + * + * @param string $key + * @param int $maxAttempts + * @param \Closure $callback + * @param int $decaySeconds + * @return mixed + * @static + */ + public static function attempt($key, $maxAttempts, $callback, $decaySeconds = 60) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->attempt($key, $maxAttempts, $callback, $decaySeconds); + } + /** + * Determine if the given key has been "accessed" too many times. + * + * @param string $key + * @param int $maxAttempts + * @return bool + * @static + */ + public static function tooManyAttempts($key, $maxAttempts) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->tooManyAttempts($key, $maxAttempts); + } + /** + * Increment the counter for a given key for a given decay time. + * + * @param string $key + * @param int $decaySeconds + * @return int + * @static + */ + public static function hit($key, $decaySeconds = 60) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->hit($key, $decaySeconds); + } + /** + * Get the number of attempts for the given key. + * + * @param string $key + * @return mixed + * @static + */ + public static function attempts($key) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->attempts($key); + } + /** + * Reset the number of attempts for the given key. + * + * @param string $key + * @return mixed + * @static + */ + public static function resetAttempts($key) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->resetAttempts($key); + } + /** + * Get the number of retries left for the given key. + * + * @param string $key + * @param int $maxAttempts + * @return int + * @static + */ + public static function remaining($key, $maxAttempts) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->remaining($key, $maxAttempts); + } + /** + * Get the number of retries left for the given key. + * + * @param string $key + * @param int $maxAttempts + * @return int + * @static + */ + public static function retriesLeft($key, $maxAttempts) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->retriesLeft($key, $maxAttempts); + } + /** + * Clear the hits and lockout timer for the given key. + * + * @param string $key + * @return void + * @static + */ + public static function clear($key) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + $instance->clear($key); + } + /** + * Get the number of seconds until the "key" is accessible again. + * + * @param string $key + * @return int + * @static + */ + public static function availableIn($key) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->availableIn($key); + } + /** + * Clean the rate limiter key from unicode characters. + * + * @param string $key + * @return string + * @static + */ + public static function cleanRateLimiterKey($key) + { + /** @var \Illuminate\Cache\RateLimiter $instance */ + return $instance->cleanRateLimiterKey($key); + } + + } + /** + * + * + * @see \Illuminate\Routing\Redirector + */ + class Redirect { + /** + * Create a new redirect response to the "home" route. + * + * @param int $status + * @return \Illuminate\Http\RedirectResponse + * @deprecated Will be removed in a future Laravel version. + * @static + */ + public static function home($status = 302) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->home($status); + } + /** + * Create a new redirect response to the previous location. + * + * @param int $status + * @param array $headers + * @param mixed $fallback + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function back($status = 302, $headers = [], $fallback = false) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->back($status, $headers, $fallback); + } + /** + * Create a new redirect response to the current URI. + * + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function refresh($status = 302, $headers = []) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->refresh($status, $headers); + } + /** + * Create a new redirect response, while putting the current URL in the session. + * + * @param string $path + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function guest($path, $status = 302, $headers = [], $secure = null) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->guest($path, $status, $headers, $secure); + } + /** + * Create a new redirect response to the previously intended location. + * + * @param mixed $default + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function intended($default = '/', $status = 302, $headers = [], $secure = null) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->intended($default, $status, $headers, $secure); + } + /** + * Create a new redirect response to the given path. + * + * @param string $path + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function to($path, $status = 302, $headers = [], $secure = null) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->to($path, $status, $headers, $secure); + } + /** + * Create a new redirect response to an external URL (no validation). + * + * @param string $path + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function away($path, $status = 302, $headers = []) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->away($path, $status, $headers); + } + /** + * Create a new redirect response to the given HTTPS path. + * + * @param string $path + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function secure($path, $status = 302, $headers = []) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->secure($path, $status, $headers); + } + /** + * Create a new redirect response to a named route. + * + * @param string $route + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function route($route, $parameters = [], $status = 302, $headers = []) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->route($route, $parameters, $status, $headers); + } + /** + * Create a new redirect response to a signed named route. + * + * @param string $route + * @param mixed $parameters + * @param \DateTimeInterface|\DateInterval|int|null $expiration + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function signedRoute($route, $parameters = [], $expiration = null, $status = 302, $headers = []) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->signedRoute($route, $parameters, $expiration, $status, $headers); + } + /** + * Create a new redirect response to a signed named route. + * + * @param string $route + * @param \DateTimeInterface|\DateInterval|int|null $expiration + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function temporarySignedRoute($route, $expiration, $parameters = [], $status = 302, $headers = []) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->temporarySignedRoute($route, $expiration, $parameters, $status, $headers); + } + /** + * Create a new redirect response to a controller action. + * + * @param string|array $action + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function action($action, $parameters = [], $status = 302, $headers = []) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->action($action, $parameters, $status, $headers); + } + /** + * Get the URL generator instance. + * + * @return \Illuminate\Routing\UrlGenerator + * @static + */ + public static function getUrlGenerator() + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->getUrlGenerator(); + } + /** + * Set the active session store. + * + * @param \Illuminate\Session\Store $session + * @return void + * @static + */ + public static function setSession($session) + { + /** @var \Illuminate\Routing\Redirector $instance */ + $instance->setSession($session); + } + /** + * Get the "intended" URL from the session. + * + * @return string|null + * @static + */ + public static function getIntendedUrl() + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->getIntendedUrl(); + } + /** + * Set the "intended" URL in the session. + * + * @param string $url + * @return \Illuminate\Routing\Redirector + * @static + */ + public static function setIntendedUrl($url) + { + /** @var \Illuminate\Routing\Redirector $instance */ + return $instance->setIntendedUrl($url); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Routing\Redirector::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Routing\Redirector::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Routing\Redirector::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Routing\Redirector::flushMacros(); + } + + } + /** + * + * + * @see \Illuminate\Http\Request + */ + class Request { + /** + * Create a new Illuminate HTTP request from server variables. + * + * @return static + * @static + */ + public static function capture() + { + return \Illuminate\Http\Request::capture(); + } + /** + * Return the Request instance. + * + * @return \Illuminate\Http\Request + * @static + */ + public static function instance() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->instance(); + } + /** + * Get the request method. + * + * @return string + * @static + */ + public static function method() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->method(); + } + /** + * Get the root URL for the application. + * + * @return string + * @static + */ + public static function root() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->root(); + } + /** + * Get the URL (no query string) for the request. + * + * @return string + * @static + */ + public static function url() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->url(); + } + /** + * Get the full URL for the request. + * + * @return string + * @static + */ + public static function fullUrl() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->fullUrl(); + } + /** + * Get the full URL for the request with the added query string parameters. + * + * @param array $query + * @return string + * @static + */ + public static function fullUrlWithQuery($query) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->fullUrlWithQuery($query); + } + /** + * Get the full URL for the request without the given query string parameters. + * + * @param array|string $keys + * @return string + * @static + */ + public static function fullUrlWithoutQuery($keys) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->fullUrlWithoutQuery($keys); + } + /** + * Get the current path info for the request. + * + * @return string + * @static + */ + public static function path() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->path(); + } + /** + * Get the current decoded path info for the request. + * + * @return string + * @static + */ + public static function decodedPath() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->decodedPath(); + } + /** + * Get a segment from the URI (1 based index). + * + * @param int $index + * @param string|null $default + * @return string|null + * @static + */ + public static function segment($index, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->segment($index, $default); + } + /** + * Get all of the segments for the request path. + * + * @return array + * @static + */ + public static function segments() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->segments(); + } + /** + * Determine if the current request URI matches a pattern. + * + * @param mixed $patterns + * @return bool + * @static + */ + public static function is(...$patterns) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->is(...$patterns); + } + /** + * Determine if the route name matches a given pattern. + * + * @param mixed $patterns + * @return bool + * @static + */ + public static function routeIs(...$patterns) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->routeIs(...$patterns); + } + /** + * Determine if the current request URL and query string match a pattern. + * + * @param mixed $patterns + * @return bool + * @static + */ + public static function fullUrlIs(...$patterns) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->fullUrlIs(...$patterns); + } + /** + * Get the host name. + * + * @return string + * @static + */ + public static function host() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->host(); + } + /** + * Get the HTTP host being requested. + * + * @return string + * @static + */ + public static function httpHost() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->httpHost(); + } + /** + * Get the scheme and HTTP host. + * + * @return string + * @static + */ + public static function schemeAndHttpHost() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->schemeAndHttpHost(); + } + /** + * Determine if the request is the result of an AJAX call. + * + * @return bool + * @static + */ + public static function ajax() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->ajax(); + } + /** + * Determine if the request is the result of a PJAX call. + * + * @return bool + * @static + */ + public static function pjax() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->pjax(); + } + /** + * Determine if the request is the result of a prefetch call. + * + * @return bool + * @static + */ + public static function prefetch() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->prefetch(); + } + /** + * Determine if the request is over HTTPS. + * + * @return bool + * @static + */ + public static function secure() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->secure(); + } + /** + * Get the client IP address. + * + * @return string|null + * @static + */ + public static function ip() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->ip(); + } + /** + * Get the client IP addresses. + * + * @return array + * @static + */ + public static function ips() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->ips(); + } + /** + * Get the client user agent. + * + * @return string|null + * @static + */ + public static function userAgent() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->userAgent(); + } + /** + * Merge new input into the current request's input array. + * + * @param array $input + * @return \Illuminate\Http\Request + * @static + */ + public static function merge($input) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->merge($input); + } + /** + * Merge new input into the request's input, but only when that key is missing from the request. + * + * @param array $input + * @return \Illuminate\Http\Request + * @static + */ + public static function mergeIfMissing($input) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->mergeIfMissing($input); + } + /** + * Replace the input for the current request. + * + * @param array $input + * @return \Illuminate\Http\Request + * @static + */ + public static function replace($input) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->replace($input); + } + /** + * This method belongs to Symfony HttpFoundation and is not usually needed when using Laravel. + * + * Instead, you may use the "input" method. + * + * @param string $key + * @param mixed $default + * @return mixed + * @static + */ + public static function get($key, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->get($key, $default); + } + /** + * Get the JSON payload for the request. + * + * @param string|null $key + * @param mixed $default + * @return \Symfony\Component\HttpFoundation\ParameterBag|mixed + * @static + */ + public static function json($key = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->json($key, $default); + } + /** + * Create a new request instance from the given Laravel request. + * + * @param \Illuminate\Http\Request $from + * @param \Illuminate\Http\Request|null $to + * @return static + * @static + */ + public static function createFrom($from, $to = null) + { + return \Illuminate\Http\Request::createFrom($from, $to); + } + /** + * Create an Illuminate request from a Symfony instance. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @return static + * @static + */ + public static function createFromBase($request) + { + return \Illuminate\Http\Request::createFromBase($request); + } + /** + * Clones a request and overrides some of its parameters. + * + * @return static + * @param array $query The GET parameters + * @param array $request The POST parameters + * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) + * @param array $cookies The COOKIE parameters + * @param array $files The FILES parameters + * @param array $server The SERVER parameters + * @static + */ + public static function duplicate($query = null, $request = null, $attributes = null, $cookies = null, $files = null, $server = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->duplicate($query, $request, $attributes, $cookies, $files, $server); + } + /** + * Whether the request contains a Session object. + * + * This method does not give any information about the state of the session object, + * like whether the session is started or not. It is just a way to check if this Request + * is associated with a Session instance. + * + * @param bool $skipIfUninitialized When true, ignores factories injected by `setSessionFactory` + * @static + */ + public static function hasSession($skipIfUninitialized = false) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->hasSession($skipIfUninitialized); + } + /** + * Gets the Session. + * + * @throws SessionNotFoundException When session is not set properly + * @static + */ + public static function getSession() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->getSession(); + } + /** + * Get the session associated with the request. + * + * @return \Illuminate\Contracts\Session\Session + * @throws \RuntimeException + * @static + */ + public static function session() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->session(); + } + /** + * Set the session instance on the request. + * + * @param \Illuminate\Contracts\Session\Session $session + * @return void + * @static + */ + public static function setLaravelSession($session) + { + /** @var \Illuminate\Http\Request $instance */ + $instance->setLaravelSession($session); + } + /** + * Set the locale for the request instance. + * + * @param string $locale + * @return void + * @static + */ + public static function setRequestLocale($locale) + { + /** @var \Illuminate\Http\Request $instance */ + $instance->setRequestLocale($locale); + } + /** + * Set the default locale for the request instance. + * + * @param string $locale + * @return void + * @static + */ + public static function setDefaultRequestLocale($locale) + { + /** @var \Illuminate\Http\Request $instance */ + $instance->setDefaultRequestLocale($locale); + } + /** + * Get the user making the request. + * + * @param string|null $guard + * @return mixed + * @static + */ + public static function user($guard = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->user($guard); + } + /** + * Get the route handling the request. + * + * @param string|null $param + * @param mixed $default + * @return \Illuminate\Routing\Route|object|string|null + * @static + */ + public static function route($param = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->route($param, $default); + } + /** + * Get a unique fingerprint for the request / route / IP address. + * + * @return string + * @throws \RuntimeException + * @static + */ + public static function fingerprint() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->fingerprint(); + } + /** + * Set the JSON payload for the request. + * + * @param \Symfony\Component\HttpFoundation\ParameterBag $json + * @return \Illuminate\Http\Request + * @static + */ + public static function setJson($json) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->setJson($json); + } + /** + * Get the user resolver callback. + * + * @return \Closure + * @static + */ + public static function getUserResolver() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->getUserResolver(); + } + /** + * Set the user resolver callback. + * + * @param \Closure $callback + * @return \Illuminate\Http\Request + * @static + */ + public static function setUserResolver($callback) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->setUserResolver($callback); + } + /** + * Get the route resolver callback. + * + * @return \Closure + * @static + */ + public static function getRouteResolver() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->getRouteResolver(); + } + /** + * Set the route resolver callback. + * + * @param \Closure $callback + * @return \Illuminate\Http\Request + * @static + */ + public static function setRouteResolver($callback) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->setRouteResolver($callback); + } + /** + * Get all of the input and files for the request. + * + * @return array + * @static + */ + public static function toArray() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->toArray(); + } + /** + * Determine if the given offset exists. + * + * @param string $offset + * @return bool + * @static + */ + public static function offsetExists($offset) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->offsetExists($offset); + } + /** + * Get the value at the given offset. + * + * @param string $offset + * @return mixed + * @static + */ + public static function offsetGet($offset) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->offsetGet($offset); + } + /** + * Set the value at the given offset. + * + * @param string $offset + * @param mixed $value + * @return void + * @static + */ + public static function offsetSet($offset, $value) + { + /** @var \Illuminate\Http\Request $instance */ + $instance->offsetSet($offset, $value); + } + /** + * Remove the value at the given offset. + * + * @param string $offset + * @return void + * @static + */ + public static function offsetUnset($offset) + { + /** @var \Illuminate\Http\Request $instance */ + $instance->offsetUnset($offset); + } + /** + * Sets the parameters for this request. + * + * This method also re-initializes all properties. + * + * @param array $query The GET parameters + * @param array $request The POST parameters + * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...) + * @param array $cookies The COOKIE parameters + * @param array $files The FILES parameters + * @param array $server The SERVER parameters + * @param string|resource|null $content The raw body data + * @static + */ + public static function initialize($query = [], $request = [], $attributes = [], $cookies = [], $files = [], $server = [], $content = null) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->initialize($query, $request, $attributes, $cookies, $files, $server, $content); + } + /** + * Creates a new request with values from PHP's super globals. + * + * @static + */ + public static function createFromGlobals() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::createFromGlobals(); + } + /** + * Creates a Request based on a given URI and configuration. + * + * The information contained in the URI always take precedence + * over the other information (server and parameters). + * + * @param string $uri The URI + * @param string $method The HTTP method + * @param array $parameters The query (GET) or request (POST) parameters + * @param array $cookies The request cookies ($_COOKIE) + * @param array $files The request files ($_FILES) + * @param array $server The server parameters ($_SERVER) + * @param string|resource|null $content The raw body data + * @static + */ + public static function create($uri, $method = 'GET', $parameters = [], $cookies = [], $files = [], $server = [], $content = null) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::create($uri, $method, $parameters, $cookies, $files, $server, $content); + } + /** + * Sets a callable able to create a Request instance. + * + * This is mainly useful when you need to override the Request class + * to keep BC with an existing system. It should not be used for any + * other purpose. + * + * @static + */ + public static function setFactory($callable) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::setFactory($callable); + } + /** + * Overrides the PHP global variables according to this request instance. + * + * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE. + * $_FILES is never overridden, see rfc1867 + * + * @static + */ + public static function overrideGlobals() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->overrideGlobals(); + } + /** + * Sets a list of trusted proxies. + * + * You should only list the reverse proxies that you manage directly. + * + * @param array $proxies A list of trusted proxies, the string 'REMOTE_ADDR' will be replaced with $_SERVER['REMOTE_ADDR'] + * @param int $trustedHeaderSet A bit field of Request::HEADER_*, to set which headers to trust from your proxies + * @static + */ + public static function setTrustedProxies($proxies, $trustedHeaderSet) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::setTrustedProxies($proxies, $trustedHeaderSet); + } + /** + * Gets the list of trusted proxies. + * + * @return string[] + * @static + */ + public static function getTrustedProxies() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::getTrustedProxies(); + } + /** + * Gets the set of trusted headers from trusted proxies. + * + * @return int A bit field of Request::HEADER_* that defines which headers are trusted from your proxies + * @static + */ + public static function getTrustedHeaderSet() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::getTrustedHeaderSet(); + } + /** + * Sets a list of trusted host patterns. + * + * You should only list the hosts you manage using regexs. + * + * @param array $hostPatterns A list of trusted host patterns + * @static + */ + public static function setTrustedHosts($hostPatterns) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::setTrustedHosts($hostPatterns); + } + /** + * Gets the list of trusted host patterns. + * + * @return string[] + * @static + */ + public static function getTrustedHosts() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::getTrustedHosts(); + } + /** + * Normalizes a query string. + * + * It builds a normalized query string, where keys/value pairs are alphabetized, + * have consistent escaping and unneeded delimiters are removed. + * + * @static + */ + public static function normalizeQueryString($qs) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::normalizeQueryString($qs); + } + /** + * Enables support for the _method request parameter to determine the intended HTTP method. + * + * Be warned that enabling this feature might lead to CSRF issues in your code. + * Check that you are using CSRF tokens when required. + * If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered + * and used to send a "PUT" or "DELETE" request via the _method request parameter. + * If these methods are not protected against CSRF, this presents a possible vulnerability. + * + * The HTTP method can only be overridden when the real HTTP method is POST. + * + * @static + */ + public static function enableHttpMethodParameterOverride() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::enableHttpMethodParameterOverride(); + } + /** + * Checks whether support for the _method request parameter is enabled. + * + * @static + */ + public static function getHttpMethodParameterOverride() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::getHttpMethodParameterOverride(); + } + /** + * Whether the request contains a Session which was started in one of the + * previous requests. + * + * @static + */ + public static function hasPreviousSession() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->hasPreviousSession(); + } + /** + * + * + * @static + */ + public static function setSession($session) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->setSession($session); + } + /** + * + * + * @internal + * @param \Symfony\Component\HttpFoundation\callable(): SessionInterface $factory + * @static + */ + public static function setSessionFactory($factory) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->setSessionFactory($factory); + } + /** + * Returns the client IP addresses. + * + * In the returned array the most trusted IP address is first, and the + * least trusted one last. The "real" client IP address is the last one, + * but this is also the least trusted one. Trusted proxies are stripped. + * + * Use this method carefully; you should use getClientIp() instead. + * + * @see getClientIp() + * @static + */ + public static function getClientIps() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getClientIps(); + } + /** + * Returns the client IP address. + * + * This method can read the client IP address from the "X-Forwarded-For" header + * when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For" + * header value is a comma+space separated list of IP addresses, the left-most + * being the original client, and each successive proxy that passed the request + * adding the IP address where it received the request from. + * + * If your reverse proxy uses a different header name than "X-Forwarded-For", + * ("Client-Ip" for instance), configure it via the $trustedHeaderSet + * argument of the Request::setTrustedProxies() method instead. + * + * @see getClientIps() + * @see https://wikipedia.org/wiki/X-Forwarded-For + * @static + */ + public static function getClientIp() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getClientIp(); + } + /** + * Returns current script name. + * + * @static + */ + public static function getScriptName() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getScriptName(); + } + /** + * Returns the path being requested relative to the executed script. + * + * The path info always starts with a /. + * + * Suppose this request is instantiated from /mysite on localhost: + * + * * http://localhost/mysite returns an empty string + * * http://localhost/mysite/about returns '/about' + * * http://localhost/mysite/enco%20ded returns '/enco%20ded' + * * http://localhost/mysite/about?var=1 returns '/about' + * + * @return string The raw path (i.e. not urldecoded) + * @static + */ + public static function getPathInfo() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getPathInfo(); + } + /** + * Returns the root path from which this request is executed. + * + * Suppose that an index.php file instantiates this request object: + * + * * http://localhost/index.php returns an empty string + * * http://localhost/index.php/page returns an empty string + * * http://localhost/web/index.php returns '/web' + * * http://localhost/we%20b/index.php returns '/we%20b' + * + * @return string The raw path (i.e. not urldecoded) + * @static + */ + public static function getBasePath() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getBasePath(); + } + /** + * Returns the root URL from which this request is executed. + * + * The base URL never ends with a /. + * + * This is similar to getBasePath(), except that it also includes the + * script filename (e.g. index.php) if one exists. + * + * @return string The raw URL (i.e. not urldecoded) + * @static + */ + public static function getBaseUrl() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getBaseUrl(); + } + /** + * Gets the request's scheme. + * + * @static + */ + public static function getScheme() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getScheme(); + } + /** + * Returns the port on which the request is made. + * + * This method can read the client port from the "X-Forwarded-Port" header + * when trusted proxies were set via "setTrustedProxies()". + * + * The "X-Forwarded-Port" header must contain the client port. + * + * @return int|string|null Can be a string if fetched from the server bag + * @static + */ + public static function getPort() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getPort(); + } + /** + * Returns the user. + * + * @static + */ + public static function getUser() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getUser(); + } + /** + * Returns the password. + * + * @static + */ + public static function getPassword() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getPassword(); + } + /** + * Gets the user info. + * + * @return string|null A user name if any and, optionally, scheme-specific information about how to gain authorization to access the server + * @static + */ + public static function getUserInfo() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getUserInfo(); + } + /** + * Returns the HTTP host being requested. + * + * The port name will be appended to the host if it's non-standard. + * + * @static + */ + public static function getHttpHost() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getHttpHost(); + } + /** + * Returns the requested URI (path and query string). + * + * @return string The raw URI (i.e. not URI decoded) + * @static + */ + public static function getRequestUri() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getRequestUri(); + } + /** + * Gets the scheme and HTTP host. + * + * If the URL was called with basic authentication, the user + * and the password are not added to the generated string. + * + * @static + */ + public static function getSchemeAndHttpHost() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getSchemeAndHttpHost(); + } + /** + * Generates a normalized URI (URL) for the Request. + * + * @see getQueryString() + * @static + */ + public static function getUri() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getUri(); + } + /** + * Generates a normalized URI for the given path. + * + * @param string $path A path to use instead of the current one + * @static + */ + public static function getUriForPath($path) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getUriForPath($path); + } + /** + * Returns the path as relative reference from the current Request path. + * + * Only the URIs path component (no schema, host etc.) is relevant and must be given. + * Both paths must be absolute and not contain relative parts. + * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives. + * Furthermore, they can be used to reduce the link size in documents. + * + * Example target paths, given a base path of "/a/b/c/d": + * - "/a/b/c/d" -> "" + * - "/a/b/c/" -> "./" + * - "/a/b/" -> "../" + * - "/a/b/c/other" -> "other" + * - "/a/x/y" -> "../../x/y" + * + * @static + */ + public static function getRelativeUriForPath($path) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getRelativeUriForPath($path); + } + /** + * Generates the normalized query string for the Request. + * + * It builds a normalized query string, where keys/value pairs are alphabetized + * and have consistent escaping. + * + * @static + */ + public static function getQueryString() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getQueryString(); + } + /** + * Checks whether the request is secure or not. + * + * This method can read the client protocol from the "X-Forwarded-Proto" header + * when trusted proxies were set via "setTrustedProxies()". + * + * The "X-Forwarded-Proto" header must contain the protocol: "https" or "http". + * + * @static + */ + public static function isSecure() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->isSecure(); + } + /** + * Returns the host name. + * + * This method can read the client host name from the "X-Forwarded-Host" header + * when trusted proxies were set via "setTrustedProxies()". + * + * The "X-Forwarded-Host" header must contain the client host name. + * + * @throws SuspiciousOperationException when the host name is invalid or not trusted + * @static + */ + public static function getHost() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getHost(); + } + /** + * Sets the request method. + * + * @static + */ + public static function setMethod($method) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->setMethod($method); + } + /** + * Gets the request "intended" method. + * + * If the X-HTTP-Method-Override header is set, and if the method is a POST, + * then it is used to determine the "real" intended HTTP method. + * + * The _method request parameter can also be used to determine the HTTP method, + * but only if enableHttpMethodParameterOverride() has been called. + * + * The method is always an uppercased string. + * + * @see getRealMethod() + * @static + */ + public static function getMethod() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getMethod(); + } + /** + * Gets the "real" request method. + * + * @see getMethod() + * @static + */ + public static function getRealMethod() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getRealMethod(); + } + /** + * Gets the mime type associated with the format. + * + * @static + */ + public static function getMimeType($format) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getMimeType($format); + } + /** + * Gets the mime types associated with the format. + * + * @return string[] + * @static + */ + public static function getMimeTypes($format) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + return \Illuminate\Http\Request::getMimeTypes($format); + } + /** + * Gets the format associated with the mime type. + * + * @static + */ + public static function getFormat($mimeType) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getFormat($mimeType); + } + /** + * Associates a format with mime types. + * + * @param string|string[] $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type) + * @static + */ + public static function setFormat($format, $mimeTypes) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->setFormat($format, $mimeTypes); + } + /** + * Gets the request format. + * + * Here is the process to determine the format: + * + * * format defined by the user (with setRequestFormat()) + * * _format request attribute + * * $default + * + * @see getPreferredFormat + * @static + */ + public static function getRequestFormat($default = 'html') + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getRequestFormat($default); + } + /** + * Sets the request format. + * + * @static + */ + public static function setRequestFormat($format) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->setRequestFormat($format); + } + /** + * Gets the usual name of the format associated with the request's media type (provided in the Content-Type header). + * + * @deprecated since Symfony 6.2, use getContentTypeFormat() instead + * @static + */ + public static function getContentType() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getContentType(); + } + /** + * Gets the usual name of the format associated with the request's media type (provided in the Content-Type header). + * + * @see Request::$formats + * @static + */ + public static function getContentTypeFormat() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getContentTypeFormat(); + } + /** + * Sets the default locale. + * + * @static + */ + public static function setDefaultLocale($locale) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->setDefaultLocale($locale); + } + /** + * Get the default locale. + * + * @static + */ + public static function getDefaultLocale() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getDefaultLocale(); + } + /** + * Sets the locale. + * + * @static + */ + public static function setLocale($locale) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->setLocale($locale); + } + /** + * Get the locale. + * + * @static + */ + public static function getLocale() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getLocale(); + } + /** + * Checks if the request method is of specified type. + * + * @param string $method Uppercase request method (GET, POST etc) + * @static + */ + public static function isMethod($method) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->isMethod($method); + } + /** + * Checks whether or not the method is safe. + * + * @see https://tools.ietf.org/html/rfc7231#section-4.2.1 + * @static + */ + public static function isMethodSafe() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->isMethodSafe(); + } + /** + * Checks whether or not the method is idempotent. + * + * @static + */ + public static function isMethodIdempotent() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->isMethodIdempotent(); + } + /** + * Checks whether the method is cacheable or not. + * + * @see https://tools.ietf.org/html/rfc7231#section-4.2.3 + * @static + */ + public static function isMethodCacheable() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->isMethodCacheable(); + } + /** + * Returns the protocol version. + * + * If the application is behind a proxy, the protocol version used in the + * requests between the client and the proxy and between the proxy and the + * server might be different. This returns the former (from the "Via" header) + * if the proxy is trusted (see "setTrustedProxies()"), otherwise it returns + * the latter (from the "SERVER_PROTOCOL" server parameter). + * + * @static + */ + public static function getProtocolVersion() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getProtocolVersion(); + } + /** + * Returns the request body content. + * + * @param bool $asResource If true, a resource will be returned + * @return string|resource + * @psalm-return ($asResource is true ? resource : string) + * @static + */ + public static function getContent($asResource = false) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getContent($asResource); + } + /** + * Gets the Etags. + * + * @static + */ + public static function getETags() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getETags(); + } + /** + * + * + * @static + */ + public static function isNoCache() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->isNoCache(); + } + /** + * Gets the preferred format for the response by inspecting, in the following order: + * * the request format set using setRequestFormat; + * * the values of the Accept HTTP header. + * + * Note that if you use this method, you should send the "Vary: Accept" header + * in the response to prevent any issues with intermediary HTTP caches. + * + * @static + */ + public static function getPreferredFormat($default = 'html') + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getPreferredFormat($default); + } + /** + * Returns the preferred language. + * + * @param string[] $locales An array of ordered available locales + * @static + */ + public static function getPreferredLanguage($locales = null) + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getPreferredLanguage($locales); + } + /** + * Gets a list of languages acceptable by the client browser ordered in the user browser preferences. + * + * @return string[] + * @static + */ + public static function getLanguages() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getLanguages(); + } + /** + * Gets a list of charsets acceptable by the client browser in preferable order. + * + * @return string[] + * @static + */ + public static function getCharsets() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getCharsets(); + } + /** + * Gets a list of encodings acceptable by the client browser in preferable order. + * + * @return string[] + * @static + */ + public static function getEncodings() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getEncodings(); + } + /** + * Gets a list of content types acceptable by the client browser in preferable order. + * + * @return string[] + * @static + */ + public static function getAcceptableContentTypes() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->getAcceptableContentTypes(); + } + /** + * Returns true if the request is an XMLHttpRequest. + * + * It works if your JavaScript library sets an X-Requested-With HTTP header. + * It is known to work with common JavaScript frameworks: + * + * @see https://wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript + * @static + */ + public static function isXmlHttpRequest() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->isXmlHttpRequest(); + } + /** + * Checks whether the client browser prefers safe content or not according to RFC8674. + * + * @see https://tools.ietf.org/html/rfc8674 + * @static + */ + public static function preferSafeContent() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->preferSafeContent(); + } + /** + * Indicates whether this request originated from a trusted proxy. + * + * This can be useful to determine whether or not to trust the + * contents of a proxy-specific header. + * + * @static + */ + public static function isFromTrustedProxy() + { //Method inherited from \Symfony\Component\HttpFoundation\Request + /** @var \Illuminate\Http\Request $instance */ + return $instance->isFromTrustedProxy(); + } + /** + * Filter the given array of rules into an array of rules that are included in precognitive headers. + * + * @param array $rules + * @return array + * @static + */ + public static function filterPrecognitiveRules($rules) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->filterPrecognitiveRules($rules); + } + /** + * Determine if the request is attempting to be precognitive. + * + * @return bool + * @static + */ + public static function isAttemptingPrecognition() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->isAttemptingPrecognition(); + } + /** + * Determine if the request is precognitive. + * + * @return bool + * @static + */ + public static function isPrecognitive() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->isPrecognitive(); + } + /** + * Determine if the request is sending JSON. + * + * @return bool + * @static + */ + public static function isJson() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->isJson(); + } + /** + * Determine if the current request probably expects a JSON response. + * + * @return bool + * @static + */ + public static function expectsJson() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->expectsJson(); + } + /** + * Determine if the current request is asking for JSON. + * + * @return bool + * @static + */ + public static function wantsJson() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->wantsJson(); + } + /** + * Determines whether the current requests accepts a given content type. + * + * @param string|array $contentTypes + * @return bool + * @static + */ + public static function accepts($contentTypes) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->accepts($contentTypes); + } + /** + * Return the most suitable content type from the given array based on content negotiation. + * + * @param string|array $contentTypes + * @return string|null + * @static + */ + public static function prefers($contentTypes) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->prefers($contentTypes); + } + /** + * Determine if the current request accepts any content type. + * + * @return bool + * @static + */ + public static function acceptsAnyContentType() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->acceptsAnyContentType(); + } + /** + * Determines whether a request accepts JSON. + * + * @return bool + * @static + */ + public static function acceptsJson() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->acceptsJson(); + } + /** + * Determines whether a request accepts HTML. + * + * @return bool + * @static + */ + public static function acceptsHtml() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->acceptsHtml(); + } + /** + * Determine if the given content types match. + * + * @param string $actual + * @param string $type + * @return bool + * @static + */ + public static function matchesType($actual, $type) + { + return \Illuminate\Http\Request::matchesType($actual, $type); + } + /** + * Get the data format expected in the response. + * + * @param string $default + * @return string + * @static + */ + public static function format($default = 'html') + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->format($default); + } + /** + * Retrieve an old input item. + * + * @param string|null $key + * @param \Illuminate\Database\Eloquent\Model|string|array|null $default + * @return string|array|null + * @static + */ + public static function old($key = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->old($key, $default); + } + /** + * Flash the input for the current request to the session. + * + * @return void + * @static + */ + public static function flash() + { + /** @var \Illuminate\Http\Request $instance */ + $instance->flash(); + } + /** + * Flash only some of the input to the session. + * + * @param array|mixed $keys + * @return void + * @static + */ + public static function flashOnly($keys) + { + /** @var \Illuminate\Http\Request $instance */ + $instance->flashOnly($keys); + } + /** + * Flash only some of the input to the session. + * + * @param array|mixed $keys + * @return void + * @static + */ + public static function flashExcept($keys) + { + /** @var \Illuminate\Http\Request $instance */ + $instance->flashExcept($keys); + } + /** + * Flush all of the old input from the session. + * + * @return void + * @static + */ + public static function flush() + { + /** @var \Illuminate\Http\Request $instance */ + $instance->flush(); + } + /** + * Retrieve a server variable from the request. + * + * @param string|null $key + * @param string|array|null $default + * @return string|array|null + * @static + */ + public static function server($key = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->server($key, $default); + } + /** + * Determine if a header is set on the request. + * + * @param string $key + * @return bool + * @static + */ + public static function hasHeader($key) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->hasHeader($key); + } + /** + * Retrieve a header from the request. + * + * @param string|null $key + * @param string|array|null $default + * @return string|array|null + * @static + */ + public static function header($key = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->header($key, $default); + } + /** + * Get the bearer token from the request headers. + * + * @return string|null + * @static + */ + public static function bearerToken() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->bearerToken(); + } + /** + * Determine if the request contains a given input item key. + * + * @param string|array $key + * @return bool + * @static + */ + public static function exists($key) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->exists($key); + } + /** + * Determine if the request contains a given input item key. + * + * @param string|array $key + * @return bool + * @static + */ + public static function has($key) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->has($key); + } + /** + * Determine if the request contains any of the given inputs. + * + * @param string|array $keys + * @return bool + * @static + */ + public static function hasAny($keys) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->hasAny($keys); + } + /** + * Apply the callback if the request contains the given input item key. + * + * @param string $key + * @param callable $callback + * @param callable|null $default + * @return $this|mixed + * @static + */ + public static function whenHas($key, $callback, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->whenHas($key, $callback, $default); + } + /** + * Determine if the request contains a non-empty value for an input item. + * + * @param string|array $key + * @return bool + * @static + */ + public static function filled($key) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->filled($key); + } + /** + * Determine if the request contains an empty value for an input item. + * + * @param string|array $key + * @return bool + * @static + */ + public static function isNotFilled($key) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->isNotFilled($key); + } + /** + * Determine if the request contains a non-empty value for any of the given inputs. + * + * @param string|array $keys + * @return bool + * @static + */ + public static function anyFilled($keys) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->anyFilled($keys); + } + /** + * Apply the callback if the request contains a non-empty value for the given input item key. + * + * @param string $key + * @param callable $callback + * @param callable|null $default + * @return $this|mixed + * @static + */ + public static function whenFilled($key, $callback, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->whenFilled($key, $callback, $default); + } + /** + * Determine if the request is missing a given input item key. + * + * @param string|array $key + * @return bool + * @static + */ + public static function missing($key) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->missing($key); + } + /** + * Apply the callback if the request is missing the given input item key. + * + * @param string $key + * @param callable $callback + * @param callable|null $default + * @return $this|mixed + * @static + */ + public static function whenMissing($key, $callback, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->whenMissing($key, $callback, $default); + } + /** + * Get the keys for all of the input and files. + * + * @return array + * @static + */ + public static function keys() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->keys(); + } + /** + * Get all of the input and files for the request. + * + * @param array|mixed|null $keys + * @return array + * @static + */ + public static function all($keys = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->all($keys); + } + /** + * Retrieve an input item from the request. + * + * @param string|null $key + * @param mixed $default + * @return mixed + * @static + */ + public static function input($key = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->input($key, $default); + } + /** + * Retrieve input from the request as a Stringable instance. + * + * @param string $key + * @param mixed $default + * @return \Illuminate\Support\Stringable + * @static + */ + public static function str($key, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->str($key, $default); + } + /** + * Retrieve input from the request as a Stringable instance. + * + * @param string $key + * @param mixed $default + * @return \Illuminate\Support\Stringable + * @static + */ + public static function string($key, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->string($key, $default); + } + /** + * Retrieve input as a boolean value. + * + * Returns true when value is "1", "true", "on", and "yes". Otherwise, returns false. + * + * @param string|null $key + * @param bool $default + * @return bool + * @static + */ + public static function boolean($key = null, $default = false) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->boolean($key, $default); + } + /** + * Retrieve input as an integer value. + * + * @param string $key + * @param int $default + * @return int + * @static + */ + public static function integer($key, $default = 0) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->integer($key, $default); + } + /** + * Retrieve input as a float value. + * + * @param string $key + * @param float $default + * @return float + * @static + */ + public static function float($key, $default = 0.0) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->float($key, $default); + } + /** + * Retrieve input from the request as a Carbon instance. + * + * @param string $key + * @param string|null $format + * @param string|null $tz + * @return \Illuminate\Support\Carbon|null + * @throws \Carbon\Exceptions\InvalidFormatException + * @static + */ + public static function date($key, $format = null, $tz = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->date($key, $format, $tz); + } + /** + * Retrieve input from the request as an enum. + * + * @template TEnum + * @param string $key + * @param \Illuminate\Http\class-string $enumClass + * @return \Illuminate\Http\TEnum|null + * @static + */ + public static function enum($key, $enumClass) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->enum($key, $enumClass); + } + /** + * Retrieve input from the request as a collection. + * + * @param array|string|null $key + * @return \Illuminate\Support\Collection + * @static + */ + public static function collect($key = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->collect($key); + } + /** + * Get a subset containing the provided keys with values from the input data. + * + * @param array|mixed $keys + * @return array + * @static + */ + public static function only($keys) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->only($keys); + } + /** + * Get all of the input except for a specified array of items. + * + * @param array|mixed $keys + * @return array + * @static + */ + public static function except($keys) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->except($keys); + } + /** + * Retrieve a query string item from the request. + * + * @param string|null $key + * @param string|array|null $default + * @return string|array|null + * @static + */ + public static function query($key = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->query($key, $default); + } + /** + * Retrieve a request payload item from the request. + * + * @param string|null $key + * @param string|array|null $default + * @return string|array|null + * @static + */ + public static function post($key = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->post($key, $default); + } + /** + * Determine if a cookie is set on the request. + * + * @param string $key + * @return bool + * @static + */ + public static function hasCookie($key) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->hasCookie($key); + } + /** + * Retrieve a cookie from the request. + * + * @param string|null $key + * @param string|array|null $default + * @return string|array|null + * @static + */ + public static function cookie($key = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->cookie($key, $default); + } + /** + * Get an array of all of the files on the request. + * + * @return array + * @static + */ + public static function allFiles() + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->allFiles(); + } + /** + * Determine if the uploaded data contains a file. + * + * @param string $key + * @return bool + * @static + */ + public static function hasFile($key) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->hasFile($key); + } + /** + * Retrieve a file from the request. + * + * @param string|null $key + * @param mixed $default + * @return \Illuminate\Http\UploadedFile|\Illuminate\Http\UploadedFile[]|array|null + * @static + */ + public static function file($key = null, $default = null) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->file($key, $default); + } + /** + * Dump the request items and end the script. + * + * @param mixed $keys + * @return \Illuminate\Http\never + * @static + */ + public static function dd(...$keys) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->dd(...$keys); + } + /** + * Dump the items. + * + * @param mixed $keys + * @return \Illuminate\Http\Request + * @static + */ + public static function dump($keys = []) + { + /** @var \Illuminate\Http\Request $instance */ + return $instance->dump($keys); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Http\Request::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Http\Request::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Http\Request::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Http\Request::flushMacros(); + } + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestValidation() + * @param array $rules + * @param mixed $params + * @static + */ + public static function validate($rules, ...$params) + { + return \Illuminate\Http\Request::validate($rules, ...$params); + } + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestValidation() + * @param string $errorBag + * @param array $rules + * @param mixed $params + * @static + */ + public static function validateWithBag($errorBag, $rules, ...$params) + { + return \Illuminate\Http\Request::validateWithBag($errorBag, $rules, ...$params); + } + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestSignatureValidation() + * @param mixed $absolute + * @static + */ + public static function hasValidSignature($absolute = true) + { + return \Illuminate\Http\Request::hasValidSignature($absolute); + } + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestSignatureValidation() + * @static + */ + public static function hasValidRelativeSignature() + { + return \Illuminate\Http\Request::hasValidRelativeSignature(); + } + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestSignatureValidation() + * @param mixed $ignoreQuery + * @param mixed $absolute + * @static + */ + public static function hasValidSignatureWhileIgnoring($ignoreQuery = [], $absolute = true) + { + return \Illuminate\Http\Request::hasValidSignatureWhileIgnoring($ignoreQuery, $absolute); + } + + } + /** + * + * + * @see \Illuminate\Routing\ResponseFactory + */ + class Response { + /** + * Create a new response instance. + * + * @param mixed $content + * @param int $status + * @param array $headers + * @return \Illuminate\Http\Response + * @static + */ + public static function make($content = '', $status = 200, $headers = []) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->make($content, $status, $headers); + } + /** + * Create a new "no content" response. + * + * @param int $status + * @param array $headers + * @return \Illuminate\Http\Response + * @static + */ + public static function noContent($status = 204, $headers = []) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->noContent($status, $headers); + } + /** + * Create a new response for a given view. + * + * @param string|array $view + * @param array $data + * @param int $status + * @param array $headers + * @return \Illuminate\Http\Response + * @static + */ + public static function view($view, $data = [], $status = 200, $headers = []) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->view($view, $data, $status, $headers); + } + /** + * Create a new JSON response instance. + * + * @param mixed $data + * @param int $status + * @param array $headers + * @param int $options + * @return \Illuminate\Http\JsonResponse + * @static + */ + public static function json($data = [], $status = 200, $headers = [], $options = 0) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->json($data, $status, $headers, $options); + } + /** + * Create a new JSONP response instance. + * + * @param string $callback + * @param mixed $data + * @param int $status + * @param array $headers + * @param int $options + * @return \Illuminate\Http\JsonResponse + * @static + */ + public static function jsonp($callback, $data = [], $status = 200, $headers = [], $options = 0) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->jsonp($callback, $data, $status, $headers, $options); + } + /** + * Create a new streamed response instance. + * + * @param callable $callback + * @param int $status + * @param array $headers + * @return \Symfony\Component\HttpFoundation\StreamedResponse + * @static + */ + public static function stream($callback, $status = 200, $headers = []) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->stream($callback, $status, $headers); + } + /** + * Create a new streamed response instance as a file download. + * + * @param callable $callback + * @param string|null $name + * @param array $headers + * @param string|null $disposition + * @return \Symfony\Component\HttpFoundation\StreamedResponse + * @static + */ + public static function streamDownload($callback, $name = null, $headers = [], $disposition = 'attachment') + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->streamDownload($callback, $name, $headers, $disposition); + } + /** + * Create a new file download response. + * + * @param \SplFileInfo|string $file + * @param string|null $name + * @param array $headers + * @param string|null $disposition + * @return \Symfony\Component\HttpFoundation\BinaryFileResponse + * @static + */ + public static function download($file, $name = null, $headers = [], $disposition = 'attachment') + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->download($file, $name, $headers, $disposition); + } + /** + * Return the raw contents of a binary file. + * + * @param \SplFileInfo|string $file + * @param array $headers + * @return \Symfony\Component\HttpFoundation\BinaryFileResponse + * @static + */ + public static function file($file, $headers = []) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->file($file, $headers); + } + /** + * Create a new redirect response to the given path. + * + * @param string $path + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function redirectTo($path, $status = 302, $headers = [], $secure = null) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->redirectTo($path, $status, $headers, $secure); + } + /** + * Create a new redirect response to a named route. + * + * @param string $route + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function redirectToRoute($route, $parameters = [], $status = 302, $headers = []) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->redirectToRoute($route, $parameters, $status, $headers); + } + /** + * Create a new redirect response to a controller action. + * + * @param string $action + * @param mixed $parameters + * @param int $status + * @param array $headers + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function redirectToAction($action, $parameters = [], $status = 302, $headers = []) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->redirectToAction($action, $parameters, $status, $headers); + } + /** + * Create a new redirect response, while putting the current URL in the session. + * + * @param string $path + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function redirectGuest($path, $status = 302, $headers = [], $secure = null) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->redirectGuest($path, $status, $headers, $secure); + } + /** + * Create a new redirect response to the previously intended location. + * + * @param string $default + * @param int $status + * @param array $headers + * @param bool|null $secure + * @return \Illuminate\Http\RedirectResponse + * @static + */ + public static function redirectToIntended($default = '/', $status = 302, $headers = [], $secure = null) + { + /** @var \Illuminate\Routing\ResponseFactory $instance */ + return $instance->redirectToIntended($default, $status, $headers, $secure); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Routing\ResponseFactory::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Routing\ResponseFactory::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Routing\ResponseFactory::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Routing\ResponseFactory::flushMacros(); + } + + } + /** + * + * + * @method static \Illuminate\Routing\RouteRegistrar attribute(string $key, mixed $value) + * @method static \Illuminate\Routing\RouteRegistrar whereAlpha(array|string $parameters) + * @method static \Illuminate\Routing\RouteRegistrar whereAlphaNumeric(array|string $parameters) + * @method static \Illuminate\Routing\RouteRegistrar whereNumber(array|string $parameters) + * @method static \Illuminate\Routing\RouteRegistrar whereUlid(array|string $parameters) + * @method static \Illuminate\Routing\RouteRegistrar whereUuid(array|string $parameters) + * @method static \Illuminate\Routing\RouteRegistrar whereIn(array|string $parameters, array $values) + * @method static \Illuminate\Routing\RouteRegistrar as(string $value) + * @method static \Illuminate\Routing\RouteRegistrar controller(string $controller) + * @method static \Illuminate\Routing\RouteRegistrar domain(string $value) + * @method static \Illuminate\Routing\RouteRegistrar middleware(array|string|null $middleware) + * @method static \Illuminate\Routing\RouteRegistrar name(string $value) + * @method static \Illuminate\Routing\RouteRegistrar namespace(string|null $value) + * @method static \Illuminate\Routing\RouteRegistrar prefix(string $prefix) + * @method static \Illuminate\Routing\RouteRegistrar scopeBindings() + * @method static \Illuminate\Routing\RouteRegistrar where(array $where) + * @method static \Illuminate\Routing\RouteRegistrar withoutMiddleware(array|string $middleware) + * @method static \Illuminate\Routing\RouteRegistrar withoutScopedBindings() + * @see \Illuminate\Routing\Router + */ + class Route { + /** + * Register a new GET route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function get($uri, $action = null) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->get($uri, $action); + } + /** + * Register a new POST route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function post($uri, $action = null) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->post($uri, $action); + } + /** + * Register a new PUT route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function put($uri, $action = null) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->put($uri, $action); + } + /** + * Register a new PATCH route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function patch($uri, $action = null) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->patch($uri, $action); + } + /** + * Register a new DELETE route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function delete($uri, $action = null) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->delete($uri, $action); + } + /** + * Register a new OPTIONS route with the router. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function options($uri, $action = null) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->options($uri, $action); + } + /** + * Register a new route responding to all verbs. + * + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function any($uri, $action = null) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->any($uri, $action); + } + /** + * Register a new Fallback route with the router. + * + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function fallback($action) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->fallback($action); + } + /** + * Create a redirect from one URI to another. + * + * @param string $uri + * @param string $destination + * @param int $status + * @return \Illuminate\Routing\Route + * @static + */ + public static function redirect($uri, $destination, $status = 302) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->redirect($uri, $destination, $status); + } + /** + * Create a permanent redirect from one URI to another. + * + * @param string $uri + * @param string $destination + * @return \Illuminate\Routing\Route + * @static + */ + public static function permanentRedirect($uri, $destination) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->permanentRedirect($uri, $destination); + } + /** + * Register a new route that returns a view. + * + * @param string $uri + * @param string $view + * @param array $data + * @param int|array $status + * @param array $headers + * @return \Illuminate\Routing\Route + * @static + */ + public static function view($uri, $view, $data = [], $status = 200, $headers = []) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->view($uri, $view, $data, $status, $headers); + } + /** + * Register a new route with the given verbs. + * + * @param array|string $methods + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function match($methods, $uri, $action = null) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->match($methods, $uri, $action); + } + /** + * Register an array of resource controllers. + * + * @param array $resources + * @param array $options + * @return void + * @static + */ + public static function resources($resources, $options = []) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->resources($resources, $options); + } + /** + * Route a resource to a controller. + * + * @param string $name + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\PendingResourceRegistration + * @static + */ + public static function resource($name, $controller, $options = []) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->resource($name, $controller, $options); + } + /** + * Register an array of API resource controllers. + * + * @param array $resources + * @param array $options + * @return void + * @static + */ + public static function apiResources($resources, $options = []) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->apiResources($resources, $options); + } + /** + * Route an API resource to a controller. + * + * @param string $name + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\PendingResourceRegistration + * @static + */ + public static function apiResource($name, $controller, $options = []) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->apiResource($name, $controller, $options); + } + /** + * Register an array of singleton resource controllers. + * + * @param array $singletons + * @param array $options + * @return void + * @static + */ + public static function singletons($singletons, $options = []) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->singletons($singletons, $options); + } + /** + * Route a singleton resource to a controller. + * + * @param string $name + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\PendingSingletonResourceRegistration + * @static + */ + public static function singleton($name, $controller, $options = []) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->singleton($name, $controller, $options); + } + /** + * Register an array of API singleton resource controllers. + * + * @param array $singletons + * @param array $options + * @return void + * @static + */ + public static function apiSingletons($singletons, $options = []) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->apiSingletons($singletons, $options); + } + /** + * Route an API singleton resource to a controller. + * + * @param string $name + * @param string $controller + * @param array $options + * @return \Illuminate\Routing\PendingSingletonResourceRegistration + * @static + */ + public static function apiSingleton($name, $controller, $options = []) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->apiSingleton($name, $controller, $options); + } + /** + * Create a route group with shared attributes. + * + * @param array $attributes + * @param \Closure|array|string $routes + * @return \Illuminate\Routing\Router + * @static + */ + public static function group($attributes, $routes) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->group($attributes, $routes); + } + /** + * Merge the given array with the last group stack. + * + * @param array $new + * @param bool $prependExistingPrefix + * @return array + * @static + */ + public static function mergeWithLastGroup($new, $prependExistingPrefix = true) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->mergeWithLastGroup($new, $prependExistingPrefix); + } + /** + * Get the prefix from the last group on the stack. + * + * @return string + * @static + */ + public static function getLastGroupPrefix() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->getLastGroupPrefix(); + } + /** + * Add a route to the underlying route collection. + * + * @param array|string $methods + * @param string $uri + * @param array|string|callable|null $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function addRoute($methods, $uri, $action) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->addRoute($methods, $uri, $action); + } + /** + * Create a new Route object. + * + * @param array|string $methods + * @param string $uri + * @param mixed $action + * @return \Illuminate\Routing\Route + * @static + */ + public static function newRoute($methods, $uri, $action) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->newRoute($methods, $uri, $action); + } + /** + * Return the response returned by the given route. + * + * @param string $name + * @return \Symfony\Component\HttpFoundation\Response + * @static + */ + public static function respondWithRoute($name) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->respondWithRoute($name); + } + /** + * Dispatch the request to the application. + * + * @param \Illuminate\Http\Request $request + * @return \Symfony\Component\HttpFoundation\Response + * @static + */ + public static function dispatch($request) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->dispatch($request); + } + /** + * Dispatch the request to a route and return the response. + * + * @param \Illuminate\Http\Request $request + * @return \Symfony\Component\HttpFoundation\Response + * @static + */ + public static function dispatchToRoute($request) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->dispatchToRoute($request); + } + /** + * Gather the middleware for the given route with resolved class names. + * + * @param \Illuminate\Routing\Route $route + * @return array + * @static + */ + public static function gatherRouteMiddleware($route) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->gatherRouteMiddleware($route); + } + /** + * Resolve a flat array of middleware classes from the provided array. + * + * @param array $middleware + * @param array $excluded + * @return array + * @static + */ + public static function resolveMiddleware($middleware, $excluded = []) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->resolveMiddleware($middleware, $excluded); + } + /** + * Create a response instance from the given value. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param mixed $response + * @return \Symfony\Component\HttpFoundation\Response + * @static + */ + public static function prepareResponse($request, $response) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->prepareResponse($request, $response); + } + /** + * Static version of prepareResponse. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param mixed $response + * @return \Symfony\Component\HttpFoundation\Response + * @static + */ + public static function toResponse($request, $response) + { + return \Illuminate\Routing\Router::toResponse($request, $response); + } + /** + * Substitute the route bindings onto the route. + * + * @param \Illuminate\Routing\Route $route + * @return \Illuminate\Routing\Route + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model> + * @throws \Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException + * @static + */ + public static function substituteBindings($route) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->substituteBindings($route); + } + /** + * Substitute the implicit route bindings for the given route. + * + * @param \Illuminate\Routing\Route $route + * @return void + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model> + * @throws \Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException + * @static + */ + public static function substituteImplicitBindings($route) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->substituteImplicitBindings($route); + } + /** + * Register a route matched event listener. + * + * @param string|callable $callback + * @return void + * @static + */ + public static function matched($callback) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->matched($callback); + } + /** + * Get all of the defined middleware short-hand names. + * + * @return array + * @static + */ + public static function getMiddleware() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->getMiddleware(); + } + /** + * Register a short-hand name for a middleware. + * + * @param string $name + * @param string $class + * @return \Illuminate\Routing\Router + * @static + */ + public static function aliasMiddleware($name, $class) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->aliasMiddleware($name, $class); + } + /** + * Check if a middlewareGroup with the given name exists. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMiddlewareGroup($name) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->hasMiddlewareGroup($name); + } + /** + * Get all of the defined middleware groups. + * + * @return array + * @static + */ + public static function getMiddlewareGroups() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->getMiddlewareGroups(); + } + /** + * Register a group of middleware. + * + * @param string $name + * @param array $middleware + * @return \Illuminate\Routing\Router + * @static + */ + public static function middlewareGroup($name, $middleware) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->middlewareGroup($name, $middleware); + } + /** + * Add a middleware to the beginning of a middleware group. + * + * If the middleware is already in the group, it will not be added again. + * + * @param string $group + * @param string $middleware + * @return \Illuminate\Routing\Router + * @static + */ + public static function prependMiddlewareToGroup($group, $middleware) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->prependMiddlewareToGroup($group, $middleware); + } + /** + * Add a middleware to the end of a middleware group. + * + * If the middleware is already in the group, it will not be added again. + * + * @param string $group + * @param string $middleware + * @return \Illuminate\Routing\Router + * @static + */ + public static function pushMiddlewareToGroup($group, $middleware) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->pushMiddlewareToGroup($group, $middleware); + } + /** + * Remove the given middleware from the specified group. + * + * @param string $group + * @param string $middleware + * @return \Illuminate\Routing\Router + * @static + */ + public static function removeMiddlewareFromGroup($group, $middleware) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->removeMiddlewareFromGroup($group, $middleware); + } + /** + * Flush the router's middleware groups. + * + * @return \Illuminate\Routing\Router + * @static + */ + public static function flushMiddlewareGroups() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->flushMiddlewareGroups(); + } + /** + * Add a new route parameter binder. + * + * @param string $key + * @param string|callable $binder + * @return void + * @static + */ + public static function bind($key, $binder) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->bind($key, $binder); + } + /** + * Register a model binder for a wildcard. + * + * @param string $key + * @param string $class + * @param \Closure|null $callback + * @return void + * @static + */ + public static function model($key, $class, $callback = null) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->model($key, $class, $callback); + } + /** + * Get the binding callback for a given binding. + * + * @param string $key + * @return \Closure|null + * @static + */ + public static function getBindingCallback($key) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->getBindingCallback($key); + } + /** + * Get the global "where" patterns. + * + * @return array + * @static + */ + public static function getPatterns() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->getPatterns(); + } + /** + * Set a global where pattern on all routes. + * + * @param string $key + * @param string $pattern + * @return void + * @static + */ + public static function pattern($key, $pattern) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->pattern($key, $pattern); + } + /** + * Set a group of global where patterns on all routes. + * + * @param array $patterns + * @return void + * @static + */ + public static function patterns($patterns) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->patterns($patterns); + } + /** + * Determine if the router currently has a group stack. + * + * @return bool + * @static + */ + public static function hasGroupStack() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->hasGroupStack(); + } + /** + * Get the current group stack for the router. + * + * @return array + * @static + */ + public static function getGroupStack() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->getGroupStack(); + } + /** + * Get a route parameter for the current route. + * + * @param string $key + * @param string|null $default + * @return mixed + * @static + */ + public static function input($key, $default = null) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->input($key, $default); + } + /** + * Get the request currently being dispatched. + * + * @return \Illuminate\Http\Request + * @static + */ + public static function getCurrentRequest() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->getCurrentRequest(); + } + /** + * Get the currently dispatched route instance. + * + * @return \Illuminate\Routing\Route|null + * @static + */ + public static function getCurrentRoute() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->getCurrentRoute(); + } + /** + * Get the currently dispatched route instance. + * + * @return \Illuminate\Routing\Route|null + * @static + */ + public static function current() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->current(); + } + /** + * Check if a route with the given name exists. + * + * @param string|array $name + * @return bool + * @static + */ + public static function has($name) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->has($name); + } + /** + * Get the current route name. + * + * @return string|null + * @static + */ + public static function currentRouteName() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->currentRouteName(); + } + /** + * Alias for the "currentRouteNamed" method. + * + * @param mixed $patterns + * @return bool + * @static + */ + public static function is(...$patterns) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->is(...$patterns); + } + /** + * Determine if the current route matches a pattern. + * + * @param mixed $patterns + * @return bool + * @static + */ + public static function currentRouteNamed(...$patterns) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->currentRouteNamed(...$patterns); + } + /** + * Get the current route action. + * + * @return string|null + * @static + */ + public static function currentRouteAction() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->currentRouteAction(); + } + /** + * Alias for the "currentRouteUses" method. + * + * @param array $patterns + * @return bool + * @static + */ + public static function uses(...$patterns) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->uses(...$patterns); + } + /** + * Determine if the current route action matches a given action. + * + * @param string $action + * @return bool + * @static + */ + public static function currentRouteUses($action) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->currentRouteUses($action); + } + /** + * Set the unmapped global resource parameters to singular. + * + * @param bool $singular + * @return void + * @static + */ + public static function singularResourceParameters($singular = true) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->singularResourceParameters($singular); + } + /** + * Set the global resource parameter mapping. + * + * @param array $parameters + * @return void + * @static + */ + public static function resourceParameters($parameters = []) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->resourceParameters($parameters); + } + /** + * Get or set the verbs used in the resource URIs. + * + * @param array $verbs + * @return array|null + * @static + */ + public static function resourceVerbs($verbs = []) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->resourceVerbs($verbs); + } + /** + * Get the underlying route collection. + * + * @return \Illuminate\Routing\RouteCollectionInterface + * @static + */ + public static function getRoutes() + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->getRoutes(); + } + /** + * Set the route collection instance. + * + * @param \Illuminate\Routing\RouteCollection $routes + * @return void + * @static + */ + public static function setRoutes($routes) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->setRoutes($routes); + } + /** + * Set the compiled route collection instance. + * + * @param array $routes + * @return void + * @static + */ + public static function setCompiledRoutes($routes) + { + /** @var \Illuminate\Routing\Router $instance */ + $instance->setCompiledRoutes($routes); + } + /** + * Remove any duplicate middleware from the given array. + * + * @param array $middleware + * @return array + * @static + */ + public static function uniqueMiddleware($middleware) + { + return \Illuminate\Routing\Router::uniqueMiddleware($middleware); + } + /** + * Set the container instance used by the router. + * + * @param \Illuminate\Container\Container $container + * @return \Illuminate\Routing\Router + * @static + */ + public static function setContainer($container) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->setContainer($container); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Routing\Router::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Routing\Router::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Routing\Router::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Routing\Router::flushMacros(); + } + /** + * Dynamically handle calls to the class. + * + * @param string $method + * @param array $parameters + * @return mixed + * @throws \BadMethodCallException + * @static + */ + public static function macroCall($method, $parameters) + { + /** @var \Illuminate\Routing\Router $instance */ + return $instance->macroCall($method, $parameters); + } + /** + * + * + * @see \Laravel\Ui\AuthRouteMethods::auth() + * @param mixed $options + * @static + */ + public static function auth($options = []) + { + return \Illuminate\Routing\Router::auth($options); + } + /** + * + * + * @see \Laravel\Ui\AuthRouteMethods::resetPassword() + * @static + */ + public static function resetPassword() + { + return \Illuminate\Routing\Router::resetPassword(); + } + /** + * + * + * @see \Laravel\Ui\AuthRouteMethods::confirmPassword() + * @static + */ + public static function confirmPassword() + { + return \Illuminate\Routing\Router::confirmPassword(); + } + /** + * + * + * @see \Laravel\Ui\AuthRouteMethods::emailVerification() + * @static + */ + public static function emailVerification() + { + return \Illuminate\Routing\Router::emailVerification(); + } + + } + /** + * + * + * @see \Illuminate\Database\Schema\Builder + */ + class Schema { + /** + * Create a database in the schema. + * + * @param string $name + * @return bool + * @static + */ + public static function createDatabase($name) + { + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->createDatabase($name); + } + /** + * Drop a database from the schema if the database exists. + * + * @param string $name + * @return bool + * @static + */ + public static function dropDatabaseIfExists($name) + { + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->dropDatabaseIfExists($name); + } + /** + * Determine if the given table exists. + * + * @param string $table + * @return bool + * @static + */ + public static function hasTable($table) + { + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->hasTable($table); + } + /** + * Get the column listing for a given table. + * + * @param string $table + * @return array + * @static + */ + public static function getColumnListing($table) + { + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->getColumnListing($table); + } + /** + * Drop all tables from the database. + * + * @return void + * @static + */ + public static function dropAllTables() + { + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->dropAllTables(); + } + /** + * Drop all views from the database. + * + * @return void + * @static + */ + public static function dropAllViews() + { + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->dropAllViews(); + } + /** + * Get all of the table names for the database. + * + * @return array + * @static + */ + public static function getAllTables() + { + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->getAllTables(); + } + /** + * Get all of the view names for the database. + * + * @return array + * @static + */ + public static function getAllViews() + { + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->getAllViews(); + } + /** + * Set the default string length for migrations. + * + * @param int $length + * @return void + * @static + */ + public static function defaultStringLength($length) + { //Method inherited from \Illuminate\Database\Schema\Builder + \Illuminate\Database\Schema\MySqlBuilder::defaultStringLength($length); + } + /** + * Set the default morph key type for migrations. + * + * @param string $type + * @return void + * @throws \InvalidArgumentException + * @static + */ + public static function defaultMorphKeyType($type) + { //Method inherited from \Illuminate\Database\Schema\Builder + \Illuminate\Database\Schema\MySqlBuilder::defaultMorphKeyType($type); + } + /** + * Set the default morph key type for migrations to UUIDs. + * + * @return void + * @static + */ + public static function morphUsingUuids() + { //Method inherited from \Illuminate\Database\Schema\Builder + \Illuminate\Database\Schema\MySqlBuilder::morphUsingUuids(); + } + /** + * Set the default morph key type for migrations to ULIDs. + * + * @return void + * @static + */ + public static function morphUsingUlids() + { //Method inherited from \Illuminate\Database\Schema\Builder + \Illuminate\Database\Schema\MySqlBuilder::morphUsingUlids(); + } + /** + * Attempt to use native schema operations for dropping and renaming columns, even if Doctrine DBAL is installed. + * + * @param bool $value + * @return void + * @static + */ + public static function useNativeSchemaOperationsIfPossible($value = true) + { //Method inherited from \Illuminate\Database\Schema\Builder + \Illuminate\Database\Schema\MySqlBuilder::useNativeSchemaOperationsIfPossible($value); + } + /** + * Determine if the given table has a given column. + * + * @param string $table + * @param string $column + * @return bool + * @static + */ + public static function hasColumn($table, $column) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->hasColumn($table, $column); + } + /** + * Determine if the given table has given columns. + * + * @param string $table + * @param array $columns + * @return bool + * @static + */ + public static function hasColumns($table, $columns) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->hasColumns($table, $columns); + } + /** + * Execute a table builder callback if the given table has a given column. + * + * @param string $table + * @param string $column + * @param \Closure $callback + * @return void + * @static + */ + public static function whenTableHasColumn($table, $column, $callback) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->whenTableHasColumn($table, $column, $callback); + } + /** + * Execute a table builder callback if the given table doesn't have a given column. + * + * @param string $table + * @param string $column + * @param \Closure $callback + * @return void + * @static + */ + public static function whenTableDoesntHaveColumn($table, $column, $callback) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->whenTableDoesntHaveColumn($table, $column, $callback); + } + /** + * Get the data type for the given column name. + * + * @param string $table + * @param string $column + * @return string + * @static + */ + public static function getColumnType($table, $column) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->getColumnType($table, $column); + } + /** + * Modify a table on the schema. + * + * @param string $table + * @param \Closure $callback + * @return void + * @static + */ + public static function table($table, $callback) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->table($table, $callback); + } + /** + * Create a new table on the schema. + * + * @param string $table + * @param \Closure $callback + * @return void + * @static + */ + public static function create($table, $callback) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->create($table, $callback); + } + /** + * Drop a table from the schema. + * + * @param string $table + * @return void + * @static + */ + public static function drop($table) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->drop($table); + } + /** + * Drop a table from the schema if it exists. + * + * @param string $table + * @return void + * @static + */ + public static function dropIfExists($table) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->dropIfExists($table); + } + /** + * Drop columns from a table schema. + * + * @param string $table + * @param string|array $columns + * @return void + * @static + */ + public static function dropColumns($table, $columns) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->dropColumns($table, $columns); + } + /** + * Drop all types from the database. + * + * @return void + * @throws \LogicException + * @static + */ + public static function dropAllTypes() + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->dropAllTypes(); + } + /** + * Rename a table on the schema. + * + * @param string $from + * @param string $to + * @return void + * @static + */ + public static function rename($from, $to) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->rename($from, $to); + } + /** + * Enable foreign key constraints. + * + * @return bool + * @static + */ + public static function enableForeignKeyConstraints() + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->enableForeignKeyConstraints(); + } + /** + * Disable foreign key constraints. + * + * @return bool + * @static + */ + public static function disableForeignKeyConstraints() + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->disableForeignKeyConstraints(); + } + /** + * Disable foreign key constraints during the execution of a callback. + * + * @param \Closure $callback + * @return mixed + * @static + */ + public static function withoutForeignKeyConstraints($callback) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->withoutForeignKeyConstraints($callback); + } + /** + * Get the database connection instance. + * + * @return \Illuminate\Database\Connection + * @static + */ + public static function getConnection() + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->getConnection(); + } + /** + * Set the database connection instance. + * + * @param \Illuminate\Database\Connection $connection + * @return \Illuminate\Database\Schema\MySqlBuilder + * @static + */ + public static function setConnection($connection) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + return $instance->setConnection($connection); + } + /** + * Set the Schema Blueprint resolver callback. + * + * @param \Closure $resolver + * @return void + * @static + */ + public static function blueprintResolver($resolver) + { //Method inherited from \Illuminate\Database\Schema\Builder + /** @var \Illuminate\Database\Schema\MySqlBuilder $instance */ + $instance->blueprintResolver($resolver); + } + + } + /** + * + * + * @see \Illuminate\Session\SessionManager + */ + class Session { + /** + * Determine if requests for the same session should wait for each to finish before executing. + * + * @return bool + * @static + */ + public static function shouldBlock() + { + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->shouldBlock(); + } + /** + * Get the name of the cache store / driver that should be used to acquire session locks. + * + * @return string|null + * @static + */ + public static function blockDriver() + { + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->blockDriver(); + } + /** + * Get the session configuration. + * + * @return array + * @static + */ + public static function getSessionConfig() + { + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->getSessionConfig(); + } + /** + * Get the default session driver name. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Set the default session driver name. + * + * @param string $name + * @return void + * @static + */ + public static function setDefaultDriver($name) + { + /** @var \Illuminate\Session\SessionManager $instance */ + $instance->setDefaultDriver($name); + } + /** + * Get a driver instance. + * + * @param string|null $driver + * @return mixed + * @throws \InvalidArgumentException + * @static + */ + public static function driver($driver = null) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->driver($driver); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Session\SessionManager + * @static + */ + public static function extend($driver, $callback) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Get all of the created "drivers". + * + * @return array + * @static + */ + public static function getDrivers() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->getDrivers(); + } + /** + * Get the container instance used by the manager. + * + * @return \Illuminate\Contracts\Container\Container + * @static + */ + public static function getContainer() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->getContainer(); + } + /** + * Set the container instance used by the manager. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return \Illuminate\Session\SessionManager + * @static + */ + public static function setContainer($container) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->setContainer($container); + } + /** + * Forget all of the resolved driver instances. + * + * @return \Illuminate\Session\SessionManager + * @static + */ + public static function forgetDrivers() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Illuminate\Session\SessionManager $instance */ + return $instance->forgetDrivers(); + } + /** + * Start the session, reading the data from a handler. + * + * @return bool + * @static + */ + public static function start() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->start(); + } + /** + * Save the session data to storage. + * + * @return void + * @static + */ + public static function save() + { + /** @var \Illuminate\Session\Store $instance */ + $instance->save(); + } + /** + * Age the flash data for the session. + * + * @return void + * @static + */ + public static function ageFlashData() + { + /** @var \Illuminate\Session\Store $instance */ + $instance->ageFlashData(); + } + /** + * Get all of the session data. + * + * @return array + * @static + */ + public static function all() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->all(); + } + /** + * Get a subset of the session data. + * + * @param array $keys + * @return array + * @static + */ + public static function only($keys) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->only($keys); + } + /** + * Checks if a key exists. + * + * @param string|array $key + * @return bool + * @static + */ + public static function exists($key) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->exists($key); + } + /** + * Determine if the given key is missing from the session data. + * + * @param string|array $key + * @return bool + * @static + */ + public static function missing($key) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->missing($key); + } + /** + * Checks if a key is present and not null. + * + * @param string|array $key + * @return bool + * @static + */ + public static function has($key) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->has($key); + } + /** + * Get an item from the session. + * + * @param string $key + * @param mixed $default + * @return mixed + * @static + */ + public static function get($key, $default = null) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->get($key, $default); + } + /** + * Get the value of a given key and then forget it. + * + * @param string $key + * @param mixed $default + * @return mixed + * @static + */ + public static function pull($key, $default = null) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->pull($key, $default); + } + /** + * Determine if the session contains old input. + * + * @param string|null $key + * @return bool + * @static + */ + public static function hasOldInput($key = null) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->hasOldInput($key); + } + /** + * Get the requested item from the flashed input array. + * + * @param string|null $key + * @param mixed $default + * @return mixed + * @static + */ + public static function getOldInput($key = null, $default = null) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->getOldInput($key, $default); + } + /** + * Replace the given session attributes entirely. + * + * @param array $attributes + * @return void + * @static + */ + public static function replace($attributes) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->replace($attributes); + } + /** + * Put a key / value pair or array of key / value pairs in the session. + * + * @param string|array $key + * @param mixed $value + * @return void + * @static + */ + public static function put($key, $value = null) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->put($key, $value); + } + /** + * Get an item from the session, or store the default value. + * + * @param string $key + * @param \Closure $callback + * @return mixed + * @static + */ + public static function remember($key, $callback) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->remember($key, $callback); + } + /** + * Push a value onto a session array. + * + * @param string $key + * @param mixed $value + * @return void + * @static + */ + public static function push($key, $value) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->push($key, $value); + } + /** + * Increment the value of an item in the session. + * + * @param string $key + * @param int $amount + * @return mixed + * @static + */ + public static function increment($key, $amount = 1) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->increment($key, $amount); + } + /** + * Decrement the value of an item in the session. + * + * @param string $key + * @param int $amount + * @return int + * @static + */ + public static function decrement($key, $amount = 1) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->decrement($key, $amount); + } + /** + * Flash a key / value pair to the session. + * + * @param string $key + * @param mixed $value + * @return void + * @static + */ + public static function flash($key, $value = true) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->flash($key, $value); + } + /** + * Flash a key / value pair to the session for immediate use. + * + * @param string $key + * @param mixed $value + * @return void + * @static + */ + public static function now($key, $value) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->now($key, $value); + } + /** + * Reflash all of the session flash data. + * + * @return void + * @static + */ + public static function reflash() + { + /** @var \Illuminate\Session\Store $instance */ + $instance->reflash(); + } + /** + * Reflash a subset of the current flash data. + * + * @param array|mixed $keys + * @return void + * @static + */ + public static function keep($keys = null) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->keep($keys); + } + /** + * Flash an input array to the session. + * + * @param array $value + * @return void + * @static + */ + public static function flashInput($value) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->flashInput($value); + } + /** + * Remove an item from the session, returning its value. + * + * @param string $key + * @return mixed + * @static + */ + public static function remove($key) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->remove($key); + } + /** + * Remove one or many items from the session. + * + * @param string|array $keys + * @return void + * @static + */ + public static function forget($keys) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->forget($keys); + } + /** + * Remove all of the items from the session. + * + * @return void + * @static + */ + public static function flush() + { + /** @var \Illuminate\Session\Store $instance */ + $instance->flush(); + } + /** + * Flush the session data and regenerate the ID. + * + * @return bool + * @static + */ + public static function invalidate() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->invalidate(); + } + /** + * Generate a new session identifier. + * + * @param bool $destroy + * @return bool + * @static + */ + public static function regenerate($destroy = false) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->regenerate($destroy); + } + /** + * Generate a new session ID for the session. + * + * @param bool $destroy + * @return bool + * @static + */ + public static function migrate($destroy = false) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->migrate($destroy); + } + /** + * Determine if the session has been started. + * + * @return bool + * @static + */ + public static function isStarted() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->isStarted(); + } + /** + * Get the name of the session. + * + * @return string + * @static + */ + public static function getName() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->getName(); + } + /** + * Set the name of the session. + * + * @param string $name + * @return void + * @static + */ + public static function setName($name) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->setName($name); + } + /** + * Get the current session ID. + * + * @return string + * @static + */ + public static function getId() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->getId(); + } + /** + * Set the session ID. + * + * @param string|null $id + * @return void + * @static + */ + public static function setId($id) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->setId($id); + } + /** + * Determine if this is a valid session ID. + * + * @param string|null $id + * @return bool + * @static + */ + public static function isValidId($id) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->isValidId($id); + } + /** + * Set the existence of the session on the handler if applicable. + * + * @param bool $value + * @return void + * @static + */ + public static function setExists($value) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->setExists($value); + } + /** + * Get the CSRF token value. + * + * @return string + * @static + */ + public static function token() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->token(); + } + /** + * Regenerate the CSRF token value. + * + * @return void + * @static + */ + public static function regenerateToken() + { + /** @var \Illuminate\Session\Store $instance */ + $instance->regenerateToken(); + } + /** + * Get the previous URL from the session. + * + * @return string|null + * @static + */ + public static function previousUrl() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->previousUrl(); + } + /** + * Set the "previous" URL in the session. + * + * @param string $url + * @return void + * @static + */ + public static function setPreviousUrl($url) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->setPreviousUrl($url); + } + /** + * Specify that the user has confirmed their password. + * + * @return void + * @static + */ + public static function passwordConfirmed() + { + /** @var \Illuminate\Session\Store $instance */ + $instance->passwordConfirmed(); + } + /** + * Get the underlying session handler implementation. + * + * @return \SessionHandlerInterface + * @static + */ + public static function getHandler() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->getHandler(); + } + /** + * Set the underlying session handler implementation. + * + * @param \SessionHandlerInterface $handler + * @return \SessionHandlerInterface + * @static + */ + public static function setHandler($handler) + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->setHandler($handler); + } + /** + * Determine if the session handler needs a request. + * + * @return bool + * @static + */ + public static function handlerNeedsRequest() + { + /** @var \Illuminate\Session\Store $instance */ + return $instance->handlerNeedsRequest(); + } + /** + * Set the request on the handler instance. + * + * @param \Illuminate\Http\Request $request + * @return void + * @static + */ + public static function setRequestOnHandler($request) + { + /** @var \Illuminate\Session\Store $instance */ + $instance->setRequestOnHandler($request); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Session\Store::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Session\Store::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Session\Store::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Session\Store::flushMacros(); + } + + } + /** + * + * + * @method static bool has(string $location) + * @method static string read(string $location) + * @method static \League\Flysystem\DirectoryListing listContents(string $location, bool $deep = false) + * @method static int fileSize(string $path) + * @method static string visibility(string $path) + * @method static void write(string $location, string $contents, array $config = []) + * @method static void createDirectory(string $location, array $config = []) + * @see \Illuminate\Filesystem\FilesystemManager + */ + class Storage { + /** + * Get a filesystem instance. + * + * @param string|null $name + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function drive($name = null) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->drive($name); + } + /** + * Get a filesystem instance. + * + * @param string|null $name + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function disk($name = null) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->disk($name); + } + /** + * Get a default cloud filesystem instance. + * + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function cloud() + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->cloud(); + } + /** + * Build an on-demand disk. + * + * @param string|array $config + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function build($config) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->build($config); + } + /** + * Create an instance of the local driver. + * + * @param array $config + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function createLocalDriver($config) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->createLocalDriver($config); + } + /** + * Create an instance of the ftp driver. + * + * @param array $config + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function createFtpDriver($config) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->createFtpDriver($config); + } + /** + * Create an instance of the sftp driver. + * + * @param array $config + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function createSftpDriver($config) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->createSftpDriver($config); + } + /** + * Create an instance of the Amazon S3 driver. + * + * @param array $config + * @return \Illuminate\Contracts\Filesystem\Cloud + * @static + */ + public static function createS3Driver($config) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->createS3Driver($config); + } + /** + * Create a scoped driver. + * + * @param array $config + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function createScopedDriver($config) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->createScopedDriver($config); + } + /** + * Set the given disk instance. + * + * @param string $name + * @param mixed $disk + * @return \Illuminate\Filesystem\FilesystemManager + * @static + */ + public static function set($name, $disk) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->set($name, $disk); + } + /** + * Get the default driver name. + * + * @return string + * @static + */ + public static function getDefaultDriver() + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Get the default cloud driver name. + * + * @return string + * @static + */ + public static function getDefaultCloudDriver() + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->getDefaultCloudDriver(); + } + /** + * Unset the given disk instances. + * + * @param array|string $disk + * @return \Illuminate\Filesystem\FilesystemManager + * @static + */ + public static function forgetDisk($disk) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->forgetDisk($disk); + } + /** + * Disconnect the given disk and remove from local cache. + * + * @param string|null $name + * @return void + * @static + */ + public static function purge($name = null) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + $instance->purge($name); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Filesystem\FilesystemManager + * @static + */ + public static function extend($driver, $callback) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Set the application instance used by the manager. + * + * @param \Illuminate\Contracts\Foundation\Application $app + * @return \Illuminate\Filesystem\FilesystemManager + * @static + */ + public static function setApplication($app) + { + /** @var \Illuminate\Filesystem\FilesystemManager $instance */ + return $instance->setApplication($app); + } + /** + * Assert that the given file or directory exists. + * + * @param string|array $path + * @param string|null $content + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function assertExists($path, $content = null) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->assertExists($path, $content); + } + /** + * Assert that the given file or directory does not exist. + * + * @param string|array $path + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function assertMissing($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->assertMissing($path); + } + /** + * Assert that the given directory is empty. + * + * @param string $path + * @return \Illuminate\Filesystem\FilesystemAdapter + * @static + */ + public static function assertDirectoryEmpty($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->assertDirectoryEmpty($path); + } + /** + * Determine if a file or directory exists. + * + * @param string $path + * @return bool + * @static + */ + public static function exists($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->exists($path); + } + /** + * Determine if a file or directory is missing. + * + * @param string $path + * @return bool + * @static + */ + public static function missing($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->missing($path); + } + /** + * Determine if a file exists. + * + * @param string $path + * @return bool + * @static + */ + public static function fileExists($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->fileExists($path); + } + /** + * Determine if a file is missing. + * + * @param string $path + * @return bool + * @static + */ + public static function fileMissing($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->fileMissing($path); + } + /** + * Determine if a directory exists. + * + * @param string $path + * @return bool + * @static + */ + public static function directoryExists($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->directoryExists($path); + } + /** + * Determine if a directory is missing. + * + * @param string $path + * @return bool + * @static + */ + public static function directoryMissing($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->directoryMissing($path); + } + /** + * Get the full path for the file at the given "short" path. + * + * @param string $path + * @return string + * @static + */ + public static function path($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->path($path); + } + /** + * Get the contents of a file. + * + * @param string $path + * @return string|null + * @static + */ + public static function get($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->get($path); + } + /** + * Create a streamed response for a given file. + * + * @param string $path + * @param string|null $name + * @param array $headers + * @param string|null $disposition + * @return \Symfony\Component\HttpFoundation\StreamedResponse + * @static + */ + public static function response($path, $name = null, $headers = [], $disposition = 'inline') + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->response($path, $name, $headers, $disposition); + } + /** + * Create a streamed download response for a given file. + * + * @param string $path + * @param string|null $name + * @return \Symfony\Component\HttpFoundation\StreamedResponse + * @static + */ + public static function download($path, $name = null, $headers = []) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->download($path, $name, $headers); + } + /** + * Write the contents of a file. + * + * @param string $path + * @param \Psr\Http\Message\StreamInterface|\Illuminate\Http\File|\Illuminate\Http\UploadedFile|string|resource $contents + * @param mixed $options + * @return string|bool + * @static + */ + public static function put($path, $contents, $options = []) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->put($path, $contents, $options); + } + /** + * Store the uploaded file on the disk. + * + * @param string $path + * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $file + * @param mixed $options + * @return string|false + * @static + */ + public static function putFile($path, $file, $options = []) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->putFile($path, $file, $options); + } + /** + * Store the uploaded file on the disk with a given name. + * + * @param string $path + * @param \Illuminate\Http\File|\Illuminate\Http\UploadedFile|string $file + * @param string $name + * @param mixed $options + * @return string|false + * @static + */ + public static function putFileAs($path, $file, $name, $options = []) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->putFileAs($path, $file, $name, $options); + } + /** + * Get the visibility for the given path. + * + * @param string $path + * @return string + * @static + */ + public static function getVisibility($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->getVisibility($path); + } + /** + * Set the visibility for the given path. + * + * @param string $path + * @param string $visibility + * @return bool + * @static + */ + public static function setVisibility($path, $visibility) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->setVisibility($path, $visibility); + } + /** + * Prepend to a file. + * + * @param string $path + * @param string $data + * @param string $separator + * @return bool + * @static + */ + public static function prepend($path, $data, $separator = ' +') + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->prepend($path, $data, $separator); + } + /** + * Append to a file. + * + * @param string $path + * @param string $data + * @param string $separator + * @return bool + * @static + */ + public static function append($path, $data, $separator = ' +') + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->append($path, $data, $separator); + } + /** + * Delete the file at a given path. + * + * @param string|array $paths + * @return bool + * @static + */ + public static function delete($paths) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->delete($paths); + } + /** + * Copy a file to a new location. + * + * @param string $from + * @param string $to + * @return bool + * @static + */ + public static function copy($from, $to) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->copy($from, $to); + } + /** + * Move a file to a new location. + * + * @param string $from + * @param string $to + * @return bool + * @static + */ + public static function move($from, $to) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->move($from, $to); + } + /** + * Get the file size of a given file. + * + * @param string $path + * @return int + * @static + */ + public static function size($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->size($path); + } + /** + * Get the checksum for a file. + * + * @return string|false + * @throws UnableToProvideChecksum + * @static + */ + public static function checksum($path, $options = []) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->checksum($path, $options); + } + /** + * Get the mime-type of a given file. + * + * @param string $path + * @return string|false + * @static + */ + public static function mimeType($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->mimeType($path); + } + /** + * Get the file's last modification time. + * + * @param string $path + * @return int + * @static + */ + public static function lastModified($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->lastModified($path); + } + /** + * Get a resource to read the file. + * + * @param string $path + * @return resource|null The path resource or null on failure. + * @static + */ + public static function readStream($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->readStream($path); + } + /** + * Write a new file using a stream. + * + * @param string $path + * @param resource $resource + * @param array $options + * @return bool + * @static + */ + public static function writeStream($path, $resource, $options = []) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->writeStream($path, $resource, $options); + } + /** + * Get the URL for the file at the given path. + * + * @param string $path + * @return string + * @throws \RuntimeException + * @static + */ + public static function url($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->url($path); + } + /** + * Determine if temporary URLs can be generated. + * + * @return bool + * @static + */ + public static function providesTemporaryUrls() + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->providesTemporaryUrls(); + } + /** + * Get a temporary URL for the file at the given path. + * + * @param string $path + * @param \DateTimeInterface $expiration + * @param array $options + * @return string + * @throws \RuntimeException + * @static + */ + public static function temporaryUrl($path, $expiration, $options = []) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->temporaryUrl($path, $expiration, $options); + } + /** + * Get a temporary upload URL for the file at the given path. + * + * @param string $path + * @param \DateTimeInterface $expiration + * @param array $options + * @return array + * @throws \RuntimeException + * @static + */ + public static function temporaryUploadUrl($path, $expiration, $options = []) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->temporaryUploadUrl($path, $expiration, $options); + } + /** + * Get an array of all files in a directory. + * + * @param string|null $directory + * @param bool $recursive + * @return array + * @static + */ + public static function files($directory = null, $recursive = false) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->files($directory, $recursive); + } + /** + * Get all of the files from the given directory (recursive). + * + * @param string|null $directory + * @return array + * @static + */ + public static function allFiles($directory = null) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->allFiles($directory); + } + /** + * Get all of the directories within a given directory. + * + * @param string|null $directory + * @param bool $recursive + * @return array + * @static + */ + public static function directories($directory = null, $recursive = false) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->directories($directory, $recursive); + } + /** + * Get all the directories within a given directory (recursive). + * + * @param string|null $directory + * @return array + * @static + */ + public static function allDirectories($directory = null) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->allDirectories($directory); + } + /** + * Create a directory. + * + * @param string $path + * @return bool + * @static + */ + public static function makeDirectory($path) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->makeDirectory($path); + } + /** + * Recursively delete a directory. + * + * @param string $directory + * @return bool + * @static + */ + public static function deleteDirectory($directory) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->deleteDirectory($directory); + } + /** + * Get the Flysystem driver. + * + * @return \League\Flysystem\FilesystemOperator + * @static + */ + public static function getDriver() + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->getDriver(); + } + /** + * Get the Flysystem adapter. + * + * @return \League\Flysystem\FilesystemAdapter + * @static + */ + public static function getAdapter() + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->getAdapter(); + } + /** + * Get the configuration values. + * + * @return array + * @static + */ + public static function getConfig() + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->getConfig(); + } + /** + * Define a custom temporary URL builder callback. + * + * @param \Closure $callback + * @return void + * @static + */ + public static function buildTemporaryUrlsUsing($callback) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + $instance->buildTemporaryUrlsUsing($callback); + } + /** + * Apply the callback if the given "value" is (or resolves to) truthy. + * + * @template TWhenParameter + * @template TWhenReturnType + * @param \Illuminate\Filesystem\(\Closure($this): TWhenParameter)|TWhenParameter|null $value + * @param \Illuminate\Filesystem\(callable($this, TWhenParameter): TWhenReturnType)|null $callback + * @param \Illuminate\Filesystem\(callable($this, TWhenParameter): TWhenReturnType)|null $default + * @return $this|\Illuminate\Filesystem\TWhenReturnType + * @static + */ + public static function when($value = null, $callback = null, $default = null) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->when($value, $callback, $default); + } + /** + * Apply the callback if the given "value" is (or resolves to) falsy. + * + * @template TUnlessParameter + * @template TUnlessReturnType + * @param \Illuminate\Filesystem\(\Closure($this): TUnlessParameter)|TUnlessParameter|null $value + * @param \Illuminate\Filesystem\(callable($this, TUnlessParameter): TUnlessReturnType)|null $callback + * @param \Illuminate\Filesystem\(callable($this, TUnlessParameter): TUnlessReturnType)|null $default + * @return $this|\Illuminate\Filesystem\TUnlessReturnType + * @static + */ + public static function unless($value = null, $callback = null, $default = null) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->unless($value, $callback, $default); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Filesystem\FilesystemAdapter::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Filesystem\FilesystemAdapter::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Filesystem\FilesystemAdapter::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Filesystem\FilesystemAdapter::flushMacros(); + } + /** + * Dynamically handle calls to the class. + * + * @param string $method + * @param array $parameters + * @return mixed + * @throws \BadMethodCallException + * @static + */ + public static function macroCall($method, $parameters) + { + /** @var \Illuminate\Filesystem\FilesystemAdapter $instance */ + return $instance->macroCall($method, $parameters); + } + + } + /** + * + * + * @see \Illuminate\Routing\UrlGenerator + */ + class URL { + /** + * Get the full URL for the current request. + * + * @return string + * @static + */ + public static function full() + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->full(); + } + /** + * Get the current URL for the request. + * + * @return string + * @static + */ + public static function current() + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->current(); + } + /** + * Get the URL for the previous request. + * + * @param mixed $fallback + * @return string + * @static + */ + public static function previous($fallback = false) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->previous($fallback); + } + /** + * Get the previous path info for the request. + * + * @param mixed $fallback + * @return string + * @static + */ + public static function previousPath($fallback = false) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->previousPath($fallback); + } + /** + * Generate an absolute URL to the given path. + * + * @param string $path + * @param mixed $extra + * @param bool|null $secure + * @return string + * @static + */ + public static function to($path, $extra = [], $secure = null) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->to($path, $extra, $secure); + } + /** + * Generate a secure, absolute URL to the given path. + * + * @param string $path + * @param array $parameters + * @return string + * @static + */ + public static function secure($path, $parameters = []) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->secure($path, $parameters); + } + /** + * Generate the URL to an application asset. + * + * @param string $path + * @param bool|null $secure + * @return string + * @static + */ + public static function asset($path, $secure = null) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->asset($path, $secure); + } + /** + * Generate the URL to a secure asset. + * + * @param string $path + * @return string + * @static + */ + public static function secureAsset($path) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->secureAsset($path); + } + /** + * Generate the URL to an asset from a custom root domain such as CDN, etc. + * + * @param string $root + * @param string $path + * @param bool|null $secure + * @return string + * @static + */ + public static function assetFrom($root, $path, $secure = null) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->assetFrom($root, $path, $secure); + } + /** + * Get the default scheme for a raw URL. + * + * @param bool|null $secure + * @return string + * @static + */ + public static function formatScheme($secure = null) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->formatScheme($secure); + } + /** + * Create a signed route URL for a named route. + * + * @param string $name + * @param mixed $parameters + * @param \DateTimeInterface|\DateInterval|int|null $expiration + * @param bool $absolute + * @return string + * @throws \InvalidArgumentException + * @static + */ + public static function signedRoute($name, $parameters = [], $expiration = null, $absolute = true) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->signedRoute($name, $parameters, $expiration, $absolute); + } + /** + * Create a temporary signed route URL for a named route. + * + * @param string $name + * @param \DateTimeInterface|\DateInterval|int $expiration + * @param array $parameters + * @param bool $absolute + * @return string + * @static + */ + public static function temporarySignedRoute($name, $expiration, $parameters = [], $absolute = true) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->temporarySignedRoute($name, $expiration, $parameters, $absolute); + } + /** + * Determine if the given request has a valid signature. + * + * @param \Illuminate\Http\Request $request + * @param bool $absolute + * @param array $ignoreQuery + * @return bool + * @static + */ + public static function hasValidSignature($request, $absolute = true, $ignoreQuery = []) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->hasValidSignature($request, $absolute, $ignoreQuery); + } + /** + * Determine if the given request has a valid signature for a relative URL. + * + * @param \Illuminate\Http\Request $request + * @param array $ignoreQuery + * @return bool + * @static + */ + public static function hasValidRelativeSignature($request, $ignoreQuery = []) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->hasValidRelativeSignature($request, $ignoreQuery); + } + /** + * Determine if the signature from the given request matches the URL. + * + * @param \Illuminate\Http\Request $request + * @param bool $absolute + * @param array $ignoreQuery + * @return bool + * @static + */ + public static function hasCorrectSignature($request, $absolute = true, $ignoreQuery = []) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->hasCorrectSignature($request, $absolute, $ignoreQuery); + } + /** + * Determine if the expires timestamp from the given request is not from the past. + * + * @param \Illuminate\Http\Request $request + * @return bool + * @static + */ + public static function signatureHasNotExpired($request) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->signatureHasNotExpired($request); + } + /** + * Get the URL to a named route. + * + * @param string $name + * @param mixed $parameters + * @param bool $absolute + * @return string + * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException + * @static + */ + public static function route($name, $parameters = [], $absolute = true) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->route($name, $parameters, $absolute); + } + /** + * Get the URL for a given route instance. + * + * @param \Illuminate\Routing\Route $route + * @param mixed $parameters + * @param bool $absolute + * @return string + * @throws \Illuminate\Routing\Exceptions\UrlGenerationException + * @static + */ + public static function toRoute($route, $parameters, $absolute) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->toRoute($route, $parameters, $absolute); + } + /** + * Get the URL to a controller action. + * + * @param string|array $action + * @param mixed $parameters + * @param bool $absolute + * @return string + * @throws \InvalidArgumentException + * @static + */ + public static function action($action, $parameters = [], $absolute = true) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->action($action, $parameters, $absolute); + } + /** + * Format the array of URL parameters. + * + * @param mixed|array $parameters + * @return array + * @static + */ + public static function formatParameters($parameters) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->formatParameters($parameters); + } + /** + * Get the base URL for the request. + * + * @param string $scheme + * @param string|null $root + * @return string + * @static + */ + public static function formatRoot($scheme, $root = null) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->formatRoot($scheme, $root); + } + /** + * Format the given URL segments into a single URL. + * + * @param string $root + * @param string $path + * @param \Illuminate\Routing\Route|null $route + * @return string + * @static + */ + public static function format($root, $path, $route = null) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->format($root, $path, $route); + } + /** + * Determine if the given path is a valid URL. + * + * @param string $path + * @return bool + * @static + */ + public static function isValidUrl($path) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->isValidUrl($path); + } + /** + * Set the default named parameters used by the URL generator. + * + * @param array $defaults + * @return void + * @static + */ + public static function defaults($defaults) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + $instance->defaults($defaults); + } + /** + * Get the default named parameters used by the URL generator. + * + * @return array + * @static + */ + public static function getDefaultParameters() + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->getDefaultParameters(); + } + /** + * Force the scheme for URLs. + * + * @param string|null $scheme + * @return void + * @static + */ + public static function forceScheme($scheme) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + $instance->forceScheme($scheme); + } + /** + * Set the forced root URL. + * + * @param string|null $root + * @return void + * @static + */ + public static function forceRootUrl($root) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + $instance->forceRootUrl($root); + } + /** + * Set a callback to be used to format the host of generated URLs. + * + * @param \Closure $callback + * @return \Illuminate\Routing\UrlGenerator + * @static + */ + public static function formatHostUsing($callback) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->formatHostUsing($callback); + } + /** + * Set a callback to be used to format the path of generated URLs. + * + * @param \Closure $callback + * @return \Illuminate\Routing\UrlGenerator + * @static + */ + public static function formatPathUsing($callback) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->formatPathUsing($callback); + } + /** + * Get the path formatter being used by the URL generator. + * + * @return \Closure + * @static + */ + public static function pathFormatter() + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->pathFormatter(); + } + /** + * Get the request instance. + * + * @return \Illuminate\Http\Request + * @static + */ + public static function getRequest() + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->getRequest(); + } + /** + * Set the current request instance. + * + * @param \Illuminate\Http\Request $request + * @return void + * @static + */ + public static function setRequest($request) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + $instance->setRequest($request); + } + /** + * Set the route collection. + * + * @param \Illuminate\Routing\RouteCollectionInterface $routes + * @return \Illuminate\Routing\UrlGenerator + * @static + */ + public static function setRoutes($routes) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->setRoutes($routes); + } + /** + * Set the session resolver for the generator. + * + * @param callable $sessionResolver + * @return \Illuminate\Routing\UrlGenerator + * @static + */ + public static function setSessionResolver($sessionResolver) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->setSessionResolver($sessionResolver); + } + /** + * Set the encryption key resolver. + * + * @param callable $keyResolver + * @return \Illuminate\Routing\UrlGenerator + * @static + */ + public static function setKeyResolver($keyResolver) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->setKeyResolver($keyResolver); + } + /** + * Clone a new instance of the URL generator with a different encryption key resolver. + * + * @param callable $keyResolver + * @return \Illuminate\Routing\UrlGenerator + * @static + */ + public static function withKeyResolver($keyResolver) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->withKeyResolver($keyResolver); + } + /** + * Get the root controller namespace. + * + * @return string + * @static + */ + public static function getRootControllerNamespace() + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->getRootControllerNamespace(); + } + /** + * Set the root controller namespace. + * + * @param string $rootNamespace + * @return \Illuminate\Routing\UrlGenerator + * @static + */ + public static function setRootControllerNamespace($rootNamespace) + { + /** @var \Illuminate\Routing\UrlGenerator $instance */ + return $instance->setRootControllerNamespace($rootNamespace); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Routing\UrlGenerator::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Routing\UrlGenerator::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Routing\UrlGenerator::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Routing\UrlGenerator::flushMacros(); + } + + } + /** + * + * + * @see \Illuminate\Validation\Factory + */ + class Validator { + /** + * Create a new Validator instance. + * + * @param array $data + * @param array $rules + * @param array $messages + * @param array $customAttributes + * @return \Illuminate\Validation\Validator + * @static + */ + public static function make($data, $rules, $messages = [], $customAttributes = []) + { + /** @var \Illuminate\Validation\Factory $instance */ + return $instance->make($data, $rules, $messages, $customAttributes); + } + /** + * Validate the given data against the provided rules. + * + * @param array $data + * @param array $rules + * @param array $messages + * @param array $customAttributes + * @return array + * @throws \Illuminate\Validation\ValidationException + * @static + */ + public static function validate($data, $rules, $messages = [], $customAttributes = []) + { + /** @var \Illuminate\Validation\Factory $instance */ + return $instance->validate($data, $rules, $messages, $customAttributes); + } + /** + * Register a custom validator extension. + * + * @param string $rule + * @param \Closure|string $extension + * @param string|null $message + * @return void + * @static + */ + public static function extend($rule, $extension, $message = null) + { + /** @var \Illuminate\Validation\Factory $instance */ + $instance->extend($rule, $extension, $message); + } + /** + * Register a custom implicit validator extension. + * + * @param string $rule + * @param \Closure|string $extension + * @param string|null $message + * @return void + * @static + */ + public static function extendImplicit($rule, $extension, $message = null) + { + /** @var \Illuminate\Validation\Factory $instance */ + $instance->extendImplicit($rule, $extension, $message); + } + /** + * Register a custom dependent validator extension. + * + * @param string $rule + * @param \Closure|string $extension + * @param string|null $message + * @return void + * @static + */ + public static function extendDependent($rule, $extension, $message = null) + { + /** @var \Illuminate\Validation\Factory $instance */ + $instance->extendDependent($rule, $extension, $message); + } + /** + * Register a custom validator message replacer. + * + * @param string $rule + * @param \Closure|string $replacer + * @return void + * @static + */ + public static function replacer($rule, $replacer) + { + /** @var \Illuminate\Validation\Factory $instance */ + $instance->replacer($rule, $replacer); + } + /** + * Indicate that unvalidated array keys should be included in validated data when the parent array is validated. + * + * @return void + * @static + */ + public static function includeUnvalidatedArrayKeys() + { + /** @var \Illuminate\Validation\Factory $instance */ + $instance->includeUnvalidatedArrayKeys(); + } + /** + * Indicate that unvalidated array keys should be excluded from the validated data, even if the parent array was validated. + * + * @return void + * @static + */ + public static function excludeUnvalidatedArrayKeys() + { + /** @var \Illuminate\Validation\Factory $instance */ + $instance->excludeUnvalidatedArrayKeys(); + } + /** + * Set the Validator instance resolver. + * + * @param \Closure $resolver + * @return void + * @static + */ + public static function resolver($resolver) + { + /** @var \Illuminate\Validation\Factory $instance */ + $instance->resolver($resolver); + } + /** + * Get the Translator implementation. + * + * @return \Illuminate\Contracts\Translation\Translator + * @static + */ + public static function getTranslator() + { + /** @var \Illuminate\Validation\Factory $instance */ + return $instance->getTranslator(); + } + /** + * Get the Presence Verifier implementation. + * + * @return \Illuminate\Validation\PresenceVerifierInterface + * @static + */ + public static function getPresenceVerifier() + { + /** @var \Illuminate\Validation\Factory $instance */ + return $instance->getPresenceVerifier(); + } + /** + * Set the Presence Verifier implementation. + * + * @param \Illuminate\Validation\PresenceVerifierInterface $presenceVerifier + * @return void + * @static + */ + public static function setPresenceVerifier($presenceVerifier) + { + /** @var \Illuminate\Validation\Factory $instance */ + $instance->setPresenceVerifier($presenceVerifier); + } + /** + * Get the container instance used by the validation factory. + * + * @return \Illuminate\Contracts\Container\Container|null + * @static + */ + public static function getContainer() + { + /** @var \Illuminate\Validation\Factory $instance */ + return $instance->getContainer(); + } + /** + * Set the container instance used by the validation factory. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return \Illuminate\Validation\Factory + * @static + */ + public static function setContainer($container) + { + /** @var \Illuminate\Validation\Factory $instance */ + return $instance->setContainer($container); + } + + } + /** + * + * + * @see \Illuminate\View\Factory + */ + class View { + /** + * Get the evaluated view contents for the given view. + * + * @param string $path + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return \Illuminate\Contracts\View\View + * @static + */ + public static function file($path, $data = [], $mergeData = []) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->file($path, $data, $mergeData); + } + /** + * Get the evaluated view contents for the given view. + * + * @param string $view + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return \Illuminate\Contracts\View\View + * @static + */ + public static function make($view, $data = [], $mergeData = []) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->make($view, $data, $mergeData); + } + /** + * Get the first view that actually exists from the given list. + * + * @param array $views + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return \Illuminate\Contracts\View\View + * @throws \InvalidArgumentException + * @static + */ + public static function first($views, $data = [], $mergeData = []) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->first($views, $data, $mergeData); + } + /** + * Get the rendered content of the view based on a given condition. + * + * @param bool $condition + * @param string $view + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return string + * @static + */ + public static function renderWhen($condition, $view, $data = [], $mergeData = []) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->renderWhen($condition, $view, $data, $mergeData); + } + /** + * Get the rendered content of the view based on the negation of a given condition. + * + * @param bool $condition + * @param string $view + * @param \Illuminate\Contracts\Support\Arrayable|array $data + * @param array $mergeData + * @return string + * @static + */ + public static function renderUnless($condition, $view, $data = [], $mergeData = []) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->renderUnless($condition, $view, $data, $mergeData); + } + /** + * Get the rendered contents of a partial from a loop. + * + * @param string $view + * @param array $data + * @param string $iterator + * @param string $empty + * @return string + * @static + */ + public static function renderEach($view, $data, $iterator, $empty = 'raw|') + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->renderEach($view, $data, $iterator, $empty); + } + /** + * Determine if a given view exists. + * + * @param string $view + * @return bool + * @static + */ + public static function exists($view) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->exists($view); + } + /** + * Get the appropriate view engine for the given path. + * + * @param string $path + * @return \Illuminate\Contracts\View\Engine + * @throws \InvalidArgumentException + * @static + */ + public static function getEngineFromPath($path) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getEngineFromPath($path); + } + /** + * Add a piece of shared data to the environment. + * + * @param array|string $key + * @param mixed|null $value + * @return mixed + * @static + */ + public static function share($key, $value = null) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->share($key, $value); + } + /** + * Increment the rendering counter. + * + * @return void + * @static + */ + public static function incrementRender() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->incrementRender(); + } + /** + * Decrement the rendering counter. + * + * @return void + * @static + */ + public static function decrementRender() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->decrementRender(); + } + /** + * Check if there are no active render operations. + * + * @return bool + * @static + */ + public static function doneRendering() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->doneRendering(); + } + /** + * Determine if the given once token has been rendered. + * + * @param string $id + * @return bool + * @static + */ + public static function hasRenderedOnce($id) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->hasRenderedOnce($id); + } + /** + * Mark the given once token as having been rendered. + * + * @param string $id + * @return void + * @static + */ + public static function markAsRenderedOnce($id) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->markAsRenderedOnce($id); + } + /** + * Add a location to the array of view locations. + * + * @param string $location + * @return void + * @static + */ + public static function addLocation($location) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->addLocation($location); + } + /** + * Add a new namespace to the loader. + * + * @param string $namespace + * @param string|array $hints + * @return \Illuminate\View\Factory + * @static + */ + public static function addNamespace($namespace, $hints) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->addNamespace($namespace, $hints); + } + /** + * Prepend a new namespace to the loader. + * + * @param string $namespace + * @param string|array $hints + * @return \Illuminate\View\Factory + * @static + */ + public static function prependNamespace($namespace, $hints) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->prependNamespace($namespace, $hints); + } + /** + * Replace the namespace hints for the given namespace. + * + * @param string $namespace + * @param string|array $hints + * @return \Illuminate\View\Factory + * @static + */ + public static function replaceNamespace($namespace, $hints) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->replaceNamespace($namespace, $hints); + } + /** + * Register a valid view extension and its engine. + * + * @param string $extension + * @param string $engine + * @param \Closure|null $resolver + * @return void + * @static + */ + public static function addExtension($extension, $engine, $resolver = null) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->addExtension($extension, $engine, $resolver); + } + /** + * Flush all of the factory state like sections and stacks. + * + * @return void + * @static + */ + public static function flushState() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->flushState(); + } + /** + * Flush all of the section contents if done rendering. + * + * @return void + * @static + */ + public static function flushStateIfDoneRendering() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->flushStateIfDoneRendering(); + } + /** + * Get the extension to engine bindings. + * + * @return array + * @static + */ + public static function getExtensions() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getExtensions(); + } + /** + * Get the engine resolver instance. + * + * @return \Illuminate\View\Engines\EngineResolver + * @static + */ + public static function getEngineResolver() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getEngineResolver(); + } + /** + * Get the view finder instance. + * + * @return \Illuminate\View\ViewFinderInterface + * @static + */ + public static function getFinder() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getFinder(); + } + /** + * Set the view finder instance. + * + * @param \Illuminate\View\ViewFinderInterface $finder + * @return void + * @static + */ + public static function setFinder($finder) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->setFinder($finder); + } + /** + * Flush the cache of views located by the finder. + * + * @return void + * @static + */ + public static function flushFinderCache() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->flushFinderCache(); + } + /** + * Get the event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher + * @static + */ + public static function getDispatcher() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getDispatcher(); + } + /** + * Set the event dispatcher instance. + * + * @param \Illuminate\Contracts\Events\Dispatcher $events + * @return void + * @static + */ + public static function setDispatcher($events) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->setDispatcher($events); + } + /** + * Get the IoC container instance. + * + * @return \Illuminate\Contracts\Container\Container + * @static + */ + public static function getContainer() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getContainer(); + } + /** + * Set the IoC container instance. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return void + * @static + */ + public static function setContainer($container) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->setContainer($container); + } + /** + * Get an item from the shared data. + * + * @param string $key + * @param mixed $default + * @return mixed + * @static + */ + public static function shared($key, $default = null) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->shared($key, $default); + } + /** + * Get all of the shared data for the environment. + * + * @return array + * @static + */ + public static function getShared() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getShared(); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\View\Factory::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\View\Factory::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\View\Factory::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\View\Factory::flushMacros(); + } + /** + * Start a component rendering process. + * + * @param \Illuminate\Contracts\View\View|\Illuminate\Contracts\Support\Htmlable|\Closure|string $view + * @param array $data + * @return void + * @static + */ + public static function startComponent($view, $data = []) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->startComponent($view, $data); + } + /** + * Get the first view that actually exists from the given list, and start a component. + * + * @param array $names + * @param array $data + * @return void + * @static + */ + public static function startComponentFirst($names, $data = []) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->startComponentFirst($names, $data); + } + /** + * Render the current component. + * + * @return string + * @static + */ + public static function renderComponent() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->renderComponent(); + } + /** + * Get an item from the component data that exists above the current component. + * + * @param string $key + * @param mixed $default + * @return mixed|null + * @static + */ + public static function getConsumableComponentData($key, $default = null) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getConsumableComponentData($key, $default); + } + /** + * Start the slot rendering process. + * + * @param string $name + * @param string|null $content + * @param array $attributes + * @return void + * @static + */ + public static function slot($name, $content = null, $attributes = []) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->slot($name, $content, $attributes); + } + /** + * Save the slot content for rendering. + * + * @return void + * @static + */ + public static function endSlot() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->endSlot(); + } + /** + * Register a view creator event. + * + * @param array|string $views + * @param \Closure|string $callback + * @return array + * @static + */ + public static function creator($views, $callback) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->creator($views, $callback); + } + /** + * Register multiple view composers via an array. + * + * @param array $composers + * @return array + * @static + */ + public static function composers($composers) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->composers($composers); + } + /** + * Register a view composer event. + * + * @param array|string $views + * @param \Closure|string $callback + * @return array + * @static + */ + public static function composer($views, $callback) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->composer($views, $callback); + } + /** + * Call the composer for a given view. + * + * @param \Illuminate\Contracts\View\View $view + * @return void + * @static + */ + public static function callComposer($view) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->callComposer($view); + } + /** + * Call the creator for a given view. + * + * @param \Illuminate\Contracts\View\View $view + * @return void + * @static + */ + public static function callCreator($view) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->callCreator($view); + } + /** + * Start injecting content into a fragment. + * + * @param string $fragment + * @return void + * @static + */ + public static function startFragment($fragment) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->startFragment($fragment); + } + /** + * Stop injecting content into a fragment. + * + * @return string + * @throws \InvalidArgumentException + * @static + */ + public static function stopFragment() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->stopFragment(); + } + /** + * Get the contents of a fragment. + * + * @param string $name + * @param string|null $default + * @return mixed + * @static + */ + public static function getFragment($name, $default = null) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getFragment($name, $default); + } + /** + * Get the entire array of rendered fragments. + * + * @return array + * @static + */ + public static function getFragments() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getFragments(); + } + /** + * Flush all of the fragments. + * + * @return void + * @static + */ + public static function flushFragments() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->flushFragments(); + } + /** + * Start injecting content into a section. + * + * @param string $section + * @param string|null $content + * @return void + * @static + */ + public static function startSection($section, $content = null) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->startSection($section, $content); + } + /** + * Inject inline content into a section. + * + * @param string $section + * @param string $content + * @return void + * @static + */ + public static function inject($section, $content) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->inject($section, $content); + } + /** + * Stop injecting content into a section and return its contents. + * + * @return string + * @static + */ + public static function yieldSection() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->yieldSection(); + } + /** + * Stop injecting content into a section. + * + * @param bool $overwrite + * @return string + * @throws \InvalidArgumentException + * @static + */ + public static function stopSection($overwrite = false) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->stopSection($overwrite); + } + /** + * Stop injecting content into a section and append it. + * + * @return string + * @throws \InvalidArgumentException + * @static + */ + public static function appendSection() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->appendSection(); + } + /** + * Get the string contents of a section. + * + * @param string $section + * @param string $default + * @return string + * @static + */ + public static function yieldContent($section, $default = '') + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->yieldContent($section, $default); + } + /** + * Get the parent placeholder for the current request. + * + * @param string $section + * @return string + * @static + */ + public static function parentPlaceholder($section = '') + { + return \Illuminate\View\Factory::parentPlaceholder($section); + } + /** + * Check if section exists. + * + * @param string $name + * @return bool + * @static + */ + public static function hasSection($name) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->hasSection($name); + } + /** + * Check if section does not exist. + * + * @param string $name + * @return bool + * @static + */ + public static function sectionMissing($name) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->sectionMissing($name); + } + /** + * Get the contents of a section. + * + * @param string $name + * @param string|null $default + * @return mixed + * @static + */ + public static function getSection($name, $default = null) + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getSection($name, $default); + } + /** + * Get the entire array of sections. + * + * @return array + * @static + */ + public static function getSections() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getSections(); + } + /** + * Flush all of the sections. + * + * @return void + * @static + */ + public static function flushSections() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->flushSections(); + } + /** + * Add new loop to the stack. + * + * @param \Countable|array $data + * @return void + * @static + */ + public static function addLoop($data) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->addLoop($data); + } + /** + * Increment the top loop's indices. + * + * @return void + * @static + */ + public static function incrementLoopIndices() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->incrementLoopIndices(); + } + /** + * Pop a loop from the top of the loop stack. + * + * @return void + * @static + */ + public static function popLoop() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->popLoop(); + } + /** + * Get an instance of the last loop in the stack. + * + * @return \stdClass|null + * @static + */ + public static function getLastLoop() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getLastLoop(); + } + /** + * Get the entire loop stack. + * + * @return array + * @static + */ + public static function getLoopStack() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->getLoopStack(); + } + /** + * Start injecting content into a push section. + * + * @param string $section + * @param string $content + * @return void + * @static + */ + public static function startPush($section, $content = '') + { + /** @var \Illuminate\View\Factory $instance */ + $instance->startPush($section, $content); + } + /** + * Stop injecting content into a push section. + * + * @return string + * @throws \InvalidArgumentException + * @static + */ + public static function stopPush() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->stopPush(); + } + /** + * Start prepending content into a push section. + * + * @param string $section + * @param string $content + * @return void + * @static + */ + public static function startPrepend($section, $content = '') + { + /** @var \Illuminate\View\Factory $instance */ + $instance->startPrepend($section, $content); + } + /** + * Stop prepending content into a push section. + * + * @return string + * @throws \InvalidArgumentException + * @static + */ + public static function stopPrepend() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->stopPrepend(); + } + /** + * Get the string contents of a push section. + * + * @param string $section + * @param string $default + * @return string + * @static + */ + public static function yieldPushContent($section, $default = '') + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->yieldPushContent($section, $default); + } + /** + * Flush all of the stacks. + * + * @return void + * @static + */ + public static function flushStacks() + { + /** @var \Illuminate\View\Factory $instance */ + $instance->flushStacks(); + } + /** + * Start a translation block. + * + * @param array $replacements + * @return void + * @static + */ + public static function startTranslation($replacements = []) + { + /** @var \Illuminate\View\Factory $instance */ + $instance->startTranslation($replacements); + } + /** + * Render the current translation. + * + * @return string + * @static + */ + public static function renderTranslation() + { + /** @var \Illuminate\View\Factory $instance */ + return $instance->renderTranslation(); + } + + } + /** + * + * + * @see \Illuminate\Foundation\Vite + */ + class Vite { + /** + * Get the preloaded assets. + * + * @return array + * @static + */ + public static function preloadedAssets() + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->preloadedAssets(); + } + /** + * Get the Content Security Policy nonce applied to all generated tags. + * + * @return string|null + * @static + */ + public static function cspNonce() + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->cspNonce(); + } + /** + * Generate or set a Content Security Policy nonce to apply to all generated tags. + * + * @param string|null $nonce + * @return string + * @static + */ + public static function useCspNonce($nonce = null) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->useCspNonce($nonce); + } + /** + * Use the given key to detect integrity hashes in the manifest. + * + * @param string|false $key + * @return \Illuminate\Foundation\Vite + * @static + */ + public static function useIntegrityKey($key) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->useIntegrityKey($key); + } + /** + * Set the Vite entry points. + * + * @param array $entryPoints + * @return \Illuminate\Foundation\Vite + * @static + */ + public static function withEntryPoints($entryPoints) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->withEntryPoints($entryPoints); + } + /** + * Set the filename for the manifest file. + * + * @param string $filename + * @return \Illuminate\Foundation\Vite + * @static + */ + public static function useManifestFilename($filename) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->useManifestFilename($filename); + } + /** + * Get the Vite "hot" file path. + * + * @return string + * @static + */ + public static function hotFile() + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->hotFile(); + } + /** + * Set the Vite "hot" file path. + * + * @param string $path + * @return \Illuminate\Foundation\Vite + * @static + */ + public static function useHotFile($path) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->useHotFile($path); + } + /** + * Set the Vite build directory. + * + * @param string $path + * @return \Illuminate\Foundation\Vite + * @static + */ + public static function useBuildDirectory($path) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->useBuildDirectory($path); + } + /** + * Use the given callback to resolve attributes for script tags. + * + * @param \Illuminate\Foundation\(callable(string, string, ?array, ?array): array)|array $attributes + * @return \Illuminate\Foundation\Vite + * @static + */ + public static function useScriptTagAttributes($attributes) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->useScriptTagAttributes($attributes); + } + /** + * Use the given callback to resolve attributes for style tags. + * + * @param \Illuminate\Foundation\(callable(string, string, ?array, ?array): array)|array $attributes + * @return \Illuminate\Foundation\Vite + * @static + */ + public static function useStyleTagAttributes($attributes) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->useStyleTagAttributes($attributes); + } + /** + * Use the given callback to resolve attributes for preload tags. + * + * @param \Illuminate\Foundation\(callable(string, string, ?array, ?array): (array|false))|array|false $attributes + * @return \Illuminate\Foundation\Vite + * @static + */ + public static function usePreloadTagAttributes($attributes) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->usePreloadTagAttributes($attributes); + } + /** + * Generate React refresh runtime script. + * + * @return \Illuminate\Support\HtmlString|void + * @static + */ + public static function reactRefresh() + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->reactRefresh(); + } + /** + * Get the URL for an asset. + * + * @param string $asset + * @param string|null $buildDirectory + * @return string + * @static + */ + public static function asset($asset, $buildDirectory = null) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->asset($asset, $buildDirectory); + } + /** + * Get a unique hash representing the current manifest, or null if there is no manifest. + * + * @param string|null $buildDirectory + * @return string|null + * @static + */ + public static function manifestHash($buildDirectory = null) + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->manifestHash($buildDirectory); + } + /** + * Determine if the HMR server is running. + * + * @return bool + * @static + */ + public static function isRunningHot() + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->isRunningHot(); + } + /** + * Get the Vite tag content as a string of HTML. + * + * @return string + * @static + */ + public static function toHtml() + { + /** @var \Illuminate\Foundation\Vite $instance */ + return $instance->toHtml(); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Foundation\Vite::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Foundation\Vite::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + return \Illuminate\Foundation\Vite::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Foundation\Vite::flushMacros(); + } + + } + /** + * + * + */ + class Redis { + /** + * Get a Redis connection by name. + * + * @param string|null $name + * @return \Illuminate\Redis\Connections\Connection + * @static + */ + public static function connection($name = null) + { + /** @var \Illuminate\Redis\RedisManager $instance */ + return $instance->connection($name); + } + /** + * Resolve the given connection by name. + * + * @param string|null $name + * @return \Illuminate\Redis\Connections\Connection + * @throws \InvalidArgumentException + * @static + */ + public static function resolve($name = null) + { + /** @var \Illuminate\Redis\RedisManager $instance */ + return $instance->resolve($name); + } + /** + * Return all of the created connections. + * + * @return array + * @static + */ + public static function connections() + { + /** @var \Illuminate\Redis\RedisManager $instance */ + return $instance->connections(); + } + /** + * Enable the firing of Redis command events. + * + * @return void + * @static + */ + public static function enableEvents() + { + /** @var \Illuminate\Redis\RedisManager $instance */ + $instance->enableEvents(); + } + /** + * Disable the firing of Redis command events. + * + * @return void + * @static + */ + public static function disableEvents() + { + /** @var \Illuminate\Redis\RedisManager $instance */ + $instance->disableEvents(); + } + /** + * Set the default driver. + * + * @param string $driver + * @return void + * @static + */ + public static function setDriver($driver) + { + /** @var \Illuminate\Redis\RedisManager $instance */ + $instance->setDriver($driver); + } + /** + * Disconnect the given connection and remove from local cache. + * + * @param string|null $name + * @return void + * @static + */ + public static function purge($name = null) + { + /** @var \Illuminate\Redis\RedisManager $instance */ + $instance->purge($name); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Illuminate\Redis\RedisManager + * @static + */ + public static function extend($driver, $callback) + { + /** @var \Illuminate\Redis\RedisManager $instance */ + return $instance->extend($driver, $callback); + } + + } + +} + + namespace Illuminate\Support { + /** + * + * + */ + class Arr { + + } + /** + * + * + */ + class Js { + + } + /** + * + * + */ + class Str { + + } + /** + * + * + * @template TKey of array-key + * @template TValue + * @implements \ArrayAccess + * @implements \Illuminate\Support\Enumerable + */ + class Collection { + /** + * + * + * @see \Barryvdh\Debugbar\ServiceProvider::register() + * @static + */ + public static function debug() + { + return \Illuminate\Support\Collection::debug(); + } + + } + +} + + namespace Webpatser\Countries { + /** + * CountriesFacade + * + */ + class CountriesFacade { + /** + * Returns one country + * + * @param string $id The country id + * @return array + * @static + */ + public static function getOne($id) + { + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getOne($id); + } + /** + * Returns a list of countries + * + * @param string sort + * @return array + * @static + */ + public static function getList($sort = null) + { + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getList($sort); + } + /** + * Returns a list of countries suitable to use with a select element in Laravelcollective\html + * Will show the value and sort by the column specified in the display attribute + * + * @param string display + * @return array + * @static + */ + public static function getListForSelect($display = 'name') + { + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getListForSelect($display); + } + /** + * Clear the list of booted models so they will be re-booted. + * + * @return void + * @static + */ + public static function clearBootedModels() + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::clearBootedModels(); + } + /** + * Disables relationship model touching for the current class during given callback scope. + * + * @param callable $callback + * @return void + * @static + */ + public static function withoutTouching($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::withoutTouching($callback); + } + /** + * Disables relationship model touching for the given model classes during given callback scope. + * + * @param array $models + * @param callable $callback + * @return void + * @static + */ + public static function withoutTouchingOn($models, $callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::withoutTouchingOn($models, $callback); + } + /** + * Determine if the given model is ignoring touches. + * + * @param string|null $class + * @return bool + * @static + */ + public static function isIgnoringTouch($class = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::isIgnoringTouch($class); + } + /** + * Indicate that models should prevent lazy loading, silently discarding attributes, and accessing missing attributes. + * + * @param bool $shouldBeStrict + * @return void + * @static + */ + public static function shouldBeStrict($shouldBeStrict = true) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::shouldBeStrict($shouldBeStrict); + } + /** + * Prevent model relationships from being lazy loaded. + * + * @param bool $value + * @return void + * @static + */ + public static function preventLazyLoading($value = true) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::preventLazyLoading($value); + } + /** + * Register a callback that is responsible for handling lazy loading violations. + * + * @param callable|null $callback + * @return void + * @static + */ + public static function handleLazyLoadingViolationUsing($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::handleLazyLoadingViolationUsing($callback); + } + /** + * Prevent non-fillable attributes from being silently discarded. + * + * @param bool $value + * @return void + * @static + */ + public static function preventSilentlyDiscardingAttributes($value = true) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::preventSilentlyDiscardingAttributes($value); + } + /** + * Register a callback that is responsible for handling discarded attribute violations. + * + * @param callable|null $callback + * @return void + * @static + */ + public static function handleDiscardedAttributeViolationUsing($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::handleDiscardedAttributeViolationUsing($callback); + } + /** + * Prevent accessing missing attributes on retrieved models. + * + * @param bool $value + * @return void + * @static + */ + public static function preventAccessingMissingAttributes($value = true) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::preventAccessingMissingAttributes($value); + } + /** + * Register a callback that is responsible for handling lazy loading violations. + * + * @param callable|null $callback + * @return void + * @static + */ + public static function handleMissingAttributeViolationUsing($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::handleMissingAttributeViolationUsing($callback); + } + /** + * Execute a callback without broadcasting any model events for all model types. + * + * @param callable $callback + * @return mixed + * @static + */ + public static function withoutBroadcasting($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::withoutBroadcasting($callback); + } + /** + * Fill the model with an array of attributes. + * + * @param array $attributes + * @return \Webpatser\Countries\Countries + * @throws \Illuminate\Database\Eloquent\MassAssignmentException + * @static + */ + public static function fill($attributes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->fill($attributes); + } + /** + * Fill the model with an array of attributes. Force mass assignment. + * + * @param array $attributes + * @return \Webpatser\Countries\Countries + * @static + */ + public static function forceFill($attributes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->forceFill($attributes); + } + /** + * Qualify the given column name by the model's table. + * + * @param string $column + * @return string + * @static + */ + public static function qualifyColumn($column) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->qualifyColumn($column); + } + /** + * Qualify the given columns with the model's table. + * + * @param array $columns + * @return array + * @static + */ + public static function qualifyColumns($columns) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->qualifyColumns($columns); + } + /** + * Create a new instance of the given model. + * + * @param array $attributes + * @param bool $exists + * @return static + * @static + */ + public static function newInstance($attributes = [], $exists = false) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newInstance($attributes, $exists); + } + /** + * Create a new model instance that is existing. + * + * @param array $attributes + * @param string|null $connection + * @return static + * @static + */ + public static function newFromBuilder($attributes = [], $connection = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newFromBuilder($attributes, $connection); + } + /** + * Begin querying the model on a given connection. + * + * @param string|null $connection + * @return \Illuminate\Database\Eloquent\Builder + * @static + */ + public static function on($connection = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::on($connection); + } + /** + * Begin querying the model on the write connection. + * + * @return \Illuminate\Database\Eloquent\Builder + * @static + */ + public static function onWriteConnection() + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::onWriteConnection(); + } + /** + * Get all of the models from the database. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Collection + * @static + */ + public static function all($columns = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::all($columns); + } + /** + * Begin querying a model with eager loading. + * + * @param array|string $relations + * @return \Illuminate\Database\Eloquent\Builder + * @static + */ + public static function with($relations) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::with($relations); + } + /** + * Eager load relations on the model. + * + * @param array|string $relations + * @return \Webpatser\Countries\Countries + * @static + */ + public static function load($relations) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->load($relations); + } + /** + * Eager load relationships on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMorph($relation, $relations) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMorph($relation, $relations); + } + /** + * Eager load relations on the model if they are not already eager loaded. + * + * @param array|string $relations + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMissing($relations) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMissing($relations); + } + /** + * Eager load relation's column aggregations on the model. + * + * @param array|string $relations + * @param string $column + * @param string $function + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadAggregate($relations, $column, $function = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadAggregate($relations, $column, $function); + } + /** + * Eager load relation counts on the model. + * + * @param array|string $relations + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadCount($relations) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadCount($relations); + } + /** + * Eager load relation max column values on the model. + * + * @param array|string $relations + * @param string $column + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMax($relations, $column) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMax($relations, $column); + } + /** + * Eager load relation min column values on the model. + * + * @param array|string $relations + * @param string $column + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMin($relations, $column) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMin($relations, $column); + } + /** + * Eager load relation's column summations on the model. + * + * @param array|string $relations + * @param string $column + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadSum($relations, $column) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadSum($relations, $column); + } + /** + * Eager load relation average column values on the model. + * + * @param array|string $relations + * @param string $column + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadAvg($relations, $column) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadAvg($relations, $column); + } + /** + * Eager load related model existence values on the model. + * + * @param array|string $relations + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadExists($relations) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadExists($relations); + } + /** + * Eager load relationship column aggregation on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @param string $function + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMorphAggregate($relation, $relations, $column, $function = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMorphAggregate($relation, $relations, $column, $function); + } + /** + * Eager load relationship counts on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMorphCount($relation, $relations) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMorphCount($relation, $relations); + } + /** + * Eager load relationship max column values on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMorphMax($relation, $relations, $column) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMorphMax($relation, $relations, $column); + } + /** + * Eager load relationship min column values on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMorphMin($relation, $relations, $column) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMorphMin($relation, $relations, $column); + } + /** + * Eager load relationship column summations on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMorphSum($relation, $relations, $column) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMorphSum($relation, $relations, $column); + } + /** + * Eager load relationship average column values on the polymorphic relation of a model. + * + * @param string $relation + * @param array $relations + * @param string $column + * @return \Webpatser\Countries\Countries + * @static + */ + public static function loadMorphAvg($relation, $relations, $column) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->loadMorphAvg($relation, $relations, $column); + } + /** + * Update the model in the database. + * + * @param array $attributes + * @param array $options + * @return bool + * @static + */ + public static function update($attributes = [], $options = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->update($attributes, $options); + } + /** + * Update the model in the database within a transaction. + * + * @param array $attributes + * @param array $options + * @return bool + * @throws \Throwable + * @static + */ + public static function updateOrFail($attributes = [], $options = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->updateOrFail($attributes, $options); + } + /** + * Update the model in the database without raising any events. + * + * @param array $attributes + * @param array $options + * @return bool + * @static + */ + public static function updateQuietly($attributes = [], $options = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->updateQuietly($attributes, $options); + } + /** + * Save the model and all of its relationships. + * + * @return bool + * @static + */ + public static function push() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->push(); + } + /** + * Save the model and all of its relationships without raising any events to the parent model. + * + * @return bool + * @static + */ + public static function pushQuietly() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->pushQuietly(); + } + /** + * Save the model to the database without raising any events. + * + * @param array $options + * @return bool + * @static + */ + public static function saveQuietly($options = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->saveQuietly($options); + } + /** + * Save the model to the database. + * + * @param array $options + * @return bool + * @static + */ + public static function save($options = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->save($options); + } + /** + * Save the model to the database within a transaction. + * + * @param array $options + * @return bool + * @throws \Throwable + * @static + */ + public static function saveOrFail($options = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->saveOrFail($options); + } + /** + * Destroy the models for the given IDs. + * + * @param \Illuminate\Support\Collection|array|int|string $ids + * @return int + * @static + */ + public static function destroy($ids) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::destroy($ids); + } + /** + * Delete the model from the database. + * + * @return bool|null + * @throws \LogicException + * @static + */ + public static function delete() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->delete(); + } + /** + * Delete the model from the database without raising any events. + * + * @return bool + * @static + */ + public static function deleteQuietly() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->deleteQuietly(); + } + /** + * Delete the model from the database within a transaction. + * + * @return bool|null + * @throws \Throwable + * @static + */ + public static function deleteOrFail() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->deleteOrFail(); + } + /** + * Force a hard delete on a soft deleted model. + * + * This method protects developers from running forceDelete when the trait is missing. + * + * @return bool|null + * @static + */ + public static function forceDelete() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->forceDelete(); + } + /** + * Begin querying the model. + * + * @return \Illuminate\Database\Eloquent\Builder + * @static + */ + public static function query() + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::query(); + } + /** + * Get a new query builder for the model's table. + * + * @return \Illuminate\Database\Eloquent\Builder + * @static + */ + public static function newQuery() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newQuery(); + } + /** + * Get a new query builder that doesn't have any global scopes or eager loading. + * + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function newModelQuery() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newModelQuery(); + } + /** + * Get a new query builder with no relationships loaded. + * + * @return \Illuminate\Database\Eloquent\Builder + * @static + */ + public static function newQueryWithoutRelationships() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newQueryWithoutRelationships(); + } + /** + * Register the global scopes for this builder instance. + * + * @param \Illuminate\Database\Eloquent\Builder $builder + * @return \Illuminate\Database\Eloquent\Builder + * @static + */ + public static function registerGlobalScopes($builder) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->registerGlobalScopes($builder); + } + /** + * Get a new query builder that doesn't have any global scopes. + * + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function newQueryWithoutScopes() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newQueryWithoutScopes(); + } + /** + * Get a new query instance without a given scope. + * + * @param \Illuminate\Database\Eloquent\Scope|string $scope + * @return \Illuminate\Database\Eloquent\Builder + * @static + */ + public static function newQueryWithoutScope($scope) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newQueryWithoutScope($scope); + } + /** + * Get a new query to restore one or more models by their queueable IDs. + * + * @param array|int $ids + * @return \Illuminate\Database\Eloquent\Builder + * @static + */ + public static function newQueryForRestoration($ids) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newQueryForRestoration($ids); + } + /** + * Create a new Eloquent query builder for the model. + * + * @param \Illuminate\Database\Query\Builder $query + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function newEloquentBuilder($query) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newEloquentBuilder($query); + } + /** + * Create a new Eloquent Collection instance. + * + * @param array $models + * @return \Illuminate\Database\Eloquent\Collection + * @static + */ + public static function newCollection($models = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newCollection($models); + } + /** + * Create a new pivot model instance. + * + * @param \Illuminate\Database\Eloquent\Model $parent + * @param array $attributes + * @param string $table + * @param bool $exists + * @param string|null $using + * @return \Illuminate\Database\Eloquent\Relations\Pivot + * @static + */ + public static function newPivot($parent, $attributes, $table, $exists, $using = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->newPivot($parent, $attributes, $table, $exists, $using); + } + /** + * Determine if the model has a given scope. + * + * @param string $scope + * @return bool + * @static + */ + public static function hasNamedScope($scope) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasNamedScope($scope); + } + /** + * Apply the given named scope if possible. + * + * @param string $scope + * @param array $parameters + * @return mixed + * @static + */ + public static function callNamedScope($scope, $parameters = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->callNamedScope($scope, $parameters); + } + /** + * Convert the model instance to an array. + * + * @return array + * @static + */ + public static function toArray() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->toArray(); + } + /** + * Convert the model instance to JSON. + * + * @param int $options + * @return string + * @throws \Illuminate\Database\Eloquent\JsonEncodingException + * @static + */ + public static function toJson($options = 0) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->toJson($options); + } + /** + * Convert the object into something JSON serializable. + * + * @return mixed + * @static + */ + public static function jsonSerialize() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->jsonSerialize(); + } + /** + * Reload a fresh model instance from the database. + * + * @param array|string $with + * @return static|null + * @static + */ + public static function fresh($with = []) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->fresh($with); + } + /** + * Reload the current model instance with fresh attributes from the database. + * + * @return \Webpatser\Countries\Countries + * @static + */ + public static function refresh() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->refresh(); + } + /** + * Clone the model into a new, non-existing instance. + * + * @param array|null $except + * @return static + * @static + */ + public static function replicate($except = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->replicate($except); + } + /** + * Clone the model into a new, non-existing instance without raising any events. + * + * @param array|null $except + * @return static + * @static + */ + public static function replicateQuietly($except = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->replicateQuietly($except); + } + /** + * Determine if two models have the same ID and belong to the same table. + * + * @param \Illuminate\Database\Eloquent\Model|null $model + * @return bool + * @static + */ + public static function is($model) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->is($model); + } + /** + * Determine if two models are not the same. + * + * @param \Illuminate\Database\Eloquent\Model|null $model + * @return bool + * @static + */ + public static function isNot($model) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->isNot($model); + } + /** + * Get the database connection for the model. + * + * @return \Illuminate\Database\Connection + * @static + */ + public static function getConnection() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getConnection(); + } + /** + * Get the current connection name for the model. + * + * @return string|null + * @static + */ + public static function getConnectionName() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getConnectionName(); + } + /** + * Set the connection associated with the model. + * + * @param string|null $name + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setConnection($name) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setConnection($name); + } + /** + * Resolve a connection instance. + * + * @param string|null $connection + * @return \Illuminate\Database\Connection + * @static + */ + public static function resolveConnection($connection = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::resolveConnection($connection); + } + /** + * Get the connection resolver instance. + * + * @return \Illuminate\Database\ConnectionResolverInterface + * @static + */ + public static function getConnectionResolver() + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::getConnectionResolver(); + } + /** + * Set the connection resolver instance. + * + * @param \Illuminate\Database\ConnectionResolverInterface $resolver + * @return void + * @static + */ + public static function setConnectionResolver($resolver) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::setConnectionResolver($resolver); + } + /** + * Unset the connection resolver for models. + * + * @return void + * @static + */ + public static function unsetConnectionResolver() + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::unsetConnectionResolver(); + } + /** + * Get the table associated with the model. + * + * @return string + * @static + */ + public static function getTable() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getTable(); + } + /** + * Set the table associated with the model. + * + * @param string $table + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setTable($table) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setTable($table); + } + /** + * Get the primary key for the model. + * + * @return string + * @static + */ + public static function getKeyName() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getKeyName(); + } + /** + * Set the primary key for the model. + * + * @param string $key + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setKeyName($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setKeyName($key); + } + /** + * Get the table qualified key name. + * + * @return string + * @static + */ + public static function getQualifiedKeyName() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getQualifiedKeyName(); + } + /** + * Get the auto-incrementing key type. + * + * @return string + * @static + */ + public static function getKeyType() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getKeyType(); + } + /** + * Set the data type for the primary key. + * + * @param string $type + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setKeyType($type) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setKeyType($type); + } + /** + * Get the value indicating whether the IDs are incrementing. + * + * @return bool + * @static + */ + public static function getIncrementing() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getIncrementing(); + } + /** + * Set whether IDs are incrementing. + * + * @param bool $value + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setIncrementing($value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setIncrementing($value); + } + /** + * Get the value of the model's primary key. + * + * @return mixed + * @static + */ + public static function getKey() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getKey(); + } + /** + * Get the queueable identity for the entity. + * + * @return mixed + * @static + */ + public static function getQueueableId() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getQueueableId(); + } + /** + * Get the queueable relationships for the entity. + * + * @return array + * @static + */ + public static function getQueueableRelations() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getQueueableRelations(); + } + /** + * Get the queueable connection for the entity. + * + * @return string|null + * @static + */ + public static function getQueueableConnection() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getQueueableConnection(); + } + /** + * Get the value of the model's route key. + * + * @return mixed + * @static + */ + public static function getRouteKey() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getRouteKey(); + } + /** + * Get the route key for the model. + * + * @return string + * @static + */ + public static function getRouteKeyName() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getRouteKeyName(); + } + /** + * Retrieve the model for a bound value. + * + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Model|null + * @static + */ + public static function resolveRouteBinding($value, $field = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->resolveRouteBinding($value, $field); + } + /** + * Retrieve the model for a bound value. + * + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Model|null + * @static + */ + public static function resolveSoftDeletableRouteBinding($value, $field = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->resolveSoftDeletableRouteBinding($value, $field); + } + /** + * Retrieve the child model for a bound value. + * + * @param string $childType + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Model|null + * @static + */ + public static function resolveChildRouteBinding($childType, $value, $field) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->resolveChildRouteBinding($childType, $value, $field); + } + /** + * Retrieve the child model for a bound value. + * + * @param string $childType + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Model|null + * @static + */ + public static function resolveSoftDeletableChildRouteBinding($childType, $value, $field) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->resolveSoftDeletableChildRouteBinding($childType, $value, $field); + } + /** + * Retrieve the model for a bound value. + * + * @param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation $query + * @param mixed $value + * @param string|null $field + * @return \Illuminate\Database\Eloquent\Relations\Relation + * @static + */ + public static function resolveRouteBindingQuery($query, $value, $field = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->resolveRouteBindingQuery($query, $value, $field); + } + /** + * Get the default foreign key name for the model. + * + * @return string + * @static + */ + public static function getForeignKey() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getForeignKey(); + } + /** + * Get the number of models to return per page. + * + * @return int + * @static + */ + public static function getPerPage() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getPerPage(); + } + /** + * Set the number of models to return per page. + * + * @param int $perPage + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setPerPage($perPage) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setPerPage($perPage); + } + /** + * Determine if lazy loading is disabled. + * + * @return bool + * @static + */ + public static function preventsLazyLoading() + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::preventsLazyLoading(); + } + /** + * Determine if discarding guarded attribute fills is disabled. + * + * @return bool + * @static + */ + public static function preventsSilentlyDiscardingAttributes() + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::preventsSilentlyDiscardingAttributes(); + } + /** + * Determine if accessing missing attributes is disabled. + * + * @return bool + * @static + */ + public static function preventsAccessingMissingAttributes() + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::preventsAccessingMissingAttributes(); + } + /** + * Get the broadcast channel route definition that is associated with the given entity. + * + * @return string + * @static + */ + public static function broadcastChannelRoute() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->broadcastChannelRoute(); + } + /** + * Get the broadcast channel name that is associated with the given entity. + * + * @return string + * @static + */ + public static function broadcastChannel() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->broadcastChannel(); + } + /** + * Determine if the given attribute exists. + * + * @param mixed $offset + * @return bool + * @static + */ + public static function offsetExists($offset) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->offsetExists($offset); + } + /** + * Get the value for a given offset. + * + * @param mixed $offset + * @return mixed + * @static + */ + public static function offsetGet($offset) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->offsetGet($offset); + } + /** + * Set the value for a given offset. + * + * @param mixed $offset + * @param mixed $value + * @return void + * @static + */ + public static function offsetSet($offset, $value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + $instance->offsetSet($offset, $value); + } + /** + * Unset the value for a given offset. + * + * @param mixed $offset + * @return void + * @static + */ + public static function offsetUnset($offset) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + $instance->offsetUnset($offset); + } + /** + * Indicate that the object's string representation should be escaped when __toString is invoked. + * + * @param bool $escape + * @return \Webpatser\Countries\Countries + * @static + */ + public static function escapeWhenCastingToString($escape = true) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->escapeWhenCastingToString($escape); + } + /** + * Convert the model's attributes to an array. + * + * @return array + * @static + */ + public static function attributesToArray() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->attributesToArray(); + } + /** + * Get the model's relationships in array form. + * + * @return array + * @static + */ + public static function relationsToArray() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->relationsToArray(); + } + /** + * Get an attribute from the model. + * + * @param string $key + * @return mixed + * @static + */ + public static function getAttribute($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getAttribute($key); + } + /** + * Get a plain attribute (not a relationship). + * + * @param string $key + * @return mixed + * @static + */ + public static function getAttributeValue($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getAttributeValue($key); + } + /** + * Get a relationship. + * + * @param string $key + * @return mixed + * @static + */ + public static function getRelationValue($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getRelationValue($key); + } + /** + * Determine if the given key is a relationship method on the model. + * + * @param string $key + * @return bool + * @static + */ + public static function isRelation($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->isRelation($key); + } + /** + * Determine if a get mutator exists for an attribute. + * + * @param string $key + * @return bool + * @static + */ + public static function hasGetMutator($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasGetMutator($key); + } + /** + * Determine if a "Attribute" return type marked mutator exists for an attribute. + * + * @param string $key + * @return bool + * @static + */ + public static function hasAttributeMutator($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasAttributeMutator($key); + } + /** + * Determine if a "Attribute" return type marked get mutator exists for an attribute. + * + * @param string $key + * @return bool + * @static + */ + public static function hasAttributeGetMutator($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasAttributeGetMutator($key); + } + /** + * Merge new casts with existing casts on the model. + * + * @param array $casts + * @return \Webpatser\Countries\Countries + * @static + */ + public static function mergeCasts($casts) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->mergeCasts($casts); + } + /** + * Set a given attribute on the model. + * + * @param string $key + * @param mixed $value + * @return mixed + * @static + */ + public static function setAttribute($key, $value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setAttribute($key, $value); + } + /** + * Determine if a set mutator exists for an attribute. + * + * @param string $key + * @return bool + * @static + */ + public static function hasSetMutator($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasSetMutator($key); + } + /** + * Determine if an "Attribute" return type marked set mutator exists for an attribute. + * + * @param string $key + * @return bool + * @static + */ + public static function hasAttributeSetMutator($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasAttributeSetMutator($key); + } + /** + * Set a given JSON attribute on the model. + * + * @param string $key + * @param mixed $value + * @return \Webpatser\Countries\Countries + * @static + */ + public static function fillJsonAttribute($key, $value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->fillJsonAttribute($key, $value); + } + /** + * Decode the given JSON back into an array or object. + * + * @param string $value + * @param bool $asObject + * @return mixed + * @static + */ + public static function fromJson($value, $asObject = false) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->fromJson($value, $asObject); + } + /** + * Decrypt the given encrypted string. + * + * @param string $value + * @return mixed + * @static + */ + public static function fromEncryptedString($value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->fromEncryptedString($value); + } + /** + * Set the encrypter instance that will be used to encrypt attributes. + * + * @param \Illuminate\Contracts\Encryption\Encrypter|null $encrypter + * @return void + * @static + */ + public static function encryptUsing($encrypter) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::encryptUsing($encrypter); + } + /** + * Decode the given float. + * + * @param mixed $value + * @return mixed + * @static + */ + public static function fromFloat($value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->fromFloat($value); + } + /** + * Convert a DateTime to a storable string. + * + * @param mixed $value + * @return string|null + * @static + */ + public static function fromDateTime($value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->fromDateTime($value); + } + /** + * Get the attributes that should be converted to dates. + * + * @return array + * @static + */ + public static function getDates() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getDates(); + } + /** + * Get the format for database stored dates. + * + * @return string + * @static + */ + public static function getDateFormat() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getDateFormat(); + } + /** + * Set the date format used by the model. + * + * @param string $format + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setDateFormat($format) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setDateFormat($format); + } + /** + * Determine whether an attribute should be cast to a native type. + * + * @param string $key + * @param array|string|null $types + * @return bool + * @static + */ + public static function hasCast($key, $types = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasCast($key, $types); + } + /** + * Get the casts array. + * + * @return array + * @static + */ + public static function getCasts() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getCasts(); + } + /** + * Get all of the current attributes on the model. + * + * @return array + * @static + */ + public static function getAttributes() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getAttributes(); + } + /** + * Set the array of model attributes. No checking is done. + * + * @param array $attributes + * @param bool $sync + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setRawAttributes($attributes, $sync = false) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setRawAttributes($attributes, $sync); + } + /** + * Get the model's original attribute values. + * + * @param string|null $key + * @param mixed $default + * @return mixed|array + * @static + */ + public static function getOriginal($key = null, $default = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getOriginal($key, $default); + } + /** + * Get the model's raw original attribute values. + * + * @param string|null $key + * @param mixed $default + * @return mixed|array + * @static + */ + public static function getRawOriginal($key = null, $default = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getRawOriginal($key, $default); + } + /** + * Get a subset of the model's attributes. + * + * @param array|mixed $attributes + * @return array + * @static + */ + public static function only($attributes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->only($attributes); + } + /** + * Sync the original attributes with the current. + * + * @return \Webpatser\Countries\Countries + * @static + */ + public static function syncOriginal() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->syncOriginal(); + } + /** + * Sync a single original attribute with its current value. + * + * @param string $attribute + * @return \Webpatser\Countries\Countries + * @static + */ + public static function syncOriginalAttribute($attribute) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->syncOriginalAttribute($attribute); + } + /** + * Sync multiple original attribute with their current values. + * + * @param array|string $attributes + * @return \Webpatser\Countries\Countries + * @static + */ + public static function syncOriginalAttributes($attributes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->syncOriginalAttributes($attributes); + } + /** + * Sync the changed attributes. + * + * @return \Webpatser\Countries\Countries + * @static + */ + public static function syncChanges() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->syncChanges(); + } + /** + * Determine if the model or any of the given attribute(s) have been modified. + * + * @param array|string|null $attributes + * @return bool + * @static + */ + public static function isDirty($attributes = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->isDirty($attributes); + } + /** + * Determine if the model or all the given attribute(s) have remained the same. + * + * @param array|string|null $attributes + * @return bool + * @static + */ + public static function isClean($attributes = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->isClean($attributes); + } + /** + * Discard attribute changes and reset the attributes to their original state. + * + * @return \Webpatser\Countries\Countries + * @static + */ + public static function discardChanges() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->discardChanges(); + } + /** + * Determine if the model or any of the given attribute(s) were changed when the model was last saved. + * + * @param array|string|null $attributes + * @return bool + * @static + */ + public static function wasChanged($attributes = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->wasChanged($attributes); + } + /** + * Get the attributes that have been changed since the last sync. + * + * @return array + * @static + */ + public static function getDirty() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getDirty(); + } + /** + * Get the attributes that were changed when the model was last saved. + * + * @return array + * @static + */ + public static function getChanges() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getChanges(); + } + /** + * Determine if the new and old values for a given key are equivalent. + * + * @param string $key + * @return bool + * @static + */ + public static function originalIsEquivalent($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->originalIsEquivalent($key); + } + /** + * Append attributes to query when building a query. + * + * @param array|string $attributes + * @return \Webpatser\Countries\Countries + * @static + */ + public static function append($attributes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->append($attributes); + } + /** + * Get the accessors that are being appended to model arrays. + * + * @return array + * @static + */ + public static function getAppends() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getAppends(); + } + /** + * Set the accessors to append to model arrays. + * + * @param array $appends + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setAppends($appends) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setAppends($appends); + } + /** + * Return whether the accessor attribute has been appended. + * + * @param string $attribute + * @return bool + * @static + */ + public static function hasAppended($attribute) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasAppended($attribute); + } + /** + * Get the mutated attributes for a given instance. + * + * @return array + * @static + */ + public static function getMutatedAttributes() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getMutatedAttributes(); + } + /** + * Extract and cache all the mutated attributes of a class. + * + * @param object|string $classOrInstance + * @return void + * @static + */ + public static function cacheMutatedAttributes($classOrInstance) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::cacheMutatedAttributes($classOrInstance); + } + /** + * Register observers with the model. + * + * @param object|array|string $classes + * @return void + * @throws \RuntimeException + * @static + */ + public static function observe($classes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::observe($classes); + } + /** + * Get the observable event names. + * + * @return array + * @static + */ + public static function getObservableEvents() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getObservableEvents(); + } + /** + * Set the observable event names. + * + * @param array $observables + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setObservableEvents($observables) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setObservableEvents($observables); + } + /** + * Add an observable event name. + * + * @param array|mixed $observables + * @return void + * @static + */ + public static function addObservableEvents($observables) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + $instance->addObservableEvents($observables); + } + /** + * Remove an observable event name. + * + * @param array|mixed $observables + * @return void + * @static + */ + public static function removeObservableEvents($observables) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + $instance->removeObservableEvents($observables); + } + /** + * Register a retrieved model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function retrieved($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::retrieved($callback); + } + /** + * Register a saving model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function saving($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::saving($callback); + } + /** + * Register a saved model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function saved($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::saved($callback); + } + /** + * Register an updating model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function updating($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::updating($callback); + } + /** + * Register an updated model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function updated($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::updated($callback); + } + /** + * Register a creating model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function creating($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::creating($callback); + } + /** + * Register a created model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function created($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::created($callback); + } + /** + * Register a replicating model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function replicating($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::replicating($callback); + } + /** + * Register a deleting model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function deleting($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::deleting($callback); + } + /** + * Register a deleted model event with the dispatcher. + * + * @param \Illuminate\Events\Queued\Closure|\Closure|string|array $callback + * @return void + * @static + */ + public static function deleted($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::deleted($callback); + } + /** + * Remove all the event listeners for the model. + * + * @return void + * @static + */ + public static function flushEventListeners() + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::flushEventListeners(); + } + /** + * Get the event dispatcher instance. + * + * @return \Illuminate\Contracts\Events\Dispatcher + * @static + */ + public static function getEventDispatcher() + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::getEventDispatcher(); + } + /** + * Set the event dispatcher instance. + * + * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher + * @return void + * @static + */ + public static function setEventDispatcher($dispatcher) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::setEventDispatcher($dispatcher); + } + /** + * Unset the event dispatcher for models. + * + * @return void + * @static + */ + public static function unsetEventDispatcher() + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::unsetEventDispatcher(); + } + /** + * Execute a callback without firing any model events for any model type. + * + * @param callable $callback + * @return mixed + * @static + */ + public static function withoutEvents($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::withoutEvents($callback); + } + /** + * Register a new global scope on the model. + * + * @param \Illuminate\Database\Eloquent\Scope|\Closure|string $scope + * @param \Illuminate\Database\Eloquent\Scope|\Closure|null $implementation + * @return mixed + * @throws \InvalidArgumentException + * @static + */ + public static function addGlobalScope($scope, $implementation = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::addGlobalScope($scope, $implementation); + } + /** + * Determine if a model has a global scope. + * + * @param \Illuminate\Database\Eloquent\Scope|string $scope + * @return bool + * @static + */ + public static function hasGlobalScope($scope) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::hasGlobalScope($scope); + } + /** + * Get a global scope registered with the model. + * + * @param \Illuminate\Database\Eloquent\Scope|string $scope + * @return \Illuminate\Database\Eloquent\Scope|\Closure|null + * @static + */ + public static function getGlobalScope($scope) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::getGlobalScope($scope); + } + /** + * Get the global scopes for this class instance. + * + * @return array + * @static + */ + public static function getGlobalScopes() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getGlobalScopes(); + } + /** + * Get the dynamic relation resolver if defined or inherited, or return null. + * + * @param string $class + * @param string $key + * @return mixed + * @static + */ + public static function relationResolver($class, $key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->relationResolver($class, $key); + } + /** + * Define a dynamic relation resolver. + * + * @param string $name + * @param \Closure $callback + * @return void + * @static + */ + public static function resolveRelationUsing($name, $callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::resolveRelationUsing($name, $callback); + } + /** + * Define a one-to-one relationship. + * + * @param string $related + * @param string|null $foreignKey + * @param string|null $localKey + * @return \Illuminate\Database\Eloquent\Relations\HasOne + * @static + */ + public static function hasOne($related, $foreignKey = null, $localKey = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasOne($related, $foreignKey, $localKey); + } + /** + * Define a has-one-through relationship. + * + * @param string $related + * @param string $through + * @param string|null $firstKey + * @param string|null $secondKey + * @param string|null $localKey + * @param string|null $secondLocalKey + * @return \Illuminate\Database\Eloquent\Relations\HasOneThrough + * @static + */ + public static function hasOneThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasOneThrough($related, $through, $firstKey, $secondKey, $localKey, $secondLocalKey); + } + /** + * Define a polymorphic one-to-one relationship. + * + * @param string $related + * @param string $name + * @param string|null $type + * @param string|null $id + * @param string|null $localKey + * @return \Illuminate\Database\Eloquent\Relations\MorphOne + * @static + */ + public static function morphOne($related, $name, $type = null, $id = null, $localKey = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->morphOne($related, $name, $type, $id, $localKey); + } + /** + * Define an inverse one-to-one or many relationship. + * + * @param string $related + * @param string|null $foreignKey + * @param string|null $ownerKey + * @param string|null $relation + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + * @static + */ + public static function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->belongsTo($related, $foreignKey, $ownerKey, $relation); + } + /** + * Define a polymorphic, inverse one-to-one or many relationship. + * + * @param string|null $name + * @param string|null $type + * @param string|null $id + * @param string|null $ownerKey + * @return \Illuminate\Database\Eloquent\Relations\MorphTo + * @static + */ + public static function morphTo($name = null, $type = null, $id = null, $ownerKey = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->morphTo($name, $type, $id, $ownerKey); + } + /** + * Retrieve the actual class name for a given morph class. + * + * @param string $class + * @return string + * @static + */ + public static function getActualClassNameForMorph($class) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::getActualClassNameForMorph($class); + } + /** + * Create a pending has-many-through or has-one-through relationship. + * + * @param string|\Illuminate\Database\Eloquent\Relations\HasMany|\Illuminate\Database\Eloquent\Relations\HasOne $relationship + * @return \Illuminate\Database\Eloquent\PendingHasThroughRelationship + * @static + */ + public static function through($relationship) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->through($relationship); + } + /** + * Define a one-to-many relationship. + * + * @param string $related + * @param string|null $foreignKey + * @param string|null $localKey + * @return \Illuminate\Database\Eloquent\Relations\HasMany + * @static + */ + public static function hasMany($related, $foreignKey = null, $localKey = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasMany($related, $foreignKey, $localKey); + } + /** + * Define a has-many-through relationship. + * + * @param string $related + * @param string $through + * @param string|null $firstKey + * @param string|null $secondKey + * @param string|null $localKey + * @param string|null $secondLocalKey + * @return \Illuminate\Database\Eloquent\Relations\HasManyThrough + * @static + */ + public static function hasManyThrough($related, $through, $firstKey = null, $secondKey = null, $localKey = null, $secondLocalKey = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->hasManyThrough($related, $through, $firstKey, $secondKey, $localKey, $secondLocalKey); + } + /** + * Define a polymorphic one-to-many relationship. + * + * @param string $related + * @param string $name + * @param string|null $type + * @param string|null $id + * @param string|null $localKey + * @return \Illuminate\Database\Eloquent\Relations\MorphMany + * @static + */ + public static function morphMany($related, $name, $type = null, $id = null, $localKey = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->morphMany($related, $name, $type, $id, $localKey); + } + /** + * Define a many-to-many relationship. + * + * @param string $related + * @param string|null $table + * @param string|null $foreignPivotKey + * @param string|null $relatedPivotKey + * @param string|null $parentKey + * @param string|null $relatedKey + * @param string|null $relation + * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany + * @static + */ + public static function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, $parentKey = null, $relatedKey = null, $relation = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->belongsToMany($related, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relation); + } + /** + * Define a polymorphic many-to-many relationship. + * + * @param string $related + * @param string $name + * @param string|null $table + * @param string|null $foreignPivotKey + * @param string|null $relatedPivotKey + * @param string|null $parentKey + * @param string|null $relatedKey + * @param bool $inverse + * @return \Illuminate\Database\Eloquent\Relations\MorphToMany + * @static + */ + public static function morphToMany($related, $name, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, $parentKey = null, $relatedKey = null, $inverse = false) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->morphToMany($related, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $inverse); + } + /** + * Define a polymorphic, inverse many-to-many relationship. + * + * @param string $related + * @param string $name + * @param string|null $table + * @param string|null $foreignPivotKey + * @param string|null $relatedPivotKey + * @param string|null $parentKey + * @param string|null $relatedKey + * @return \Illuminate\Database\Eloquent\Relations\MorphToMany + * @static + */ + public static function morphedByMany($related, $name, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, $parentKey = null, $relatedKey = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->morphedByMany($related, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey); + } + /** + * Get the joining table name for a many-to-many relation. + * + * @param string $related + * @param \Illuminate\Database\Eloquent\Model|null $instance + * @return string + * @static + */ + public static function joiningTable($related, $instance = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->joiningTable($related, $instance); + } + /** + * Get this model's half of the intermediate table name for belongsToMany relationships. + * + * @return string + * @static + */ + public static function joiningTableSegment() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->joiningTableSegment(); + } + /** + * Determine if the model touches a given relation. + * + * @param string $relation + * @return bool + * @static + */ + public static function touches($relation) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->touches($relation); + } + /** + * Touch the owning relations of the model. + * + * @return void + * @static + */ + public static function touchOwners() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + $instance->touchOwners(); + } + /** + * Get the class name for polymorphic relations. + * + * @return string + * @static + */ + public static function getMorphClass() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getMorphClass(); + } + /** + * Get all the loaded relations for the instance. + * + * @return array + * @static + */ + public static function getRelations() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getRelations(); + } + /** + * Get a specified relationship. + * + * @param string $relation + * @return mixed + * @static + */ + public static function getRelation($relation) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getRelation($relation); + } + /** + * Determine if the given relation is loaded. + * + * @param string $key + * @return bool + * @static + */ + public static function relationLoaded($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->relationLoaded($key); + } + /** + * Set the given relationship on the model. + * + * @param string $relation + * @param mixed $value + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setRelation($relation, $value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setRelation($relation, $value); + } + /** + * Unset a loaded relationship. + * + * @param string $relation + * @return \Webpatser\Countries\Countries + * @static + */ + public static function unsetRelation($relation) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->unsetRelation($relation); + } + /** + * Set the entire relations array on the model. + * + * @param array $relations + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setRelations($relations) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setRelations($relations); + } + /** + * Duplicate the instance and unset all the loaded relations. + * + * @return \Webpatser\Countries\Countries + * @static + */ + public static function withoutRelations() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->withoutRelations(); + } + /** + * Unset all the loaded relations for the instance. + * + * @return \Webpatser\Countries\Countries + * @static + */ + public static function unsetRelations() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->unsetRelations(); + } + /** + * Get the relationships that are touched on save. + * + * @return array + * @static + */ + public static function getTouchedRelations() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getTouchedRelations(); + } + /** + * Set the relationships that are touched on save. + * + * @param array $touches + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setTouchedRelations($touches) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setTouchedRelations($touches); + } + /** + * Update the model's update timestamp. + * + * @param string|null $attribute + * @return bool + * @static + */ + public static function touch($attribute = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->touch($attribute); + } + /** + * Update the model's update timestamp without raising any events. + * + * @param string|null $attribute + * @return bool + * @static + */ + public static function touchQuietly($attribute = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->touchQuietly($attribute); + } + /** + * Update the creation and update timestamps. + * + * @return \Webpatser\Countries\Countries + * @static + */ + public static function updateTimestamps() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->updateTimestamps(); + } + /** + * Set the value of the "created at" attribute. + * + * @param mixed $value + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setCreatedAt($value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setCreatedAt($value); + } + /** + * Set the value of the "updated at" attribute. + * + * @param mixed $value + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setUpdatedAt($value) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setUpdatedAt($value); + } + /** + * Get a fresh timestamp for the model. + * + * @return \Illuminate\Support\Carbon + * @static + */ + public static function freshTimestamp() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->freshTimestamp(); + } + /** + * Get a fresh timestamp for the model. + * + * @return string + * @static + */ + public static function freshTimestampString() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->freshTimestampString(); + } + /** + * Determine if the model uses timestamps. + * + * @return bool + * @static + */ + public static function usesTimestamps() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->usesTimestamps(); + } + /** + * Get the name of the "created at" column. + * + * @return string|null + * @static + */ + public static function getCreatedAtColumn() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getCreatedAtColumn(); + } + /** + * Get the name of the "updated at" column. + * + * @return string|null + * @static + */ + public static function getUpdatedAtColumn() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getUpdatedAtColumn(); + } + /** + * Get the fully qualified "created at" column. + * + * @return string|null + * @static + */ + public static function getQualifiedCreatedAtColumn() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getQualifiedCreatedAtColumn(); + } + /** + * Get the fully qualified "updated at" column. + * + * @return string|null + * @static + */ + public static function getQualifiedUpdatedAtColumn() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getQualifiedUpdatedAtColumn(); + } + /** + * Disable timestamps for the current class during the given callback scope. + * + * @param callable $callback + * @return mixed + * @static + */ + public static function withoutTimestamps($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::withoutTimestamps($callback); + } + /** + * Disable timestamps for the given model classes during the given callback scope. + * + * @param array $models + * @param callable $callback + * @return mixed + * @static + */ + public static function withoutTimestampsOn($models, $callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::withoutTimestampsOn($models, $callback); + } + /** + * Determine if the given model is ignoring timestamps / touches. + * + * @param string|null $class + * @return bool + * @static + */ + public static function isIgnoringTimestamps($class = null) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::isIgnoringTimestamps($class); + } + /** + * Get the hidden attributes for the model. + * + * @return array + * @static + */ + public static function getHidden() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getHidden(); + } + /** + * Set the hidden attributes for the model. + * + * @param array $hidden + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setHidden($hidden) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setHidden($hidden); + } + /** + * Get the visible attributes for the model. + * + * @return array + * @static + */ + public static function getVisible() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getVisible(); + } + /** + * Set the visible attributes for the model. + * + * @param array $visible + * @return \Webpatser\Countries\Countries + * @static + */ + public static function setVisible($visible) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->setVisible($visible); + } + /** + * Make the given, typically hidden, attributes visible. + * + * @param array|string|null $attributes + * @return \Webpatser\Countries\Countries + * @static + */ + public static function makeVisible($attributes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->makeVisible($attributes); + } + /** + * Make the given, typically hidden, attributes visible if the given truth test passes. + * + * @param bool|\Closure $condition + * @param array|string|null $attributes + * @return \Webpatser\Countries\Countries + * @static + */ + public static function makeVisibleIf($condition, $attributes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->makeVisibleIf($condition, $attributes); + } + /** + * Make the given, typically visible, attributes hidden. + * + * @param array|string|null $attributes + * @return \Webpatser\Countries\Countries + * @static + */ + public static function makeHidden($attributes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->makeHidden($attributes); + } + /** + * Make the given, typically visible, attributes hidden if the given truth test passes. + * + * @param bool|\Closure $condition + * @param array|string|null $attributes + * @return \Webpatser\Countries\Countries + * @static + */ + public static function makeHiddenIf($condition, $attributes) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->makeHiddenIf($condition, $attributes); + } + /** + * Get the fillable attributes for the model. + * + * @return array + * @static + */ + public static function getFillable() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getFillable(); + } + /** + * Set the fillable attributes for the model. + * + * @param array $fillable + * @return \Webpatser\Countries\Countries + * @static + */ + public static function fillable($fillable) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->fillable($fillable); + } + /** + * Merge new fillable attributes with existing fillable attributes on the model. + * + * @param array $fillable + * @return \Webpatser\Countries\Countries + * @static + */ + public static function mergeFillable($fillable) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->mergeFillable($fillable); + } + /** + * Get the guarded attributes for the model. + * + * @return array + * @static + */ + public static function getGuarded() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->getGuarded(); + } + /** + * Set the guarded attributes for the model. + * + * @param array $guarded + * @return \Webpatser\Countries\Countries + * @static + */ + public static function guard($guarded) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->guard($guarded); + } + /** + * Merge new guarded attributes with existing guarded attributes on the model. + * + * @param array $guarded + * @return \Webpatser\Countries\Countries + * @static + */ + public static function mergeGuarded($guarded) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->mergeGuarded($guarded); + } + /** + * Disable all mass assignable restrictions. + * + * @param bool $state + * @return void + * @static + */ + public static function unguard($state = true) + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::unguard($state); + } + /** + * Enable the mass assignment restrictions. + * + * @return void + * @static + */ + public static function reguard() + { //Method inherited from \Illuminate\Database\Eloquent\Model + \Webpatser\Countries\Countries::reguard(); + } + /** + * Determine if the current state is "unguarded". + * + * @return bool + * @static + */ + public static function isUnguarded() + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::isUnguarded(); + } + /** + * Run the given callable while being unguarded. + * + * @param callable $callback + * @return mixed + * @static + */ + public static function unguarded($callback) + { //Method inherited from \Illuminate\Database\Eloquent\Model + return \Webpatser\Countries\Countries::unguarded($callback); + } + /** + * Determine if the given attribute may be mass assigned. + * + * @param string $key + * @return bool + * @static + */ + public static function isFillable($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->isFillable($key); + } + /** + * Determine if the given key is guarded. + * + * @param string $key + * @return bool + * @static + */ + public static function isGuarded($key) + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->isGuarded($key); + } + /** + * Determine if the model is totally guarded. + * + * @return bool + * @static + */ + public static function totallyGuarded() + { //Method inherited from \Illuminate\Database\Eloquent\Model + /** @var \Webpatser\Countries\Countries $instance */ + return $instance->totallyGuarded(); + } + + } + +} + + namespace App\Utils\ClientPortal\CustomMessage { + /** + * + * + */ + class CustomMessageFacade { + /** + * + * + * @static + */ + public static function client($client) + { + /** @var \App\Utils\ClientPortal\CustomMessage\CustomMessage $instance */ + return $instance->client($client); + } + /** + * + * + * @static + */ + public static function company($company) + { + /** @var \App\Utils\ClientPortal\CustomMessage\CustomMessage $instance */ + return $instance->company($company); + } + /** + * + * + * @static + */ + public static function contact($contact) + { + /** @var \App\Utils\ClientPortal\CustomMessage\CustomMessage $instance */ + return $instance->contact($contact); + } + /** + * + * + * @static + */ + public static function group($group) + { + /** @var \App\Utils\ClientPortal\CustomMessage\CustomMessage $instance */ + return $instance->group($group); + } + /** + * + * + * @static + */ + public static function entity($entity) + { + /** @var \App\Utils\ClientPortal\CustomMessage\CustomMessage $instance */ + return $instance->entity($entity); + } + /** + * + * + * @static + */ + public static function invitation($invitation) + { + /** @var \App\Utils\ClientPortal\CustomMessage\CustomMessage $instance */ + return $instance->invitation($invitation); + } + /** + * + * + * @static + */ + public static function message($message) + { + /** @var \App\Utils\ClientPortal\CustomMessage\CustomMessage $instance */ + return $instance->message($message); + } + + } + +} + + namespace Barryvdh\Debugbar\Facades { + /** + * + * + * @method static void alert(mixed $message) + * @method static void critical(mixed $message) + * @method static void debug(mixed $message) + * @method static void emergency(mixed $message) + * @method static void error(mixed $message) + * @method static void info(mixed $message) + * @method static void log(mixed $message) + * @method static void notice(mixed $message) + * @method static void warning(mixed $message) + * @see \Barryvdh\Debugbar\LaravelDebugbar + */ + class Debugbar { + /** + * Enable the Debugbar and boot, if not already booted. + * + * @static + */ + public static function enable() + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->enable(); + } + /** + * Boot the debugbar (add collectors, renderer and listener) + * + * @static + */ + public static function boot() + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->boot(); + } + /** + * + * + * @static + */ + public static function shouldCollect($name, $default = false) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->shouldCollect($name, $default); + } + /** + * Adds a data collector + * + * @param \DebugBar\DataCollector\DataCollectorInterface $collector + * @throws DebugBarException + * @return \Barryvdh\Debugbar\LaravelDebugbar + * @static + */ + public static function addCollector($collector) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->addCollector($collector); + } + /** + * Handle silenced errors + * + * @param $level + * @param $message + * @param string $file + * @param int $line + * @param array $context + * @throws \ErrorException + * @static + */ + public static function handleError($level, $message, $file = '', $line = 0, $context = []) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->handleError($level, $message, $file, $line, $context); + } + /** + * Starts a measure + * + * @param string $name Internal name, used to stop the measure + * @param string $label Public name + * @static + */ + public static function startMeasure($name, $label = null) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->startMeasure($name, $label); + } + /** + * Stops a measure + * + * @param string $name + * @static + */ + public static function stopMeasure($name) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->stopMeasure($name); + } + /** + * Adds an exception to be profiled in the debug bar + * + * @param \Exception $e + * @deprecated in favor of addThrowable + * @static + */ + public static function addException($e) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->addException($e); + } + /** + * Adds an exception to be profiled in the debug bar + * + * @param \Throwable $e + * @static + */ + public static function addThrowable($e) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->addThrowable($e); + } + /** + * Returns a JavascriptRenderer for this instance + * + * @param string $baseUrl + * @param string $basePathng + * @return \Barryvdh\Debugbar\JavascriptRenderer + * @static + */ + public static function getJavascriptRenderer($baseUrl = null, $basePath = null) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getJavascriptRenderer($baseUrl, $basePath); + } + /** + * Modify the response and inject the debugbar (or data in headers) + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Symfony\Component\HttpFoundation\Response $response + * @return \Symfony\Component\HttpFoundation\Response + * @static + */ + public static function modifyResponse($request, $response) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->modifyResponse($request, $response); + } + /** + * Check if the Debugbar is enabled + * + * @return boolean + * @static + */ + public static function isEnabled() + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->isEnabled(); + } + /** + * Collects the data from the collectors + * + * @return array + * @static + */ + public static function collect() + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->collect(); + } + /** + * Injects the web debug toolbar into the given Response. + * + * @param \Symfony\Component\HttpFoundation\Response $response A Response instance + * Based on https://github.com/symfony/WebProfilerBundle/blob/master/EventListener/WebDebugToolbarListener.php + * @static + */ + public static function injectDebugbar($response) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->injectDebugbar($response); + } + /** + * Disable the Debugbar + * + * @static + */ + public static function disable() + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->disable(); + } + /** + * Adds a measure + * + * @param string $label + * @param float $start + * @param float $end + * @static + */ + public static function addMeasure($label, $start, $end) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->addMeasure($label, $start, $end); + } + /** + * Utility function to measure the execution of a Closure + * + * @param string $label + * @param \Closure $closure + * @return mixed + * @static + */ + public static function measure($label, $closure) + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->measure($label, $closure); + } + /** + * Collect data in a CLI request + * + * @return array + * @static + */ + public static function collectConsole() + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->collectConsole(); + } + /** + * Adds a message to the MessagesCollector + * + * A message can be anything from an object to a string + * + * @param mixed $message + * @param string $label + * @static + */ + public static function addMessage($message, $label = 'info') + { + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->addMessage($message, $label); + } + /** + * Checks if a data collector has been added + * + * @param string $name + * @return boolean + * @static + */ + public static function hasCollector($name) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->hasCollector($name); + } + /** + * Returns a data collector + * + * @param string $name + * @return \DebugBar\DataCollector\DataCollectorInterface + * @throws DebugBarException + * @static + */ + public static function getCollector($name) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getCollector($name); + } + /** + * Returns an array of all data collectors + * + * @return \DebugBar\array[DataCollectorInterface] + * @static + */ + public static function getCollectors() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getCollectors(); + } + /** + * Sets the request id generator + * + * @param \DebugBar\RequestIdGeneratorInterface $generator + * @return \Barryvdh\Debugbar\LaravelDebugbar + * @static + */ + public static function setRequestIdGenerator($generator) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->setRequestIdGenerator($generator); + } + /** + * + * + * @return \DebugBar\RequestIdGeneratorInterface + * @static + */ + public static function getRequestIdGenerator() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getRequestIdGenerator(); + } + /** + * Returns the id of the current request + * + * @return string + * @static + */ + public static function getCurrentRequestId() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getCurrentRequestId(); + } + /** + * Sets the storage backend to use to store the collected data + * + * @param \DebugBar\StorageInterface $storage + * @return \Barryvdh\Debugbar\LaravelDebugbar + * @static + */ + public static function setStorage($storage = null) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->setStorage($storage); + } + /** + * + * + * @return \DebugBar\StorageInterface + * @static + */ + public static function getStorage() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getStorage(); + } + /** + * Checks if the data will be persisted + * + * @return boolean + * @static + */ + public static function isDataPersisted() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->isDataPersisted(); + } + /** + * Sets the HTTP driver + * + * @param \DebugBar\HttpDriverInterface $driver + * @return \Barryvdh\Debugbar\LaravelDebugbar + * @static + */ + public static function setHttpDriver($driver) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->setHttpDriver($driver); + } + /** + * Returns the HTTP driver + * + * If no http driver where defined, a PhpHttpDriver is automatically created + * + * @return \DebugBar\HttpDriverInterface + * @static + */ + public static function getHttpDriver() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getHttpDriver(); + } + /** + * Returns collected data + * + * Will collect the data if none have been collected yet + * + * @return array + * @static + */ + public static function getData() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getData(); + } + /** + * Returns an array of HTTP headers containing the data + * + * @param string $headerName + * @param integer $maxHeaderLength + * @return array + * @static + */ + public static function getDataAsHeaders($headerName = 'phpdebugbar', $maxHeaderLength = 4096, $maxTotalHeaderLength = 250000) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getDataAsHeaders($headerName, $maxHeaderLength, $maxTotalHeaderLength); + } + /** + * Sends the data through the HTTP headers + * + * @param bool $useOpenHandler + * @param string $headerName + * @param integer $maxHeaderLength + * @return \Barryvdh\Debugbar\LaravelDebugbar + * @static + */ + public static function sendDataInHeaders($useOpenHandler = null, $headerName = 'phpdebugbar', $maxHeaderLength = 4096) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->sendDataInHeaders($useOpenHandler, $headerName, $maxHeaderLength); + } + /** + * Stacks the data in the session for later rendering + * + * @static + */ + public static function stackData() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->stackData(); + } + /** + * Checks if there is stacked data in the session + * + * @return boolean + * @static + */ + public static function hasStackedData() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->hasStackedData(); + } + /** + * Returns the data stacked in the session + * + * @param boolean $delete Whether to delete the data in the session + * @return array + * @static + */ + public static function getStackedData($delete = true) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getStackedData($delete); + } + /** + * Sets the key to use in the $_SESSION array + * + * @param string $ns + * @return \Barryvdh\Debugbar\LaravelDebugbar + * @static + */ + public static function setStackDataSessionNamespace($ns) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->setStackDataSessionNamespace($ns); + } + /** + * Returns the key used in the $_SESSION array + * + * @return string + * @static + */ + public static function getStackDataSessionNamespace() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->getStackDataSessionNamespace(); + } + /** + * Sets whether to only use the session to store stacked data even + * if a storage is enabled + * + * @param boolean $enabled + * @return \Barryvdh\Debugbar\LaravelDebugbar + * @static + */ + public static function setStackAlwaysUseSessionStorage($enabled = true) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->setStackAlwaysUseSessionStorage($enabled); + } + /** + * Checks if the session is always used to store stacked data + * even if a storage is enabled + * + * @return boolean + * @static + */ + public static function isStackAlwaysUseSessionStorage() + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->isStackAlwaysUseSessionStorage(); + } + /** + * + * + * @static + */ + public static function offsetSet($key, $value) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->offsetSet($key, $value); + } + /** + * + * + * @static + */ + public static function offsetGet($key) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->offsetGet($key); + } + /** + * + * + * @static + */ + public static function offsetExists($key) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->offsetExists($key); + } + /** + * + * + * @static + */ + public static function offsetUnset($key) + { //Method inherited from \DebugBar\DebugBar + /** @var \Barryvdh\Debugbar\LaravelDebugbar $instance */ + return $instance->offsetUnset($key); + } + + } + +} + + namespace L5Swagger { + /** + * + * + */ + class L5SwaggerFacade { + /** + * + * + * @throws L5SwaggerException + * @static + */ + public static function generateDocs() + { + /** @var \L5Swagger\Generator $instance */ + return $instance->generateDocs(); + } + + } + +} + + namespace Imdhemy\Purchases\Facades { + /** + * + * + */ + class Product { + /** + * + * + * @param \GuzzleHttp\ClientInterface|null $client + * @return self + * @static + */ + public static function googlePlay($client = null) + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->googlePlay($client); + } + /** + * + * + * @return self + * @static + */ + public static function appStore() + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->appStore(); + } + /** + * + * + * @param string $packageName + * @return self + * @static + */ + public static function packageName($packageName) + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->packageName($packageName); + } + /** + * + * + * @param string $itemId + * @return self + * @static + */ + public static function id($itemId) + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->id($itemId); + } + /** + * + * + * @param string $token + * @return self + * @static + */ + public static function token($token) + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->token($token); + } + /** + * + * + * @return \Imdhemy\GooglePlay\Products\ProductPurchase + * @throws GuzzleException + * @static + */ + public static function get() + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->get(); + } + /** + * + * + * @param string|null $developerPayload + * @throws GuzzleException + * @static + */ + public static function acknowledge($developerPayload = null) + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->acknowledge($developerPayload); + } + /** + * + * + * @return \Imdhemy\AppStore\Receipts\ReceiptResponse + * @throws GuzzleException|InvalidReceiptException + * @static + */ + public static function verifyReceipt() + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->verifyReceipt(); + } + /** + * + * + * @param string $receiptData + * @return \Imdhemy\Purchases\Product + * @static + */ + public static function receiptData($receiptData) + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->receiptData($receiptData); + } + /** + * + * + * @param string $password + * @return \Imdhemy\Purchases\Product + * @static + */ + public static function password($password) + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->password($password); + } + /** + * + * + * @return \Imdhemy\GooglePlay\Products\Product + * @static + */ + public static function createProduct() + { + /** @var \Imdhemy\Purchases\Product $instance */ + return $instance->createProduct(); + } + + } + /** + * + * + */ + class Subscription { + /** + * + * + * @param \GuzzleHttp\ClientInterface|null $client + * @return self + * @static + */ + public static function googlePlay($client = null) + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->googlePlay($client); + } + /** + * + * + * @return self + * @static + */ + public static function appStore() + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->appStore(); + } + /** + * + * + * @param string $itemId + * @return self + * @static + */ + public static function id($itemId) + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->id($itemId); + } + /** + * + * + * @param string $token + * @return self + * @static + */ + public static function token($token) + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->token($token); + } + /** + * + * + * @param string $packageName + * @return self + * @static + */ + public static function packageName($packageName) + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->packageName($packageName); + } + /** + * + * + * @return \Imdhemy\AppStore\Receipts\ReceiptResponse + * @throws GuzzleException|InvalidReceiptException + * @static + */ + public static function verifyReceipt() + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->verifyReceipt(); + } + /** + * + * + * @return \Imdhemy\AppStore\Receipts\ReceiptResponse + * @throws GuzzleException|InvalidReceiptException + * @static + */ + public static function verifyRenewable() + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->verifyRenewable(); + } + /** + * + * + * @return self + * @static + */ + public static function renewable() + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->renewable(); + } + /** + * + * + * @return self + * @static + */ + public static function nonRenewable() + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->nonRenewable(); + } + /** + * + * + * @return \Imdhemy\GooglePlay\Subscriptions\SubscriptionPurchase + * @throws GuzzleException + * @static + */ + public static function get() + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->get(); + } + /** + * + * + * @param string|null $developerPayload + * @throws GuzzleException + * @static + */ + public static function acknowledge($developerPayload = null) + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->acknowledge($developerPayload); + } + /** + * + * + * @return \Imdhemy\GooglePlay\Subscriptions\Subscription + * @static + */ + public static function createSubscription() + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->createSubscription(); + } + /** + * + * + * @param string $receiptData + * @return \Imdhemy\Purchases\Subscription + * @static + */ + public static function receiptData($receiptData) + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->receiptData($receiptData); + } + /** + * + * + * @param string $password + * @return \Imdhemy\Purchases\Subscription + * @static + */ + public static function password($password) + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->password($password); + } + /** + * + * + * @return \Imdhemy\Purchases\Contracts\SubscriptionContract + * @throws GuzzleException + * @throws InvalidReceiptException + * @static + */ + public static function toStd() + { + /** @var \Imdhemy\Purchases\Subscription $instance */ + return $instance->toStd(); + } + + } + +} + + namespace Intervention\Image\Facades { + /** + * + * + */ + class Image { + /** + * Overrides configuration settings + * + * @param array $config + * @return self + * @static + */ + public static function configure($config = []) + { + /** @var \Intervention\Image\ImageManager $instance */ + return $instance->configure($config); + } + /** + * Initiates an Image instance from different input types + * + * @param mixed $data + * @return \Intervention\Image\Image + * @static + */ + public static function make($data) + { + /** @var \Intervention\Image\ImageManager $instance */ + return $instance->make($data); + } + /** + * Creates an empty image canvas + * + * @param int $width + * @param int $height + * @param mixed $background + * @return \Intervention\Image\Image + * @static + */ + public static function canvas($width, $height, $background = null) + { + /** @var \Intervention\Image\ImageManager $instance */ + return $instance->canvas($width, $height, $background); + } + /** + * Create new cached image and run callback + * (requires additional package intervention/imagecache) + * + * @param \Closure $callback + * @param int $lifetime + * @param boolean $returnObj + * @return \Image + * @static + */ + public static function cache($callback, $lifetime = null, $returnObj = false) + { + /** @var \Intervention\Image\ImageManager $instance */ + return $instance->cache($callback, $lifetime, $returnObj); + } + + } + +} + + namespace InvoiceNinja\Inspector { + /** + * + * + * @see \InvoiceNinja\Inspector\Skeleton\SkeletonClass + */ + class InspectorFacade { + /** + * + * + * @static + */ + public static function setConnectionName($connectionName) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->setConnectionName($connectionName); + } + /** + * + * + * @static + */ + public static function getConnectionName() + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->getConnectionName(); + } + /** + * + * + * @static + */ + public static function getSchemaManager() + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->getSchemaManager(); + } + /** + * + * + * @static + */ + public static function getTableNames() + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->getTableNames(); + } + /** + * + * + * @static + */ + public static function getTableSchema($table) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->getTableSchema($table); + } + /** + * + * + * @static + */ + public static function getTableColumns($table) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->getTableColumns($table); + } + /** + * + * + * @static + */ + public static function getTable($table) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->getTable($table); + } + /** + * + * + * @static + */ + public static function getTableRecords($table, $columns = []) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->getTableRecords($table, $columns); + } + /** + * + * + * @static + */ + public static function getTableRecord($table, $value, $column = 'id') + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->getTableRecord($table, $value, $column); + } + /** + * + * + * @static + */ + public static function updateTableRecord($table, $id, $request, $column = 'id') + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->updateTableRecord($table, $id, $request, $column); + } + /** + * + * + * @static + */ + public static function validate($request, $table) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->validate($request, $table); + } + /** + * + * + * @static + */ + public static function filterEnabledTables($tableNames) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->filterEnabledTables($tableNames); + } + /** + * + * + * @static + */ + public static function isTableEnabled($tableName) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->isTableEnabled($tableName); + } + /** + * + * + * @static + */ + public static function checkTableAvailablility($tableName) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->checkTableAvailablility($tableName); + } + /** + * + * + * @static + */ + public static function filterEnabledColumns($columns, $tableName) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->filterEnabledColumns($columns, $tableName); + } + /** + * + * + * @static + */ + public static function generateValidationFields($column, $columns) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->generateValidationFields($column, $columns); + } + /** + * + * + * @static + */ + public static function transformFields($requestBody) + { + /** @var \InvoiceNinja\Inspector\Inspector $instance */ + return $instance->transformFields($requestBody); + } + + } + +} + + namespace Laravel\Socialite\Facades { + /** + * + * + * @see \Laravel\Socialite\SocialiteManager + */ + class Socialite { + /** + * Get a driver instance. + * + * @param string $driver + * @return mixed + * @static + */ + public static function with($driver) + { + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->with($driver); + } + /** + * Build an OAuth 2 provider instance. + * + * @param string $provider + * @param array $config + * @return \Laravel\Socialite\Two\AbstractProvider + * @static + */ + public static function buildProvider($provider, $config) + { + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->buildProvider($provider, $config); + } + /** + * Format the server configuration. + * + * @param array $config + * @return array + * @static + */ + public static function formatConfig($config) + { + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->formatConfig($config); + } + /** + * Forget all of the resolved driver instances. + * + * @return \Laravel\Socialite\SocialiteManager + * @static + */ + public static function forgetDrivers() + { + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->forgetDrivers(); + } + /** + * Set the container instance used by the manager. + * + * @param \Illuminate\Contracts\Container\Container $container + * @return \Laravel\Socialite\SocialiteManager + * @static + */ + public static function setContainer($container) + { + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->setContainer($container); + } + /** + * Get the default driver name. + * + * @return string + * @throws \InvalidArgumentException + * @static + */ + public static function getDefaultDriver() + { + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->getDefaultDriver(); + } + /** + * Get a driver instance. + * + * @param string|null $driver + * @return mixed + * @throws \InvalidArgumentException + * @static + */ + public static function driver($driver = null) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->driver($driver); + } + /** + * Register a custom driver creator Closure. + * + * @param string $driver + * @param \Closure $callback + * @return \Laravel\Socialite\SocialiteManager + * @static + */ + public static function extend($driver, $callback) + { //Method inherited from \Illuminate\Support\Manager + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->extend($driver, $callback); + } + /** + * Get all of the created "drivers". + * + * @return array + * @static + */ + public static function getDrivers() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->getDrivers(); + } + /** + * Get the container instance used by the manager. + * + * @return \Illuminate\Contracts\Container\Container + * @static + */ + public static function getContainer() + { //Method inherited from \Illuminate\Support\Manager + /** @var \Laravel\Socialite\SocialiteManager $instance */ + return $instance->getContainer(); + } + + } + +} + + namespace Livewire { + /** + * + * + * @see \Livewire\LivewireManager + */ + class Livewire { + /** + * + * + * @static + */ + public static function component($alias, $viewClass = null) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->component($alias, $viewClass); + } + /** + * + * + * @static + */ + public static function getAlias($class, $default = null) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->getAlias($class, $default); + } + /** + * + * + * @static + */ + public static function getComponentAliases() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->getComponentAliases(); + } + /** + * + * + * @static + */ + public static function getClass($alias) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->getClass($alias); + } + /** + * + * + * @static + */ + public static function getInstance($component, $id) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->getInstance($component, $id); + } + /** + * + * + * @static + */ + public static function mount($name, $params = []) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->mount($name, $params); + } + /** + * + * + * @static + */ + public static function dummyMount($id, $tagName) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->dummyMount($id, $tagName); + } + /** + * + * + * @static + */ + public static function test($name, $params = []) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->test($name, $params); + } + /** + * + * + * @static + */ + public static function visit($browser, $class, $queryString = '') + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->visit($browser, $class, $queryString); + } + /** + * + * + * @static + */ + public static function actingAs($user, $driver = null) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->actingAs($user, $driver); + } + /** + * + * + * @static + */ + public static function addPersistentMiddleware($middleware) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->addPersistentMiddleware($middleware); + } + /** + * + * + * @static + */ + public static function setPersistentMiddleware($middleware) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->setPersistentMiddleware($middleware); + } + /** + * + * + * @static + */ + public static function getPersistentMiddleware() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->getPersistentMiddleware(); + } + /** + * + * + * @static + */ + public static function styles($options = []) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->styles($options); + } + /** + * + * + * @static + */ + public static function scripts($options = []) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->scripts($options); + } + /** + * + * + * @static + */ + public static function isLivewireRequest() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->isLivewireRequest(); + } + /** + * + * + * @static + */ + public static function isDefinitelyLivewireRequest() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->isDefinitelyLivewireRequest(); + } + /** + * + * + * @static + */ + public static function isProbablyLivewireRequest() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->isProbablyLivewireRequest(); + } + /** + * + * + * @static + */ + public static function originalUrl() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->originalUrl(); + } + /** + * + * + * @static + */ + public static function originalPath() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->originalPath(); + } + /** + * + * + * @static + */ + public static function originalMethod() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->originalMethod(); + } + /** + * + * + * @static + */ + public static function getRootElementTagName($dom) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->getRootElementTagName($dom); + } + /** + * + * + * @static + */ + public static function dispatch($event, ...$params) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->dispatch($event, ...$params); + } + /** + * + * + * @static + */ + public static function listen($event, $callback) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->listen($event, $callback); + } + /** + * + * + * @static + */ + public static function isOnVapor() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->isOnVapor(); + } + /** + * + * + * @static + */ + public static function isRunningServerless() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->isRunningServerless(); + } + /** + * + * + * @static + */ + public static function withQueryParams($queryParams) + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->withQueryParams($queryParams); + } + /** + * + * + * @static + */ + public static function setBackButtonCache() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->setBackButtonCache(); + } + /** + * + * + * @static + */ + public static function disableBackButtonCache() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->disableBackButtonCache(); + } + /** + * + * + * @static + */ + public static function enableBackButtonCache() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->enableBackButtonCache(); + } + /** + * + * + * @static + */ + public static function shouldDisableBackButtonCache() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->shouldDisableBackButtonCache(); + } + /** + * + * + * @static + */ + public static function flushState() + { + /** @var \Livewire\LivewireManager $instance */ + return $instance->flushState(); + } + + } + +} + + namespace Nwidart\Modules\Facades { + /** + * + * + */ + class Module { + /** + * Add other module location. + * + * @param string $path + * @return \Nwidart\Modules\Laravel\LaravelFileRepository + * @static + */ + public static function addLocation($path) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->addLocation($path); + } + /** + * Get all additional paths. + * + * @return array + * @static + */ + public static function getPaths() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getPaths(); + } + /** + * Get scanned modules paths. + * + * @return array + * @static + */ + public static function getScanPaths() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getScanPaths(); + } + /** + * Get & scan all modules. + * + * @return array + * @static + */ + public static function scan() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->scan(); + } + /** + * Get all modules. + * + * @return array + * @static + */ + public static function all() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->all(); + } + /** + * Get cached modules. + * + * @return array + * @static + */ + public static function getCached() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getCached(); + } + /** + * Get all modules as collection instance. + * + * @return \Nwidart\Modules\Collection + * @static + */ + public static function toCollection() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->toCollection(); + } + /** + * Get modules by status. + * + * @param $status + * @return array + * @static + */ + public static function getByStatus($status) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getByStatus($status); + } + /** + * Determine whether the given module exist. + * + * @param $name + * @return bool + * @static + */ + public static function has($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->has($name); + } + /** + * Get list of enabled modules. + * + * @return array + * @static + */ + public static function allEnabled() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->allEnabled(); + } + /** + * Get list of disabled modules. + * + * @return array + * @static + */ + public static function allDisabled() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->allDisabled(); + } + /** + * Get count from all modules. + * + * @return int + * @static + */ + public static function count() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->count(); + } + /** + * Get all ordered modules. + * + * @param string $direction + * @return array + * @static + */ + public static function getOrdered($direction = 'asc') + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getOrdered($direction); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function getPath() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getPath(); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function register() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->register(); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function boot() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->boot(); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function find($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->find($name); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function findByAlias($alias) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->findByAlias($alias); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function findRequirements($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->findRequirements($name); + } + /** + * Find a specific module, if there return that, otherwise throw exception. + * + * @param $name + * @return \Module + * @throws ModuleNotFoundException + * @static + */ + public static function findOrFail($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->findOrFail($name); + } + /** + * Get all modules as laravel collection instance. + * + * @param $status + * @return \Nwidart\Modules\Collection + * @static + */ + public static function collections($status = 1) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->collections($status); + } + /** + * Get module path for a specific module. + * + * @param $module + * @return string + * @static + */ + public static function getModulePath($module) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getModulePath($module); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function assetPath($module) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->assetPath($module); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function config($key, $default = null) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->config($key, $default); + } + /** + * Get storage path for module used. + * + * @return string + * @static + */ + public static function getUsedStoragePath() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getUsedStoragePath(); + } + /** + * Set module used for cli session. + * + * @param $name + * @throws ModuleNotFoundException + * @static + */ + public static function setUsed($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->setUsed($name); + } + /** + * Forget the module used for cli session. + * + * @static + */ + public static function forgetUsed() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->forgetUsed(); + } + /** + * Get module used for cli session. + * + * @return string + * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException + * @static + */ + public static function getUsedNow() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getUsedNow(); + } + /** + * Get laravel filesystem instance. + * + * @return \Nwidart\Modules\Filesystem + * @static + */ + public static function getFiles() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getFiles(); + } + /** + * Get module assets path. + * + * @return string + * @static + */ + public static function getAssetsPath() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getAssetsPath(); + } + /** + * Get asset url from a specific module. + * + * @param string $asset + * @return string + * @throws InvalidAssetPath + * @static + */ + public static function asset($asset) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->asset($asset); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function isEnabled($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->isEnabled($name); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function isDisabled($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->isDisabled($name); + } + /** + * Enabling a specific module. + * + * @param string $name + * @return void + * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException + * @static + */ + public static function enable($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + $instance->enable($name); + } + /** + * Disabling a specific module. + * + * @param string $name + * @return void + * @throws \Nwidart\Modules\Exceptions\ModuleNotFoundException + * @static + */ + public static function disable($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + $instance->disable($name); + } + /** + * + * + * @inheritDoc + * @static + */ + public static function delete($name) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->delete($name); + } + /** + * Update dependencies for the specified module. + * + * @param string $module + * @static + */ + public static function update($module) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->update($module); + } + /** + * Install the specified module. + * + * @param string $name + * @param string $version + * @param string $type + * @param bool $subtree + * @return \Symfony\Component\Process\Process + * @static + */ + public static function install($name, $version = 'dev-master', $type = 'composer', $subtree = false) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->install($name, $version, $type, $subtree); + } + /** + * Get stub path. + * + * @return string|null + * @static + */ + public static function getStubPath() + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->getStubPath(); + } + /** + * Set stub path. + * + * @param string $stubPath + * @return \Nwidart\Modules\Laravel\LaravelFileRepository + * @static + */ + public static function setStubPath($stubPath) + { //Method inherited from \Nwidart\Modules\FileRepository + /** @var \Nwidart\Modules\Laravel\LaravelFileRepository $instance */ + return $instance->setStubPath($stubPath); + } + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { //Method inherited from \Nwidart\Modules\FileRepository + \Nwidart\Modules\Laravel\LaravelFileRepository::macro($name, $macro); + } + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { //Method inherited from \Nwidart\Modules\FileRepository + \Nwidart\Modules\Laravel\LaravelFileRepository::mixin($mixin, $replace); + } + /** + * Checks if macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { //Method inherited from \Nwidart\Modules\FileRepository + return \Nwidart\Modules\Laravel\LaravelFileRepository::hasMacro($name); + } + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { //Method inherited from \Nwidart\Modules\FileRepository + \Nwidart\Modules\Laravel\LaravelFileRepository::flushMacros(); + } + + } + +} + + namespace Sentry\Laravel { + /** + * + * + * @see \Sentry\State\HubInterface + */ + class Facade { + /** + * Gets the client bound to the top of the stack. + * + * @static + */ + public static function getClient() + { + /** @var \Sentry\State\Hub $instance */ + return $instance->getClient(); + } + /** + * Gets the ID of the last captured event. + * + * @static + */ + public static function getLastEventId() + { + /** @var \Sentry\State\Hub $instance */ + return $instance->getLastEventId(); + } + /** + * Creates a new scope to store context information that will be layered on + * top of the current one. It is isolated, i.e. all breadcrumbs and context + * information added to this scope will be removed once the scope ends. Be + * sure to always remove this scope with {@see Hub::popScope} when the + * operation finishes or throws. + * + * @static + */ + public static function pushScope() + { + /** @var \Sentry\State\Hub $instance */ + return $instance->pushScope(); + } + /** + * Removes a previously pushed scope from the stack. This restores the state + * before the scope was pushed. All breadcrumbs and context information added + * since the last call to {@see Hub::pushScope} are discarded. + * + * @static + */ + public static function popScope() + { + /** @var \Sentry\State\Hub $instance */ + return $instance->popScope(); + } + /** + * Creates a new scope with and executes the given operation within. The scope + * is automatically removed once the operation finishes or throws. + * + * @param callable $callback The callback to be executed + * @return mixed|void The callback's return value, upon successful execution + * @psalm-template T + * @psalm-param callable(Scope): T $callback + * @psalm-return T + * @static + */ + public static function withScope($callback) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->withScope($callback); + } + /** + * Calls the given callback passing to it the current scope so that any + * operation can be run within its context. + * + * @param callable $callback The callback to be executed + * @static + */ + public static function configureScope($callback) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->configureScope($callback); + } + /** + * Binds the given client to the current scope. + * + * @param \Sentry\ClientInterface $client The client + * @static + */ + public static function bindClient($client) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->bindClient($client); + } + /** + * Captures a message event and sends it to Sentry. + * + * @param string $message The message + * @param \Sentry\Severity|null $level The severity level of the message + * @param \Sentry\EventHint|null $hint Object that can contain additional information about the event + * @static + */ + public static function captureMessage($message, $level = null, $hint = null) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->captureMessage($message, $level, $hint); + } + /** + * Captures an exception event and sends it to Sentry. + * + * @param \Throwable $exception The exception + * @param \Sentry\EventHint|null $hint Object that can contain additional information about the event + * @static + */ + public static function captureException($exception, $hint = null) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->captureException($exception, $hint); + } + /** + * Captures a new event using the provided data. + * + * @param \Event $event The event being captured + * @param \Sentry\EventHint|null $hint May contain additional information about the event + * @static + */ + public static function captureEvent($event, $hint = null) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->captureEvent($event, $hint); + } + /** + * Captures an event that logs the last occurred error. + * + * @param \Sentry\EventHint|null $hint Object that can contain additional information about the event + * @static + */ + public static function captureLastError($hint = null) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->captureLastError($hint); + } + /** + * Records a new breadcrumb which will be attached to future events. They + * will be added to subsequent events to provide more context on user's + * actions prior to an error or crash. + * + * @param \Sentry\Breadcrumb $breadcrumb The breadcrumb to record + * @return bool Whether the breadcrumb was actually added to the current scope + * @static + */ + public static function addBreadcrumb($breadcrumb) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->addBreadcrumb($breadcrumb); + } + /** + * Gets the integration whose FQCN matches the given one if it's available on the current client. + * + * @param string $className The FQCN of the integration + * @psalm-template T of IntegrationInterface + * @psalm-param class-string $className + * @psalm-return T|null + * @static + */ + public static function getIntegration($className) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->getIntegration($className); + } + /** + * Starts a new `Transaction` and returns it. This is the entry point to manual + * tracing instrumentation. + * + * A tree structure can be built by adding child spans to the transaction, and + * child spans to other spans. To start a new child span within the transaction + * or any span, call the respective `startChild()` method. + * + * Every child span must be finished before the transaction is finished, + * otherwise the unfinished spans are discarded. + * + * The transaction must be finished with a call to its `finish()` method, at + * which point the transaction with all its finished child spans will be sent to + * Sentry. + * + * @param \Sentry\State\array $customSamplingContext Additional context that will be passed to the {@see SamplingContext} + * @param \Sentry\Tracing\TransactionContext $context Properties of the new transaction + * @param \Sentry\State\array $customSamplingContext Additional context that will be passed to the {@see SamplingContext} + * @static + */ + public static function startTransaction($context, $customSamplingContext = []) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->startTransaction($context, $customSamplingContext); + } + /** + * Returns the transaction that is on the Hub. + * + * @static + */ + public static function getTransaction() + { + /** @var \Sentry\State\Hub $instance */ + return $instance->getTransaction(); + } + /** + * Sets the span on the Hub. + * + * @param \Sentry\Tracing\Span|null $span The span + * @static + */ + public static function setSpan($span) + { + /** @var \Sentry\State\Hub $instance */ + return $instance->setSpan($span); + } + /** + * Returns the span that is on the Hub. + * + * @static + */ + public static function getSpan() + { + /** @var \Sentry\State\Hub $instance */ + return $instance->getSpan(); + } + + } + +} + + namespace Spatie\LaravelIgnition\Facades { + /** + * + * + * @see \Spatie\FlareClient\Flare + */ + class Flare { + /** + * + * + * @static + */ + public static function make($apiKey = null, $contextDetector = null) + { + return \Spatie\FlareClient\Flare::make($apiKey, $contextDetector); + } + /** + * + * + * @static + */ + public static function setApiToken($apiToken) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->setApiToken($apiToken); + } + /** + * + * + * @static + */ + public static function apiTokenSet() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->apiTokenSet(); + } + /** + * + * + * @static + */ + public static function setBaseUrl($baseUrl) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->setBaseUrl($baseUrl); + } + /** + * + * + * @static + */ + public static function setStage($stage) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->setStage($stage); + } + /** + * + * + * @static + */ + public static function sendReportsImmediately() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->sendReportsImmediately(); + } + /** + * + * + * @static + */ + public static function determineVersionUsing($determineVersionCallable) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->determineVersionUsing($determineVersionCallable); + } + /** + * + * + * @static + */ + public static function reportErrorLevels($reportErrorLevels) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->reportErrorLevels($reportErrorLevels); + } + /** + * + * + * @static + */ + public static function filterExceptionsUsing($filterExceptionsCallable) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->filterExceptionsUsing($filterExceptionsCallable); + } + /** + * + * + * @static + */ + public static function filterReportsUsing($filterReportsCallable) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->filterReportsUsing($filterReportsCallable); + } + /** + * + * + * @static + */ + public static function version() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->version(); + } + /** + * + * + * @return array> + * @static + */ + public static function getMiddleware() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->getMiddleware(); + } + /** + * + * + * @static + */ + public static function setContextProviderDetector($contextDetector) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->setContextProviderDetector($contextDetector); + } + /** + * + * + * @static + */ + public static function setContainer($container) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->setContainer($container); + } + /** + * + * + * @static + */ + public static function registerFlareHandlers() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->registerFlareHandlers(); + } + /** + * + * + * @static + */ + public static function registerExceptionHandler() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->registerExceptionHandler(); + } + /** + * + * + * @static + */ + public static function registerErrorHandler() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->registerErrorHandler(); + } + /** + * + * + * @param \Spatie\FlareClient\FlareMiddleware\FlareMiddleware|array|\Spatie\FlareClient\class-string $middleware + * @return \Spatie\FlareClient\Flare + * @static + */ + public static function registerMiddleware($middleware) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->registerMiddleware($middleware); + } + /** + * + * + * @return array> + * @static + */ + public static function getMiddlewares() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->getMiddlewares(); + } + /** + * + * + * @param string $name + * @param string $messageLevel + * @param \Spatie\FlareClient\array $metaData + * @return \Spatie\FlareClient\Flare + * @static + */ + public static function glow($name, $messageLevel = 'info', $metaData = []) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->glow($name, $messageLevel, $metaData); + } + /** + * + * + * @static + */ + public static function handleException($throwable) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->handleException($throwable); + } + /** + * + * + * @return mixed + * @static + */ + public static function handleError($code, $message, $file = '', $line = 0) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->handleError($code, $message, $file, $line); + } + /** + * + * + * @static + */ + public static function applicationPath($applicationPath) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->applicationPath($applicationPath); + } + /** + * + * + * @static + */ + public static function report($throwable, $callback = null, $report = null) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->report($throwable, $callback, $report); + } + /** + * + * + * @static + */ + public static function reportMessage($message, $logLevel, $callback = null) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->reportMessage($message, $logLevel, $callback); + } + /** + * + * + * @static + */ + public static function sendTestReport($throwable) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->sendTestReport($throwable); + } + /** + * + * + * @static + */ + public static function reset() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->reset(); + } + /** + * + * + * @static + */ + public static function anonymizeIp() + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->anonymizeIp(); + } + /** + * + * + * @param \Spatie\FlareClient\array $fieldNames + * @return \Spatie\FlareClient\Flare + * @static + */ + public static function censorRequestBodyFields($fieldNames) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->censorRequestBodyFields($fieldNames); + } + /** + * + * + * @static + */ + public static function createReport($throwable) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->createReport($throwable); + } + /** + * + * + * @static + */ + public static function createReportFromMessage($message, $logLevel) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->createReportFromMessage($message, $logLevel); + } + /** + * + * + * @static + */ + public static function stage($stage) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->stage($stage); + } + /** + * + * + * @static + */ + public static function messageLevel($messageLevel) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->messageLevel($messageLevel); + } + /** + * + * + * @param string $groupName + * @param mixed $default + * @return array + * @static + */ + public static function getGroup($groupName = 'context', $default = []) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->getGroup($groupName, $default); + } + /** + * + * + * @static + */ + public static function context($key, $value) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->context($key, $value); + } + /** + * + * + * @param string $groupName + * @param \Spatie\FlareClient\array $properties + * @return \Spatie\FlareClient\Flare + * @static + */ + public static function group($groupName, $properties) + { + /** @var \Spatie\FlareClient\Flare $instance */ + return $instance->group($groupName, $properties); + } + + } + +} + + namespace Turbo124\Beacon { + /** + * + * + * @see \Turbo124\Beacon\Skeleton\SkeletonClass + */ + class CollectorFacade { + /** + * + * + * @static + */ + public static function create($metric) + { + /** @var \Turbo124\Beacon\Collector $instance */ + return $instance->create($metric); + } + /** + * + * + * @static + */ + public static function increment() + { + /** @var \Turbo124\Beacon\Collector $instance */ + return $instance->increment(); + } + /** + * + * + * @static + */ + public static function decrement() + { + /** @var \Turbo124\Beacon\Collector $instance */ + return $instance->decrement(); + } + /** + * + * + * @static + */ + public static function setCount($count) + { + /** @var \Turbo124\Beacon\Collector $instance */ + return $instance->setCount($count); + } + /** + * + * + * @static + */ + public static function send() + { + /** @var \Turbo124\Beacon\Collector $instance */ + return $instance->send(); + } + /** + * + * + * @static + */ + public static function queue() + { + /** @var \Turbo124\Beacon\Collector $instance */ + return $instance->queue(); + } + /** + * + * + * @static + */ + public static function batch() + { + /** @var \Turbo124\Beacon\Collector $instance */ + return $instance->batch(); + } + + } + +} + + namespace Illuminate\Http { + /** + * + * + */ + class Request { + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestValidation() + * @param array $rules + * @param mixed $params + * @static + */ + public static function validate($rules, ...$params) + { + return \Illuminate\Http\Request::validate($rules, ...$params); + } + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestValidation() + * @param string $errorBag + * @param array $rules + * @param mixed $params + * @static + */ + public static function validateWithBag($errorBag, $rules, ...$params) + { + return \Illuminate\Http\Request::validateWithBag($errorBag, $rules, ...$params); + } + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestSignatureValidation() + * @param mixed $absolute + * @static + */ + public static function hasValidSignature($absolute = true) + { + return \Illuminate\Http\Request::hasValidSignature($absolute); + } + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestSignatureValidation() + * @static + */ + public static function hasValidRelativeSignature() + { + return \Illuminate\Http\Request::hasValidRelativeSignature(); + } + /** + * + * + * @see \Illuminate\Foundation\Providers\FoundationServiceProvider::registerRequestSignatureValidation() + * @param mixed $ignoreQuery + * @param mixed $absolute + * @static + */ + public static function hasValidSignatureWhileIgnoring($ignoreQuery = [], $absolute = true) + { + return \Illuminate\Http\Request::hasValidSignatureWhileIgnoring($ignoreQuery, $absolute); + } + + } + +} + + namespace Illuminate\Testing { + /** + * + * + * @mixin \Illuminate\Http\Response + */ + class TestResponse { + /** + * + * + * @see \Livewire\LivewireServiceProvider::registerTestMacros() + * @param mixed $component + * @static + */ + public static function assertSeeLivewire($component) + { + return \Illuminate\Testing\TestResponse::assertSeeLivewire($component); + } + /** + * + * + * @see \Livewire\LivewireServiceProvider::registerTestMacros() + * @param mixed $component + * @static + */ + public static function assertDontSeeLivewire($component) + { + return \Illuminate\Testing\TestResponse::assertDontSeeLivewire($component); + } + + } + /** + * + * + */ + class TestView { + /** + * + * + * @see \Livewire\LivewireServiceProvider::registerTestMacros() + * @param mixed $component + * @static + */ + public static function assertSeeLivewire($component) + { + return \Illuminate\Testing\TestView::assertSeeLivewire($component); + } + /** + * + * + * @see \Livewire\LivewireServiceProvider::registerTestMacros() + * @param mixed $component + * @static + */ + public static function assertDontSeeLivewire($component) + { + return \Illuminate\Testing\TestView::assertDontSeeLivewire($component); + } + + } + +} + + namespace Illuminate\Routing { + /** + * + * + * @mixin \Illuminate\Routing\RouteRegistrar + */ + class Router { + /** + * + * + * @see \Laravel\Ui\AuthRouteMethods::auth() + * @param mixed $options + * @static + */ + public static function auth($options = []) + { + return \Illuminate\Routing\Router::auth($options); + } + /** + * + * + * @see \Laravel\Ui\AuthRouteMethods::resetPassword() + * @static + */ + public static function resetPassword() + { + return \Illuminate\Routing\Router::resetPassword(); + } + /** + * + * + * @see \Laravel\Ui\AuthRouteMethods::confirmPassword() + * @static + */ + public static function confirmPassword() + { + return \Illuminate\Routing\Router::confirmPassword(); + } + /** + * + * + * @see \Laravel\Ui\AuthRouteMethods::emailVerification() + * @static + */ + public static function emailVerification() + { + return \Illuminate\Routing\Router::emailVerification(); + } + + } + +} + + namespace Illuminate\View { + /** + * + * + */ + class ComponentAttributeBag { + /** + * + * + * @see \Livewire\LivewireServiceProvider::registerViewMacros() + * @param mixed $name + * @static + */ + public static function wire($name) + { + return \Illuminate\View\ComponentAttributeBag::wire($name); + } + + } + /** + * + * + */ + class View { + /** + * + * + * @see \Livewire\Macros\ViewMacros::extends() + * @param mixed $view + * @param mixed $params + * @static + */ + public static function extends($view, $params = []) + { + return \Illuminate\View\View::extends($view, $params); + } + /** + * + * + * @see \Livewire\Macros\ViewMacros::layout() + * @param mixed $view + * @param mixed $params + * @static + */ + public static function layout($view, $params = []) + { + return \Illuminate\View\View::layout($view, $params); + } + /** + * + * + * @see \Livewire\Macros\ViewMacros::layoutData() + * @param mixed $data + * @static + */ + public static function layoutData($data = []) + { + return \Illuminate\View\View::layoutData($data); + } + /** + * + * + * @see \Livewire\Macros\ViewMacros::section() + * @param mixed $section + * @static + */ + public static function section($section) + { + return \Illuminate\View\View::section($section); + } + /** + * + * + * @see \Livewire\Macros\ViewMacros::slot() + * @param mixed $slot + * @static + */ + public static function slot($slot) + { + return \Illuminate\View\View::slot($slot); + } + + } + +} + + namespace Nwidart\Modules { + /** + * + * + */ + class Collection { + + } + +} + + namespace Illuminate\Mail { + /** + * + * + */ + class Mailer { + /** + * + * + * @see \App\Providers\AppServiceProvider::boot() + * @param string $postmark_key + * @static + */ + public static function postmark_config($postmark_key) + { + return \Illuminate\Mail\Mailer::postmark_config($postmark_key); + } + /** + * + * + * @see \App\Providers\AppServiceProvider::boot() + * @param string $secret + * @param string $domain + * @static + */ + public static function mailgun_config($secret, $domain) + { + return \Illuminate\Mail\Mailer::mailgun_config($secret, $domain); + } + + } + +} + + +namespace { + class App extends \Illuminate\Support\Facades\App {} + class Arr extends \Illuminate\Support\Arr {} + class Artisan extends \Illuminate\Support\Facades\Artisan {} + class Auth extends \Illuminate\Support\Facades\Auth {} + class Blade extends \Illuminate\Support\Facades\Blade {} + class Broadcast extends \Illuminate\Support\Facades\Broadcast {} + class Bus extends \Illuminate\Support\Facades\Bus {} + class Cache extends \Illuminate\Support\Facades\Cache {} + class Config extends \Illuminate\Support\Facades\Config {} + class Cookie extends \Illuminate\Support\Facades\Cookie {} + class Crypt extends \Illuminate\Support\Facades\Crypt {} + class Date extends \Illuminate\Support\Facades\Date {} + class DB extends \Illuminate\Support\Facades\DB {} + class Eloquent extends \Illuminate\Database\Eloquent\Model { + /** + * Create and return an un-saved model instance. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model|static + * @static + */ + public static function make($attributes = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->make($attributes); + } + + /** + * Register a new global scope. + * + * @param string $identifier + * @param \Illuminate\Database\Eloquent\Scope|\Closure $scope + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withGlobalScope($identifier, $scope) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withGlobalScope($identifier, $scope); + } + + /** + * Remove a registered global scope. + * + * @param \Illuminate\Database\Eloquent\Scope|string $scope + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withoutGlobalScope($scope) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withoutGlobalScope($scope); + } + + /** + * Remove all or passed registered global scopes. + * + * @param array|null $scopes + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withoutGlobalScopes($scopes = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withoutGlobalScopes($scopes); + } + + /** + * Get an array of global scopes that were removed from the query. + * + * @return array + * @static + */ + public static function removedScopes() + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->removedScopes(); + } + + /** + * Add a where clause on the primary key to the query. + * + * @param mixed $id + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereKey($id) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereKey($id); + } + + /** + * Add a where clause on the primary key to the query. + * + * @param mixed $id + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereKeyNot($id) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereKeyNot($id); + } + + /** + * Add a basic where clause to the query. + * + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function where($column, $operator = null, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->where($column, $operator, $value, $boolean); + } + + /** + * Add a basic where clause to the query, and return the first result. + * + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return \Illuminate\Database\Eloquent\Model|static|null + * @static + */ + public static function firstWhere($column, $operator = null, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->firstWhere($column, $operator, $value, $boolean); + } + + /** + * Add an "or where" clause to the query. + * + * @param \Closure|array|string|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhere($column, $operator = null, $value = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhere($column, $operator, $value); + } + + /** + * Add a basic "where not" clause to the query. + * + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereNot($column, $operator = null, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereNot($column, $operator, $value, $boolean); + } + + /** + * Add an "or where not" clause to the query. + * + * @param \Closure|array|string|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhereNot($column, $operator = null, $value = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereNot($column, $operator, $value); + } + + /** + * Add an "order by" clause for a timestamp to the query. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function latest($column = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->latest($column); + } + + /** + * Add an "order by" clause for a timestamp to the query. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function oldest($column = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->oldest($column); + } + + /** + * Create a collection of models from plain arrays. + * + * @param array $items + * @return \Illuminate\Database\Eloquent\Collection + * @static + */ + public static function hydrate($items) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->hydrate($items); + } + + /** + * Create a collection of models from a raw query. + * + * @param string $query + * @param array $bindings + * @return \Illuminate\Database\Eloquent\Collection + * @static + */ + public static function fromQuery($query, $bindings = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->fromQuery($query, $bindings); + } + + /** + * Find a model by its primary key. + * + * @param mixed $id + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null + * @static + */ + public static function find($id, $columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->find($id, $columns); + } + + /** + * Find multiple models by their primary keys. + * + * @param \Illuminate\Contracts\Support\Arrayable|array $ids + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Collection + * @static + */ + public static function findMany($ids, $columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->findMany($ids, $columns); + } + + /** + * Find a model by its primary key or throw an exception. + * + * @param mixed $id + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static|static[] + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model> + * @static + */ + public static function findOrFail($id, $columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->findOrFail($id, $columns); + } + + /** + * Find a model by its primary key or return fresh model instance. + * + * @param mixed $id + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model|static + * @static + */ + public static function findOrNew($id, $columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->findOrNew($id, $columns); + } + + /** + * Find a model by its primary key or call a callback. + * + * @param mixed $id + * @param \Closure|array|string $columns + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|mixed + * @static + */ + public static function findOr($id, $columns = [], $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->findOr($id, $columns, $callback); + } + + /** + * Get the first record matching the attributes or instantiate it. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model|static + * @static + */ + public static function firstOrNew($attributes = [], $values = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->firstOrNew($attributes, $values); + } + + /** + * Get the first record matching the attributes or create it. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model|static + * @static + */ + public static function firstOrCreate($attributes = [], $values = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->firstOrCreate($attributes, $values); + } + + /** + * Create or update a record matching the attributes, and fill it with values. + * + * @param array $attributes + * @param array $values + * @return \Illuminate\Database\Eloquent\Model|static + * @static + */ + public static function updateOrCreate($attributes, $values = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->updateOrCreate($attributes, $values); + } + + /** + * Execute the query and get the first result or throw an exception. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model|static + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model> + * @static + */ + public static function firstOrFail($columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->firstOrFail($columns); + } + + /** + * Execute the query and get the first result or call a callback. + * + * @param \Closure|array|string $columns + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Model|static|mixed + * @static + */ + public static function firstOr($columns = [], $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->firstOr($columns, $callback); + } + + /** + * Execute the query and get the first result if it's the sole matching record. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model> + * @throws \Illuminate\Database\MultipleRecordsFoundException + * @static + */ + public static function sole($columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->sole($columns); + } + + /** + * Get a single column's value from the first result of a query. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return mixed + * @static + */ + public static function value($column) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->value($column); + } + + /** + * Get a single column's value from the first result of a query if it's the sole matching record. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return mixed + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model> + * @throws \Illuminate\Database\MultipleRecordsFoundException + * @static + */ + public static function soleValue($column) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->soleValue($column); + } + + /** + * Get a single column's value from the first result of the query or throw an exception. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return mixed + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model> + * @static + */ + public static function valueOrFail($column) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->valueOrFail($column); + } + + /** + * Execute the query as a "select" statement. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Collection|static[] + * @static + */ + public static function get($columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->get($columns); + } + + /** + * Get the hydrated models without eager loading. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model[]|static[] + * @static + */ + public static function getModels($columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->getModels($columns); + } + + /** + * Eager load the relationships for the models. + * + * @param array $models + * @return array + * @static + */ + public static function eagerLoadRelations($models) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->eagerLoadRelations($models); + } + + /** + * Get a lazy collection for the given query. + * + * @return \Illuminate\Support\LazyCollection + * @static + */ + public static function cursor() + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->cursor(); + } + + /** + * Get a collection with the values of a given column. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @param string|null $key + * @return \Illuminate\Support\Collection + * @static + */ + public static function pluck($column, $key = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->pluck($column, $key); + } + + /** + * Paginate the given query. + * + * @param int|null|\Closure $perPage + * @param array|string $columns + * @param string $pageName + * @param int|null $page + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator + * @throws \InvalidArgumentException + * @static + */ + public static function paginate($perPage = null, $columns = [], $pageName = 'page', $page = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->paginate($perPage, $columns, $pageName, $page); + } + + /** + * Paginate the given query into a simple paginator. + * + * @param int|null $perPage + * @param array|string $columns + * @param string $pageName + * @param int|null $page + * @return \Illuminate\Contracts\Pagination\Paginator + * @static + */ + public static function simplePaginate($perPage = null, $columns = [], $pageName = 'page', $page = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->simplePaginate($perPage, $columns, $pageName, $page); + } + + /** + * Paginate the given query into a cursor paginator. + * + * @param int|null $perPage + * @param array|string $columns + * @param string $cursorName + * @param \Illuminate\Pagination\Cursor|string|null $cursor + * @return \Illuminate\Contracts\Pagination\CursorPaginator + * @static + */ + public static function cursorPaginate($perPage = null, $columns = [], $cursorName = 'cursor', $cursor = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->cursorPaginate($perPage, $columns, $cursorName, $cursor); + } + + /** + * Save a new model and return the instance. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model|$this + * @static + */ + public static function create($attributes = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->create($attributes); + } + + /** + * Save a new model and return the instance. Allow mass-assignment. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model|$this + * @static + */ + public static function forceCreate($attributes) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->forceCreate($attributes); + } + + /** + * Insert new records or update the existing ones. + * + * @param array $values + * @param array|string $uniqueBy + * @param array|null $update + * @return int + * @static + */ + public static function upsert($values, $uniqueBy, $update = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->upsert($values, $uniqueBy, $update); + } + + /** + * Register a replacement for the default delete function. + * + * @param \Closure $callback + * @return void + * @static + */ + public static function onDelete($callback) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + $instance->onDelete($callback); + } + + /** + * Call the given local model scopes. + * + * @param array|string $scopes + * @return static|mixed + * @static + */ + public static function scopes($scopes) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->scopes($scopes); + } + + /** + * Apply the scopes to the Eloquent builder instance and return it. + * + * @return static + * @static + */ + public static function applyScopes() + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->applyScopes(); + } + + /** + * Prevent the specified relations from being eager loaded. + * + * @param mixed $relations + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function without($relations) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->without($relations); + } + + /** + * Set the relationships that should be eager loaded while removing any previously added eager loading specifications. + * + * @param mixed $relations + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withOnly($relations) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withOnly($relations); + } + + /** + * Create a new instance of the model being queried. + * + * @param array $attributes + * @return \Illuminate\Database\Eloquent\Model|static + * @static + */ + public static function newModelInstance($attributes = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->newModelInstance($attributes); + } + + /** + * Apply query-time casts to the model instance. + * + * @param array $casts + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withCasts($casts) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withCasts($casts); + } + + /** + * Get the underlying query builder instance. + * + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function getQuery() + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->getQuery(); + } + + /** + * Set the underlying query builder instance. + * + * @param \Illuminate\Database\Query\Builder $query + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function setQuery($query) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->setQuery($query); + } + + /** + * Get a base query builder instance. + * + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function toBase() + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->toBase(); + } + + /** + * Get the relationships being eagerly loaded. + * + * @return array + * @static + */ + public static function getEagerLoads() + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->getEagerLoads(); + } + + /** + * Set the relationships being eagerly loaded. + * + * @param array $eagerLoad + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function setEagerLoads($eagerLoad) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->setEagerLoads($eagerLoad); + } + + /** + * Indicate that the given relationships should not be eagerly loaded. + * + * @param array $relations + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withoutEagerLoad($relations) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withoutEagerLoad($relations); + } + + /** + * Flush the relationships being eagerly loaded. + * + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withoutEagerLoads() + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withoutEagerLoads(); + } + + /** + * Get the model instance being queried. + * + * @return \Illuminate\Database\Eloquent\Model|static + * @static + */ + public static function getModel() + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->getModel(); + } + + /** + * Set a model instance for the model being queried. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function setModel($model) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->setModel($model); + } + + /** + * Get the given macro by name. + * + * @param string $name + * @return \Closure + * @static + */ + public static function getMacro($name) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->getMacro($name); + } + + /** + * Checks if a macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasMacro($name) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->hasMacro($name); + } + + /** + * Get the given global macro by name. + * + * @param string $name + * @return \Closure + * @static + */ + public static function getGlobalMacro($name) + { + return \Illuminate\Database\Eloquent\Builder::getGlobalMacro($name); + } + + /** + * Checks if a global macro is registered. + * + * @param string $name + * @return bool + * @static + */ + public static function hasGlobalMacro($name) + { + return \Illuminate\Database\Eloquent\Builder::hasGlobalMacro($name); + } + + /** + * Clone the Eloquent query builder. + * + * @return static + * @static + */ + public static function clone() + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->clone(); + } + + /** + * Chunk the results of the query. + * + * @param int $count + * @param callable $callback + * @return bool + * @static + */ + public static function chunk($count, $callback) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->chunk($count, $callback); + } + + /** + * Run a map over each item while chunking. + * + * @param callable $callback + * @param int $count + * @return \Illuminate\Support\Collection + * @static + */ + public static function chunkMap($callback, $count = 1000) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->chunkMap($callback, $count); + } + + /** + * Execute a callback over each item while chunking. + * + * @param callable $callback + * @param int $count + * @return bool + * @throws \RuntimeException + * @static + */ + public static function each($callback, $count = 1000) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->each($callback, $count); + } + + /** + * Chunk the results of a query by comparing IDs. + * + * @param int $count + * @param callable $callback + * @param string|null $column + * @param string|null $alias + * @return bool + * @static + */ + public static function chunkById($count, $callback, $column = null, $alias = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->chunkById($count, $callback, $column, $alias); + } + + /** + * Execute a callback over each item while chunking by ID. + * + * @param callable $callback + * @param int $count + * @param string|null $column + * @param string|null $alias + * @return bool + * @static + */ + public static function eachById($callback, $count = 1000, $column = null, $alias = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->eachById($callback, $count, $column, $alias); + } + + /** + * Query lazily, by chunks of the given size. + * + * @param int $chunkSize + * @return \Illuminate\Support\LazyCollection + * @throws \InvalidArgumentException + * @static + */ + public static function lazy($chunkSize = 1000) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->lazy($chunkSize); + } + + /** + * Query lazily, by chunking the results of a query by comparing IDs. + * + * @param int $chunkSize + * @param string|null $column + * @param string|null $alias + * @return \Illuminate\Support\LazyCollection + * @throws \InvalidArgumentException + * @static + */ + public static function lazyById($chunkSize = 1000, $column = null, $alias = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->lazyById($chunkSize, $column, $alias); + } + + /** + * Query lazily, by chunking the results of a query by comparing IDs in descending order. + * + * @param int $chunkSize + * @param string|null $column + * @param string|null $alias + * @return \Illuminate\Support\LazyCollection + * @throws \InvalidArgumentException + * @static + */ + public static function lazyByIdDesc($chunkSize = 1000, $column = null, $alias = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->lazyByIdDesc($chunkSize, $column, $alias); + } + + /** + * Execute the query and get the first result. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model|object|static|null + * @static + */ + public static function first($columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->first($columns); + } + + /** + * Execute the query and get the first result if it's the sole matching record. + * + * @param array|string $columns + * @return \Illuminate\Database\Eloquent\Model|object|static|null + * @throws \Illuminate\Database\RecordsNotFoundException + * @throws \Illuminate\Database\MultipleRecordsFoundException + * @static + */ + public static function baseSole($columns = []) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->baseSole($columns); + } + + /** + * Pass the query to a given callback. + * + * @param callable $callback + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function tap($callback) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->tap($callback); + } + + /** + * Apply the callback if the given "value" is (or resolves to) truthy. + * + * @template TWhenParameter + * @template TWhenReturnType + * @param \Illuminate\Database\Eloquent\(\Closure($this): TWhenParameter)|TWhenParameter|null $value + * @param \Illuminate\Database\Eloquent\(callable($this, TWhenParameter): TWhenReturnType)|null $callback + * @param \Illuminate\Database\Eloquent\(callable($this, TWhenParameter): TWhenReturnType)|null $default + * @return $this|\Illuminate\Database\Eloquent\TWhenReturnType + * @static + */ + public static function when($value = null, $callback = null, $default = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->when($value, $callback, $default); + } + + /** + * Apply the callback if the given "value" is (or resolves to) falsy. + * + * @template TUnlessParameter + * @template TUnlessReturnType + * @param \Illuminate\Database\Eloquent\(\Closure($this): TUnlessParameter)|TUnlessParameter|null $value + * @param \Illuminate\Database\Eloquent\(callable($this, TUnlessParameter): TUnlessReturnType)|null $callback + * @param \Illuminate\Database\Eloquent\(callable($this, TUnlessParameter): TUnlessReturnType)|null $default + * @return $this|\Illuminate\Database\Eloquent\TUnlessReturnType + * @static + */ + public static function unless($value = null, $callback = null, $default = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->unless($value, $callback, $default); + } + + /** + * Add a relationship count / exists condition to the query. + * + * @param \Illuminate\Database\Eloquent\Relations\Relation|string $relation + * @param string $operator + * @param int $count + * @param string $boolean + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + * @throws \RuntimeException + * @static + */ + public static function has($relation, $operator = '>=', $count = 1, $boolean = 'and', $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->has($relation, $operator, $count, $boolean, $callback); + } + + /** + * Add a relationship count / exists condition to the query with an "or". + * + * @param string $relation + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orHas($relation, $operator = '>=', $count = 1) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orHas($relation, $operator, $count); + } + + /** + * Add a relationship count / exists condition to the query. + * + * @param string $relation + * @param string $boolean + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function doesntHave($relation, $boolean = 'and', $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->doesntHave($relation, $boolean, $callback); + } + + /** + * Add a relationship count / exists condition to the query with an "or". + * + * @param string $relation + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orDoesntHave($relation) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orDoesntHave($relation); + } + + /** + * Add a relationship count / exists condition to the query with where clauses. + * + * @param string $relation + * @param \Closure|null $callback + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereHas($relation, $callback = null, $operator = '>=', $count = 1) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereHas($relation, $callback, $operator, $count); + } + + /** + * Add a relationship count / exists condition to the query with where clauses. + * + * Also load the relationship with same condition. + * + * @param string $relation + * @param \Closure|null $callback + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withWhereHas($relation, $callback = null, $operator = '>=', $count = 1) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withWhereHas($relation, $callback, $operator, $count); + } + + /** + * Add a relationship count / exists condition to the query with where clauses and an "or". + * + * @param string $relation + * @param \Closure|null $callback + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhereHas($relation, $callback = null, $operator = '>=', $count = 1) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereHas($relation, $callback, $operator, $count); + } + + /** + * Add a relationship count / exists condition to the query with where clauses. + * + * @param string $relation + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereDoesntHave($relation, $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereDoesntHave($relation, $callback); + } + + /** + * Add a relationship count / exists condition to the query with where clauses and an "or". + * + * @param string $relation + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhereDoesntHave($relation, $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereDoesntHave($relation, $callback); + } + + /** + * Add a polymorphic relationship count / exists condition to the query. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param string $operator + * @param int $count + * @param string $boolean + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function hasMorph($relation, $types, $operator = '>=', $count = 1, $boolean = 'and', $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->hasMorph($relation, $types, $operator, $count, $boolean, $callback); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with an "or". + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orHasMorph($relation, $types, $operator = '>=', $count = 1) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orHasMorph($relation, $types, $operator, $count); + } + + /** + * Add a polymorphic relationship count / exists condition to the query. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param string $boolean + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function doesntHaveMorph($relation, $types, $boolean = 'and', $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->doesntHaveMorph($relation, $types, $boolean, $callback); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with an "or". + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orDoesntHaveMorph($relation, $types) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orDoesntHaveMorph($relation, $types); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with where clauses. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|null $callback + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereHasMorph($relation, $types, $callback = null, $operator = '>=', $count = 1) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereHasMorph($relation, $types, $callback, $operator, $count); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with where clauses and an "or". + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|null $callback + * @param string $operator + * @param int $count + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhereHasMorph($relation, $types, $callback = null, $operator = '>=', $count = 1) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereHasMorph($relation, $types, $callback, $operator, $count); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with where clauses. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereDoesntHaveMorph($relation, $types, $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereDoesntHaveMorph($relation, $types, $callback); + } + + /** + * Add a polymorphic relationship count / exists condition to the query with where clauses and an "or". + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|null $callback + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhereDoesntHaveMorph($relation, $types, $callback = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereDoesntHaveMorph($relation, $types, $callback); + } + + /** + * Add a basic where clause to a relationship query. + * + * @param string $relation + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereRelation($relation, $column, $operator = null, $value = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereRelation($relation, $column, $operator, $value); + } + + /** + * Add an "or where" clause to a relationship query. + * + * @param string $relation + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhereRelation($relation, $column, $operator = null, $value = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereRelation($relation, $column, $operator, $value); + } + + /** + * Add a polymorphic relationship condition to the query with a where clause. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereMorphRelation($relation, $types, $column, $operator = null, $value = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereMorphRelation($relation, $types, $column, $operator, $value); + } + + /** + * Add a polymorphic relationship condition to the query with an "or where" clause. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param string|array $types + * @param \Closure|string|array|\Illuminate\Database\Query\Expression $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhereMorphRelation($relation, $types, $column, $operator = null, $value = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereMorphRelation($relation, $types, $column, $operator, $value); + } + + /** + * Add a morph-to relationship condition to the query. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param \Illuminate\Database\Eloquent\Model|string $model + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereMorphedTo($relation, $model, $boolean = 'and') + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereMorphedTo($relation, $model, $boolean); + } + + /** + * Add a not morph-to relationship condition to the query. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param \Illuminate\Database\Eloquent\Model|string $model + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function whereNotMorphedTo($relation, $model, $boolean = 'and') + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereNotMorphedTo($relation, $model, $boolean); + } + + /** + * Add a morph-to relationship condition to the query with an "or where" clause. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param \Illuminate\Database\Eloquent\Model|string $model + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhereMorphedTo($relation, $model) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereMorphedTo($relation, $model); + } + + /** + * Add a not morph-to relationship condition to the query with an "or where" clause. + * + * @param \Illuminate\Database\Eloquent\Relations\MorphTo|string $relation + * @param \Illuminate\Database\Eloquent\Model|string $model + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function orWhereNotMorphedTo($relation, $model) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereNotMorphedTo($relation, $model); + } + + /** + * Add a "belongs to" relationship where clause to the query. + * + * @param \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection<\Illuminate\Database\Eloquent\Model> $related + * @param string|null $relationshipName + * @param string $boolean + * @return \Illuminate\Database\Eloquent\Builder|static + * @throws \Illuminate\Database\Eloquent\RelationNotFoundException + * @static + */ + public static function whereBelongsTo($related, $relationshipName = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->whereBelongsTo($related, $relationshipName, $boolean); + } + + /** + * Add an "BelongsTo" relationship with an "or where" clause to the query. + * + * @param \Illuminate\Database\Eloquent\Model $related + * @param string|null $relationshipName + * @return \Illuminate\Database\Eloquent\Builder|static + * @throws \RuntimeException + * @static + */ + public static function orWhereBelongsTo($related, $relationshipName = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->orWhereBelongsTo($related, $relationshipName); + } + + /** + * Add subselect queries to include an aggregate value for a relationship. + * + * @param mixed $relations + * @param string $column + * @param string $function + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withAggregate($relations, $column, $function = null) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withAggregate($relations, $column, $function); + } + + /** + * Add subselect queries to count the relations. + * + * @param mixed $relations + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withCount($relations) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withCount($relations); + } + + /** + * Add subselect queries to include the max of the relation's column. + * + * @param string|array $relation + * @param string $column + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withMax($relation, $column) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withMax($relation, $column); + } + + /** + * Add subselect queries to include the min of the relation's column. + * + * @param string|array $relation + * @param string $column + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withMin($relation, $column) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withMin($relation, $column); + } + + /** + * Add subselect queries to include the sum of the relation's column. + * + * @param string|array $relation + * @param string $column + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withSum($relation, $column) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withSum($relation, $column); + } + + /** + * Add subselect queries to include the average of the relation's column. + * + * @param string|array $relation + * @param string $column + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withAvg($relation, $column) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withAvg($relation, $column); + } + + /** + * Add subselect queries to include the existence of related models. + * + * @param string|array $relation + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function withExists($relation) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->withExists($relation); + } + + /** + * Merge the where constraints from another query to the current query. + * + * @param \Illuminate\Database\Eloquent\Builder $from + * @return \Illuminate\Database\Eloquent\Builder|static + * @static + */ + public static function mergeConstraintsFrom($from) + { + /** @var \Illuminate\Database\Eloquent\Builder $instance */ + return $instance->mergeConstraintsFrom($from); + } + + /** + * Set the columns to be selected. + * + * @param array|mixed $columns + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function select($columns = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->select($columns); + } + + /** + * Add a subselect expression to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @return \Illuminate\Database\Query\Builder + * @throws \InvalidArgumentException + * @static + */ + public static function selectSub($query, $as) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->selectSub($query, $as); + } + + /** + * Add a new "raw" select expression to the query. + * + * @param string $expression + * @param array $bindings + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function selectRaw($expression, $bindings = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->selectRaw($expression, $bindings); + } + + /** + * Makes "from" fetch from a subquery. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @return \Illuminate\Database\Query\Builder + * @throws \InvalidArgumentException + * @static + */ + public static function fromSub($query, $as) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->fromSub($query, $as); + } + + /** + * Add a raw from clause to the query. + * + * @param string $expression + * @param mixed $bindings + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function fromRaw($expression, $bindings = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->fromRaw($expression, $bindings); + } + + /** + * Add a new select column to the query. + * + * @param array|mixed $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function addSelect($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->addSelect($column); + } + + /** + * Force the query to only return distinct results. + * + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function distinct() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->distinct(); + } + + /** + * Set the table which the query is targeting. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $table + * @param string|null $as + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function from($table, $as = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->from($table, $as); + } + + /** + * Add an index hint to suggest a query index. + * + * @param string $index + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function useIndex($index) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->useIndex($index); + } + + /** + * Add an index hint to force a query index. + * + * @param string $index + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function forceIndex($index) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->forceIndex($index); + } + + /** + * Add an index hint to ignore a query index. + * + * @param string $index + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function ignoreIndex($index) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->ignoreIndex($index); + } + + /** + * Add a join clause to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @param string $type + * @param bool $where + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function join($table, $first, $operator = null, $second = null, $type = 'inner', $where = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->join($table, $first, $operator, $second, $type, $where); + } + + /** + * Add a "join where" clause to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string $operator + * @param string $second + * @param string $type + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function joinWhere($table, $first, $operator, $second, $type = 'inner') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->joinWhere($table, $first, $operator, $second, $type); + } + + /** + * Add a subquery join clause to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @param string $type + * @param bool $where + * @return \Illuminate\Database\Query\Builder + * @throws \InvalidArgumentException + * @static + */ + public static function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->joinSub($query, $as, $first, $operator, $second, $type, $where); + } + + /** + * Add a left join to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function leftJoin($table, $first, $operator = null, $second = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->leftJoin($table, $first, $operator, $second); + } + + /** + * Add a "join where" clause to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string $operator + * @param string $second + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function leftJoinWhere($table, $first, $operator, $second) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->leftJoinWhere($table, $first, $operator, $second); + } + + /** + * Add a subquery left join to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function leftJoinSub($query, $as, $first, $operator = null, $second = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->leftJoinSub($query, $as, $first, $operator, $second); + } + + /** + * Add a right join to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function rightJoin($table, $first, $operator = null, $second = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->rightJoin($table, $first, $operator, $second); + } + + /** + * Add a "right join where" clause to the query. + * + * @param string $table + * @param \Closure|string $first + * @param string $operator + * @param string $second + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function rightJoinWhere($table, $first, $operator, $second) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->rightJoinWhere($table, $first, $operator, $second); + } + + /** + * Add a subquery right join to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @param \Closure|string $first + * @param string|null $operator + * @param string|null $second + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function rightJoinSub($query, $as, $first, $operator = null, $second = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->rightJoinSub($query, $as, $first, $operator, $second); + } + + /** + * Add a "cross join" clause to the query. + * + * @param string $table + * @param \Closure|string|null $first + * @param string|null $operator + * @param string|null $second + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function crossJoin($table, $first = null, $operator = null, $second = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->crossJoin($table, $first, $operator, $second); + } + + /** + * Add a subquery cross join to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @param string $as + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function crossJoinSub($query, $as) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->crossJoinSub($query, $as); + } + + /** + * Merge an array of where clauses and bindings. + * + * @param array $wheres + * @param array $bindings + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function mergeWheres($wheres, $bindings) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->mergeWheres($wheres, $bindings); + } + + /** + * Prepare the value and operator for a where clause. + * + * @param string $value + * @param string $operator + * @param bool $useDefault + * @return array + * @throws \InvalidArgumentException + * @static + */ + public static function prepareValueAndOperator($value, $operator, $useDefault = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->prepareValueAndOperator($value, $operator, $useDefault); + } + + /** + * Add a "where" clause comparing two columns to the query. + * + * @param string|array $first + * @param string|null $operator + * @param string|null $second + * @param string|null $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereColumn($first, $operator = null, $second = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereColumn($first, $operator, $second, $boolean); + } + + /** + * Add an "or where" clause comparing two columns to the query. + * + * @param string|array $first + * @param string|null $operator + * @param string|null $second + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereColumn($first, $operator = null, $second = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereColumn($first, $operator, $second); + } + + /** + * Add a raw where clause to the query. + * + * @param string $sql + * @param mixed $bindings + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereRaw($sql, $bindings = [], $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereRaw($sql, $bindings, $boolean); + } + + /** + * Add a raw or where clause to the query. + * + * @param string $sql + * @param mixed $bindings + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereRaw($sql, $bindings = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereRaw($sql, $bindings); + } + + /** + * Add a "where in" clause to the query. + * + * @param string $column + * @param mixed $values + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereIn($column, $values, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereIn($column, $values, $boolean, $not); + } + + /** + * Add an "or where in" clause to the query. + * + * @param string $column + * @param mixed $values + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereIn($column, $values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereIn($column, $values); + } + + /** + * Add a "where not in" clause to the query. + * + * @param string $column + * @param mixed $values + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereNotIn($column, $values, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereNotIn($column, $values, $boolean); + } + + /** + * Add an "or where not in" clause to the query. + * + * @param string $column + * @param mixed $values + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereNotIn($column, $values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereNotIn($column, $values); + } + + /** + * Add a "where in raw" clause for integer values to the query. + * + * @param string $column + * @param \Illuminate\Contracts\Support\Arrayable|array $values + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereIntegerInRaw($column, $values, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereIntegerInRaw($column, $values, $boolean, $not); + } + + /** + * Add an "or where in raw" clause for integer values to the query. + * + * @param string $column + * @param \Illuminate\Contracts\Support\Arrayable|array $values + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereIntegerInRaw($column, $values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereIntegerInRaw($column, $values); + } + + /** + * Add a "where not in raw" clause for integer values to the query. + * + * @param string $column + * @param \Illuminate\Contracts\Support\Arrayable|array $values + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereIntegerNotInRaw($column, $values, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereIntegerNotInRaw($column, $values, $boolean); + } + + /** + * Add an "or where not in raw" clause for integer values to the query. + * + * @param string $column + * @param \Illuminate\Contracts\Support\Arrayable|array $values + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereIntegerNotInRaw($column, $values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereIntegerNotInRaw($column, $values); + } + + /** + * Add a "where null" clause to the query. + * + * @param string|array $columns + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereNull($columns, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereNull($columns, $boolean, $not); + } + + /** + * Add an "or where null" clause to the query. + * + * @param string|array $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereNull($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereNull($column); + } + + /** + * Add a "where not null" clause to the query. + * + * @param string|array $columns + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereNotNull($columns, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereNotNull($columns, $boolean); + } + + /** + * Add a where between statement to the query. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @param \Illuminate\Database\Query\iterable $values + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereBetween($column, $values, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereBetween($column, $values, $boolean, $not); + } + + /** + * Add a where between statement using columns to the query. + * + * @param string $column + * @param array $values + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereBetweenColumns($column, $values, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereBetweenColumns($column, $values, $boolean, $not); + } + + /** + * Add an or where between statement to the query. + * + * @param string $column + * @param \Illuminate\Database\Query\iterable $values + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereBetween($column, $values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereBetween($column, $values); + } + + /** + * Add an or where between statement using columns to the query. + * + * @param string $column + * @param array $values + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereBetweenColumns($column, $values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereBetweenColumns($column, $values); + } + + /** + * Add a where not between statement to the query. + * + * @param string $column + * @param \Illuminate\Database\Query\iterable $values + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereNotBetween($column, $values, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereNotBetween($column, $values, $boolean); + } + + /** + * Add a where not between statement using columns to the query. + * + * @param string $column + * @param array $values + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereNotBetweenColumns($column, $values, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereNotBetweenColumns($column, $values, $boolean); + } + + /** + * Add an or where not between statement to the query. + * + * @param string $column + * @param \Illuminate\Database\Query\iterable $values + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereNotBetween($column, $values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereNotBetween($column, $values); + } + + /** + * Add an or where not between statement using columns to the query. + * + * @param string $column + * @param array $values + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereNotBetweenColumns($column, $values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereNotBetweenColumns($column, $values); + } + + /** + * Add an "or where not null" clause to the query. + * + * @param string $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereNotNull($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereNotNull($column); + } + + /** + * Add a "where date" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereDate($column, $operator, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereDate($column, $operator, $value, $boolean); + } + + /** + * Add an "or where date" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereDate($column, $operator, $value = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereDate($column, $operator, $value); + } + + /** + * Add a "where time" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereTime($column, $operator, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereTime($column, $operator, $value, $boolean); + } + + /** + * Add an "or where time" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|null $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereTime($column, $operator, $value = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereTime($column, $operator, $value); + } + + /** + * Add a "where day" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|int|null $value + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereDay($column, $operator, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereDay($column, $operator, $value, $boolean); + } + + /** + * Add an "or where day" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|int|null $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereDay($column, $operator, $value = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereDay($column, $operator, $value); + } + + /** + * Add a "where month" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|int|null $value + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereMonth($column, $operator, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereMonth($column, $operator, $value, $boolean); + } + + /** + * Add an "or where month" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|int|null $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereMonth($column, $operator, $value = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereMonth($column, $operator, $value); + } + + /** + * Add a "where year" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|int|null $value + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereYear($column, $operator, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereYear($column, $operator, $value, $boolean); + } + + /** + * Add an "or where year" statement to the query. + * + * @param string $column + * @param string $operator + * @param \DateTimeInterface|string|int|null $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereYear($column, $operator, $value = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereYear($column, $operator, $value); + } + + /** + * Add a nested where statement to the query. + * + * @param \Closure $callback + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereNested($callback, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereNested($callback, $boolean); + } + + /** + * Create a new query instance for nested where condition. + * + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function forNestedWhere() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->forNestedWhere(); + } + + /** + * Add another query builder as a nested where to the query builder. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function addNestedWhereQuery($query, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->addNestedWhereQuery($query, $boolean); + } + + /** + * Add an exists clause to the query. + * + * @param \Closure $callback + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereExists($callback, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereExists($callback, $boolean, $not); + } + + /** + * Add an or exists clause to the query. + * + * @param \Closure $callback + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereExists($callback, $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereExists($callback, $not); + } + + /** + * Add a where not exists clause to the query. + * + * @param \Closure $callback + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereNotExists($callback, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereNotExists($callback, $boolean); + } + + /** + * Add a where not exists clause to the query. + * + * @param \Closure $callback + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereNotExists($callback) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereNotExists($callback); + } + + /** + * Add an exists clause to the query. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function addWhereExistsQuery($query, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->addWhereExistsQuery($query, $boolean, $not); + } + + /** + * Adds a where condition using row values. + * + * @param array $columns + * @param string $operator + * @param array $values + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @throws \InvalidArgumentException + * @static + */ + public static function whereRowValues($columns, $operator, $values, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereRowValues($columns, $operator, $values, $boolean); + } + + /** + * Adds an or where condition using row values. + * + * @param array $columns + * @param string $operator + * @param array $values + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereRowValues($columns, $operator, $values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereRowValues($columns, $operator, $values); + } + + /** + * Add a "where JSON contains" clause to the query. + * + * @param string $column + * @param mixed $value + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereJsonContains($column, $value, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereJsonContains($column, $value, $boolean, $not); + } + + /** + * Add an "or where JSON contains" clause to the query. + * + * @param string $column + * @param mixed $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereJsonContains($column, $value) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereJsonContains($column, $value); + } + + /** + * Add a "where JSON not contains" clause to the query. + * + * @param string $column + * @param mixed $value + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereJsonDoesntContain($column, $value, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereJsonDoesntContain($column, $value, $boolean); + } + + /** + * Add an "or where JSON not contains" clause to the query. + * + * @param string $column + * @param mixed $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereJsonDoesntContain($column, $value) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereJsonDoesntContain($column, $value); + } + + /** + * Add a clause that determines if a JSON path exists to the query. + * + * @param string $column + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereJsonContainsKey($column, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereJsonContainsKey($column, $boolean, $not); + } + + /** + * Add an "or" clause that determines if a JSON path exists to the query. + * + * @param string $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereJsonContainsKey($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereJsonContainsKey($column); + } + + /** + * Add a clause that determines if a JSON path does not exist to the query. + * + * @param string $column + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereJsonDoesntContainKey($column, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereJsonDoesntContainKey($column, $boolean); + } + + /** + * Add an "or" clause that determines if a JSON path does not exist to the query. + * + * @param string $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereJsonDoesntContainKey($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereJsonDoesntContainKey($column); + } + + /** + * Add a "where JSON length" clause to the query. + * + * @param string $column + * @param mixed $operator + * @param mixed $value + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereJsonLength($column, $operator, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereJsonLength($column, $operator, $value, $boolean); + } + + /** + * Add an "or where JSON length" clause to the query. + * + * @param string $column + * @param mixed $operator + * @param mixed $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereJsonLength($column, $operator, $value = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereJsonLength($column, $operator, $value); + } + + /** + * Handles dynamic "where" clauses to the query. + * + * @param string $method + * @param array $parameters + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function dynamicWhere($method, $parameters) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->dynamicWhere($method, $parameters); + } + + /** + * Add a "where fulltext" clause to the query. + * + * @param string|string[] $columns + * @param string $value + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function whereFullText($columns, $value, $options = [], $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->whereFullText($columns, $value, $options, $boolean); + } + + /** + * Add a "or where fulltext" clause to the query. + * + * @param string|string[] $columns + * @param string $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orWhereFullText($columns, $value, $options = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orWhereFullText($columns, $value, $options); + } + + /** + * Add a "group by" clause to the query. + * + * @param array|string $groups + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function groupBy(...$groups) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->groupBy(...$groups); + } + + /** + * Add a raw groupBy clause to the query. + * + * @param string $sql + * @param array $bindings + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function groupByRaw($sql, $bindings = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->groupByRaw($sql, $bindings); + } + + /** + * Add a "having" clause to the query. + * + * @param \Closure|string $column + * @param string|int|float|null $operator + * @param string|int|float|null $value + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function having($column, $operator = null, $value = null, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->having($column, $operator, $value, $boolean); + } + + /** + * Add an "or having" clause to the query. + * + * @param \Closure|string $column + * @param string|int|float|null $operator + * @param string|int|float|null $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orHaving($column, $operator = null, $value = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orHaving($column, $operator, $value); + } + + /** + * Add a nested having statement to the query. + * + * @param \Closure $callback + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function havingNested($callback, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->havingNested($callback, $boolean); + } + + /** + * Add another query builder as a nested having to the query builder. + * + * @param \Illuminate\Database\Query\Builder $query + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function addNestedHavingQuery($query, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->addNestedHavingQuery($query, $boolean); + } + + /** + * Add a "having null" clause to the query. + * + * @param string|array $columns + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function havingNull($columns, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->havingNull($columns, $boolean, $not); + } + + /** + * Add an "or having null" clause to the query. + * + * @param string $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orHavingNull($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orHavingNull($column); + } + + /** + * Add a "having not null" clause to the query. + * + * @param string|array $columns + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function havingNotNull($columns, $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->havingNotNull($columns, $boolean); + } + + /** + * Add an "or having not null" clause to the query. + * + * @param string $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orHavingNotNull($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orHavingNotNull($column); + } + + /** + * Add a "having between " clause to the query. + * + * @param string $column + * @param array $values + * @param string $boolean + * @param bool $not + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function havingBetween($column, $values, $boolean = 'and', $not = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->havingBetween($column, $values, $boolean, $not); + } + + /** + * Add a raw having clause to the query. + * + * @param string $sql + * @param array $bindings + * @param string $boolean + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function havingRaw($sql, $bindings = [], $boolean = 'and') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->havingRaw($sql, $bindings, $boolean); + } + + /** + * Add a raw or having clause to the query. + * + * @param string $sql + * @param array $bindings + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orHavingRaw($sql, $bindings = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orHavingRaw($sql, $bindings); + } + + /** + * Add an "order by" clause to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Expression|string $column + * @param string $direction + * @return \Illuminate\Database\Query\Builder + * @throws \InvalidArgumentException + * @static + */ + public static function orderBy($column, $direction = 'asc') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orderBy($column, $direction); + } + + /** + * Add a descending "order by" clause to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Expression|string $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orderByDesc($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orderByDesc($column); + } + + /** + * Put the query's results in random order. + * + * @param string|int $seed + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function inRandomOrder($seed = '') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->inRandomOrder($seed); + } + + /** + * Add a raw "order by" clause to the query. + * + * @param string $sql + * @param array $bindings + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function orderByRaw($sql, $bindings = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->orderByRaw($sql, $bindings); + } + + /** + * Alias to set the "offset" value of the query. + * + * @param int $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function skip($value) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->skip($value); + } + + /** + * Set the "offset" value of the query. + * + * @param int $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function offset($value) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->offset($value); + } + + /** + * Alias to set the "limit" value of the query. + * + * @param int $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function take($value) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->take($value); + } + + /** + * Set the "limit" value of the query. + * + * @param int $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function limit($value) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->limit($value); + } + + /** + * Set the limit and offset for a given page. + * + * @param int $page + * @param int $perPage + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function forPage($page, $perPage = 15) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->forPage($page, $perPage); + } + + /** + * Constrain the query to the previous "page" of results before a given ID. + * + * @param int $perPage + * @param int|null $lastId + * @param string $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function forPageBeforeId($perPage = 15, $lastId = 0, $column = 'id') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->forPageBeforeId($perPage, $lastId, $column); + } + + /** + * Constrain the query to the next "page" of results after a given ID. + * + * @param int $perPage + * @param int|null $lastId + * @param string $column + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->forPageAfterId($perPage, $lastId, $column); + } + + /** + * Remove all existing orders and optionally add a new order. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Query\Expression|string|null $column + * @param string $direction + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function reorder($column = null, $direction = 'asc') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->reorder($column, $direction); + } + + /** + * Add a union statement to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $query + * @param bool $all + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function union($query, $all = false) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->union($query, $all); + } + + /** + * Add a union all statement to the query. + * + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $query + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function unionAll($query) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->unionAll($query); + } + + /** + * Lock the selected rows in the table. + * + * @param string|bool $value + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function lock($value = true) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->lock($value); + } + + /** + * Lock the selected rows in the table for updating. + * + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function lockForUpdate() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->lockForUpdate(); + } + + /** + * Share lock the selected rows in the table. + * + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function sharedLock() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->sharedLock(); + } + + /** + * Register a closure to be invoked before the query is executed. + * + * @param callable $callback + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function beforeQuery($callback) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->beforeQuery($callback); + } + + /** + * Invoke the "before query" modification callbacks. + * + * @return void + * @static + */ + public static function applyBeforeQueryCallbacks() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + $instance->applyBeforeQueryCallbacks(); + } + + /** + * Get the SQL representation of the query. + * + * @return string + * @static + */ + public static function toSql() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->toSql(); + } + + /** + * Get a single expression value from the first result of a query. + * + * @param string $expression + * @param array $bindings + * @return mixed + * @static + */ + public static function rawValue($expression, $bindings = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->rawValue($expression, $bindings); + } + + /** + * Get the count of the total records for the paginator. + * + * @param array $columns + * @return int + * @static + */ + public static function getCountForPagination($columns = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->getCountForPagination($columns); + } + + /** + * Concatenate values of a given column as a string. + * + * @param string $column + * @param string $glue + * @return string + * @static + */ + public static function implode($column, $glue = '') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->implode($column, $glue); + } + + /** + * Determine if any rows exist for the current query. + * + * @return bool + * @static + */ + public static function exists() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->exists(); + } + + /** + * Determine if no rows exist for the current query. + * + * @return bool + * @static + */ + public static function doesntExist() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->doesntExist(); + } + + /** + * Execute the given callback if no rows exist for the current query. + * + * @param \Closure $callback + * @return mixed + * @static + */ + public static function existsOr($callback) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->existsOr($callback); + } + + /** + * Execute the given callback if rows exist for the current query. + * + * @param \Closure $callback + * @return mixed + * @static + */ + public static function doesntExistOr($callback) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->doesntExistOr($callback); + } + + /** + * Retrieve the "count" result of the query. + * + * @param string $columns + * @return int + * @static + */ + public static function count($columns = '*') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->count($columns); + } + + /** + * Retrieve the minimum value of a given column. + * + * @param string $column + * @return mixed + * @static + */ + public static function min($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->min($column); + } + + /** + * Retrieve the maximum value of a given column. + * + * @param string $column + * @return mixed + * @static + */ + public static function max($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->max($column); + } + + /** + * Retrieve the sum of the values of a given column. + * + * @param string $column + * @return mixed + * @static + */ + public static function sum($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->sum($column); + } + + /** + * Retrieve the average of the values of a given column. + * + * @param string $column + * @return mixed + * @static + */ + public static function avg($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->avg($column); + } + + /** + * Alias for the "avg" method. + * + * @param string $column + * @return mixed + * @static + */ + public static function average($column) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->average($column); + } + + /** + * Execute an aggregate function on the database. + * + * @param string $function + * @param array $columns + * @return mixed + * @static + */ + public static function aggregate($function, $columns = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->aggregate($function, $columns); + } + + /** + * Execute a numeric aggregate function on the database. + * + * @param string $function + * @param array $columns + * @return float|int + * @static + */ + public static function numericAggregate($function, $columns = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->numericAggregate($function, $columns); + } + + /** + * Insert new records into the database. + * + * @param array $values + * @return bool + * @static + */ + public static function insert($values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->insert($values); + } + + /** + * Insert new records into the database while ignoring errors. + * + * @param array $values + * @return int + * @static + */ + public static function insertOrIgnore($values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->insertOrIgnore($values); + } + + /** + * Insert a new record and get the value of the primary key. + * + * @param array $values + * @param string|null $sequence + * @return int + * @static + */ + public static function insertGetId($values, $sequence = null) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->insertGetId($values, $sequence); + } + + /** + * Insert new records into the table using a subquery. + * + * @param array $columns + * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query + * @return int + * @static + */ + public static function insertUsing($columns, $query) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->insertUsing($columns, $query); + } + + /** + * Update records in a PostgreSQL database using the update from syntax. + * + * @param array $values + * @return int + * @static + */ + public static function updateFrom($values) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->updateFrom($values); + } + + /** + * Insert or update a record matching the attributes, and fill it with values. + * + * @param array $attributes + * @param array $values + * @return bool + * @static + */ + public static function updateOrInsert($attributes, $values = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->updateOrInsert($attributes, $values); + } + + /** + * Increment the given column's values by the given amounts. + * + * @param \Illuminate\Database\Query\array $columns + * @param \Illuminate\Database\Query\array $extra + * @return int + * @throws \InvalidArgumentException + * @static + */ + public static function incrementEach($columns, $extra = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->incrementEach($columns, $extra); + } + + /** + * Decrement the given column's values by the given amounts. + * + * @param \Illuminate\Database\Query\array $columns + * @param \Illuminate\Database\Query\array $extra + * @return int + * @throws \InvalidArgumentException + * @static + */ + public static function decrementEach($columns, $extra = []) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->decrementEach($columns, $extra); + } + + /** + * Run a truncate statement on the table. + * + * @return void + * @static + */ + public static function truncate() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + $instance->truncate(); + } + + /** + * Create a raw database expression. + * + * @param mixed $value + * @return \Illuminate\Database\Query\Expression + * @static + */ + public static function raw($value) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->raw($value); + } + + /** + * Get the current query value bindings in a flattened array. + * + * @return array + * @static + */ + public static function getBindings() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->getBindings(); + } + + /** + * Get the raw array of bindings. + * + * @return array + * @static + */ + public static function getRawBindings() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->getRawBindings(); + } + + /** + * Set the bindings on the query builder. + * + * @param array $bindings + * @param string $type + * @return \Illuminate\Database\Query\Builder + * @throws \InvalidArgumentException + * @static + */ + public static function setBindings($bindings, $type = 'where') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->setBindings($bindings, $type); + } + + /** + * Add a binding to the query. + * + * @param mixed $value + * @param string $type + * @return \Illuminate\Database\Query\Builder + * @throws \InvalidArgumentException + * @static + */ + public static function addBinding($value, $type = 'where') + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->addBinding($value, $type); + } + + /** + * Cast the given binding value. + * + * @param mixed $value + * @return mixed + * @static + */ + public static function castBinding($value) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->castBinding($value); + } + + /** + * Merge an array of bindings into our bindings. + * + * @param \Illuminate\Database\Query\Builder $query + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function mergeBindings($query) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->mergeBindings($query); + } + + /** + * Remove all of the expressions from a list of bindings. + * + * @param array $bindings + * @return array + * @static + */ + public static function cleanBindings($bindings) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->cleanBindings($bindings); + } + + /** + * Get the database query processor instance. + * + * @return \Illuminate\Database\Query\Processors\Processor + * @static + */ + public static function getProcessor() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->getProcessor(); + } + + /** + * Get the query grammar instance. + * + * @return \Illuminate\Database\Query\Grammars\Grammar + * @static + */ + public static function getGrammar() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->getGrammar(); + } + + /** + * Use the "write" PDO connection when executing the query. + * + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function useWritePdo() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->useWritePdo(); + } + + /** + * Clone the query without the given properties. + * + * @param array $properties + * @return static + * @static + */ + public static function cloneWithout($properties) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->cloneWithout($properties); + } + + /** + * Clone the query without the given bindings. + * + * @param array $except + * @return static + * @static + */ + public static function cloneWithoutBindings($except) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->cloneWithoutBindings($except); + } + + /** + * Dump the current SQL and bindings. + * + * @return \Illuminate\Database\Query\Builder + * @static + */ + public static function dump() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->dump(); + } + + /** + * Die and dump the current SQL and bindings. + * + * @return \Illuminate\Database\Query\never + * @static + */ + public static function dd() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->dd(); + } + + /** + * Explains the query. + * + * @return \Illuminate\Support\Collection + * @static + */ + public static function explain() + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->explain(); + } + + /** + * Register a custom macro. + * + * @param string $name + * @param object|callable $macro + * @return void + * @static + */ + public static function macro($name, $macro) + { + \Illuminate\Database\Query\Builder::macro($name, $macro); + } + + /** + * Mix another object into the class. + * + * @param object $mixin + * @param bool $replace + * @return void + * @throws \ReflectionException + * @static + */ + public static function mixin($mixin, $replace = true) + { + \Illuminate\Database\Query\Builder::mixin($mixin, $replace); + } + + /** + * Flush the existing macros. + * + * @return void + * @static + */ + public static function flushMacros() + { + \Illuminate\Database\Query\Builder::flushMacros(); + } + + /** + * Dynamically handle calls to the class. + * + * @param string $method + * @param array $parameters + * @return mixed + * @throws \BadMethodCallException + * @static + */ + public static function macroCall($method, $parameters) + { + /** @var \Illuminate\Database\Query\Builder $instance */ + return $instance->macroCall($method, $parameters); + } + } + class Event extends \Illuminate\Support\Facades\Event {} + class File extends \Illuminate\Support\Facades\File {} + class Gate extends \Illuminate\Support\Facades\Gate {} + class Hash extends \Illuminate\Support\Facades\Hash {} + class Http extends \Illuminate\Support\Facades\Http {} + class Js extends \Illuminate\Support\Js {} + class Lang extends \Illuminate\Support\Facades\Lang {} + class Log extends \Illuminate\Support\Facades\Log {} + class Mail extends \Illuminate\Support\Facades\Mail {} + class Notification extends \Illuminate\Support\Facades\Notification {} + class Password extends \Illuminate\Support\Facades\Password {} + class Queue extends \Illuminate\Support\Facades\Queue {} + class RateLimiter extends \Illuminate\Support\Facades\RateLimiter {} + class Redirect extends \Illuminate\Support\Facades\Redirect {} + class Request extends \Illuminate\Support\Facades\Request {} + class Response extends \Illuminate\Support\Facades\Response {} + class Route extends \Illuminate\Support\Facades\Route {} + class Schema extends \Illuminate\Support\Facades\Schema {} + class Session extends \Illuminate\Support\Facades\Session {} + class Storage extends \Illuminate\Support\Facades\Storage {} + class Str extends \Illuminate\Support\Str {} + class URL extends \Illuminate\Support\Facades\URL {} + class Validator extends \Illuminate\Support\Facades\Validator {} + class View extends \Illuminate\Support\Facades\View {} + class Vite extends \Illuminate\Support\Facades\Vite {} + class Countries extends \Webpatser\Countries\CountriesFacade {} + class CustomMessage extends \App\Utils\ClientPortal\CustomMessage\CustomMessageFacade {} + class Redis extends \Illuminate\Support\Facades\Redis {} + class Debugbar extends \Barryvdh\Debugbar\Facades\Debugbar {} + class L5Swagger extends \L5Swagger\L5SwaggerFacade {} + class Product extends \Imdhemy\Purchases\Facades\Product {} + class Subscription extends \Imdhemy\Purchases\Facades\Subscription {} + class Image extends \Intervention\Image\Facades\Image {} + class Inspector extends \InvoiceNinja\Inspector\InspectorFacade {} + class Socialite extends \Laravel\Socialite\Facades\Socialite {} + class Livewire extends \Livewire\Livewire {} + class Module extends \Nwidart\Modules\Facades\Module {} + class Sentry extends \Sentry\Laravel\Facade {} + class Flare extends \Spatie\LaravelIgnition\Facades\Flare {} + class Beacon extends \Turbo124\Beacon\CollectorFacade {} + +} + + + + diff --git a/_ide_helper_custom.php b/_ide_helper_custom.php new file mode 100644 index 000000000000..57714df9b396 --- /dev/null +++ b/_ide_helper_custom.php @@ -0,0 +1,17 @@ +createSymfonyTransport([ 'transport' => 'mailgun', 'secret' => $secret, diff --git a/app/Services/Email/MailEntity.php b/app/Services/Email/MailEntity.php index 14e6b2a7b392..6116a884b2a0 100644 --- a/app/Services/Email/MailEntity.php +++ b/app/Services/Email/MailEntity.php @@ -93,15 +93,28 @@ class MailEntity implements ShouldQueue /* Try sending email */ $this->setMailDriver() + ->configureMailer() ->trySending(); } - + + /** + * configureMailer + * + * @return self + */ public function configureMailer(): self { - $this->setMailDriver(); - + $this->mail = Mail::mailer($this->mailer); + if ($this->client_postmark_secret) { + $this->mail->postmark_config($this->client_postmark_secret); + } + + if ($this->client_mailgun_secret) { + $this->mail->mailgun_config($this->client_mailgun_secret, $this->client_mailgun_domain); + } + return $this; } diff --git a/composer.json b/composer.json index afac04841082..c2804a1c4105 100644 --- a/composer.json +++ b/composer.json @@ -96,6 +96,7 @@ "require-dev": { "php": "^8.1", "barryvdh/laravel-debugbar": "^3.6", + "barryvdh/laravel-ide-helper": "^2.13", "beyondcode/laravel-query-detector": "^1.6", "brianium/paratest": "^6.1", "darkaonline/l5-swagger": "8.1.0", diff --git a/composer.lock b/composer.lock index 084682de16b5..a784b71becd7 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "ef4a5ce05df08ab130a9906db0e69ead", + "content-hash": "55a62c4290c3a07d0c38c8e4aeea61e0", "packages": [ { "name": "afosto/yaac", @@ -12923,6 +12923,152 @@ ], "time": "2023-02-04T15:47:28+00:00" }, + { + "name": "barryvdh/laravel-ide-helper", + "version": "v2.13.0", + "source": { + "type": "git", + "url": "https://github.com/barryvdh/laravel-ide-helper.git", + "reference": "81d5b223ff067a1f38e14c100997e153b837fe4a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/barryvdh/laravel-ide-helper/zipball/81d5b223ff067a1f38e14c100997e153b837fe4a", + "reference": "81d5b223ff067a1f38e14c100997e153b837fe4a", + "shasum": "" + }, + "require": { + "barryvdh/reflection-docblock": "^2.0.6", + "composer/class-map-generator": "^1.0", + "doctrine/dbal": "^2.6 || ^3", + "ext-json": "*", + "illuminate/console": "^8 || ^9 || ^10", + "illuminate/filesystem": "^8 || ^9 || ^10", + "illuminate/support": "^8 || ^9 || ^10", + "nikic/php-parser": "^4.7", + "php": "^7.3 || ^8.0", + "phpdocumentor/type-resolver": "^1.1.0" + }, + "require-dev": { + "ext-pdo_sqlite": "*", + "friendsofphp/php-cs-fixer": "^2", + "illuminate/config": "^8 || ^9 || ^10", + "illuminate/view": "^8 || ^9 || ^10", + "mockery/mockery": "^1.4", + "orchestra/testbench": "^6 || ^7 || ^8", + "phpunit/phpunit": "^8.5 || ^9", + "spatie/phpunit-snapshot-assertions": "^3 || ^4", + "vimeo/psalm": "^3.12" + }, + "suggest": { + "illuminate/events": "Required for automatic helper generation (^6|^7|^8|^9|^10)." + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.12-dev" + }, + "laravel": { + "providers": [ + "Barryvdh\\LaravelIdeHelper\\IdeHelperServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "Barryvdh\\LaravelIdeHelper\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Barry vd. Heuvel", + "email": "barryvdh@gmail.com" + } + ], + "description": "Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.", + "keywords": [ + "autocomplete", + "codeintel", + "helper", + "ide", + "laravel", + "netbeans", + "phpdoc", + "phpstorm", + "sublime" + ], + "support": { + "issues": "https://github.com/barryvdh/laravel-ide-helper/issues", + "source": "https://github.com/barryvdh/laravel-ide-helper/tree/v2.13.0" + }, + "funding": [ + { + "url": "https://fruitcake.nl", + "type": "custom" + }, + { + "url": "https://github.com/barryvdh", + "type": "github" + } + ], + "time": "2023-02-04T13:56:40+00:00" + }, + { + "name": "barryvdh/reflection-docblock", + "version": "v2.1.0", + "source": { + "type": "git", + "url": "https://github.com/barryvdh/ReflectionDocBlock.git", + "reference": "bf44b757feb8ba1734659029357646466ded673e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/barryvdh/ReflectionDocBlock/zipball/bf44b757feb8ba1734659029357646466ded673e", + "reference": "bf44b757feb8ba1734659029357646466ded673e", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "^8.5.14|^9" + }, + "suggest": { + "dflydev/markdown": "~1.0", + "erusev/parsedown": "~1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "Barryvdh": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "mike.vanriel@naenius.com" + } + ], + "support": { + "source": "https://github.com/barryvdh/ReflectionDocBlock/tree/v2.1.0" + }, + "time": "2022-10-31T15:35:43+00:00" + }, { "name": "beyondcode/laravel-query-detector", "version": "1.6.0", @@ -13075,6 +13221,79 @@ ], "time": "2023-02-07T10:03:32+00:00" }, + { + "name": "composer/class-map-generator", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/composer/class-map-generator.git", + "reference": "1e1cb2b791facb2dfe32932a7718cf2571187513" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/class-map-generator/zipball/1e1cb2b791facb2dfe32932a7718cf2571187513", + "reference": "1e1cb2b791facb2dfe32932a7718cf2571187513", + "shasum": "" + }, + "require": { + "composer/pcre": "^2 || ^3", + "php": "^7.2 || ^8.0", + "symfony/finder": "^4.4 || ^5.3 || ^6" + }, + "require-dev": { + "phpstan/phpstan": "^1.6", + "phpstan/phpstan-deprecation-rules": "^1", + "phpstan/phpstan-phpunit": "^1", + "phpstan/phpstan-strict-rules": "^1.1", + "symfony/filesystem": "^5.4 || ^6", + "symfony/phpunit-bridge": "^5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\ClassMapGenerator\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "https://seld.be" + } + ], + "description": "Utilities to scan PHP code and generate class maps.", + "keywords": [ + "classmap" + ], + "support": { + "issues": "https://github.com/composer/class-map-generator/issues", + "source": "https://github.com/composer/class-map-generator/tree/1.0.0" + }, + "funding": [ + { + "url": "https://packagist.com", + "type": "custom" + }, + { + "url": "https://github.com/composer", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/composer/composer", + "type": "tidelift" + } + ], + "time": "2022-06-19T11:31:27+00:00" + }, { "name": "composer/package-versions-deprecated", "version": "1.11.99.5", From 7b51db035f1e7a4a1b30b7137f865f2afa4c4a2b Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 16:00:16 +1100 Subject: [PATCH 39/72] Minor updates for mailer --- app/Services/Email/MailEntity.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/Services/Email/MailEntity.php b/app/Services/Email/MailEntity.php index 6116a884b2a0..a8946e2bc7be 100644 --- a/app/Services/Email/MailEntity.php +++ b/app/Services/Email/MailEntity.php @@ -20,6 +20,7 @@ use App\Utils\Ninja; use App\Utils\Traits\MakesHash; use GuzzleHttp\Exception\ClientException; use Illuminate\Bus\Queueable; +use Illuminate\Contracts\Mail\Mailer; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Mail\Mailable; @@ -37,7 +38,7 @@ class MailEntity implements ShouldQueue public Mailable $mailable; - public Mail $mail; + public Mailer $mail; public ?string $client_postmark_secret = null; @@ -207,8 +208,8 @@ class MailEntity implements ShouldQueue public function trySending(): void { try { - $mail = Mail::mailer($this->mailer); - $mail->send($this->mailable); + + $this->mail->send($this->mailable); /* Count the amount of emails sent across all the users accounts */ Cache::increment($this->company->account->key); From a9ef8d292540c6803ae6ec8fc62102d3fa0d0c8b Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 20:05:46 +1100 Subject: [PATCH 40/72] Minor fixes for designs --- app/Mail/Engine/PaymentEmailEngine.php | 16 ++++++++++++++++ app/Utils/HtmlEngine.php | 24 ++++++++++++++++++++++++ app/Utils/VendorHtmlEngine.php | 16 ++++++++++++++++ 3 files changed, 56 insertions(+) diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php index b32cfb4efe65..0a78f8b4caf9 100644 --- a/app/Mail/Engine/PaymentEmailEngine.php +++ b/app/Mail/Engine/PaymentEmailEngine.php @@ -388,6 +388,22 @@ class PaymentEmailEngine extends BaseEmailEngine */ private function buildViewButton(string $link, string $text): string { + + return ' + + + + + + +
+ + '. $text .' + +
+ + '; + return ' diff --git a/app/Utils/HtmlEngine.php b/app/Utils/HtmlEngine.php index f528512f21ab..dacb2972383f 100644 --- a/app/Utils/HtmlEngine.php +++ b/app/Utils/HtmlEngine.php @@ -978,6 +978,30 @@ html { */ private function buildViewButton(string $link, string $text): string { + return ' + +
+ + + + +
+ + '. $text .' + +
+ + '; + + return ' diff --git a/app/Utils/VendorHtmlEngine.php b/app/Utils/VendorHtmlEngine.php index b8d28390cdac..b40944ba8c0b 100644 --- a/app/Utils/VendorHtmlEngine.php +++ b/app/Utils/VendorHtmlEngine.php @@ -807,6 +807,22 @@ html { */ private function buildViewButton(string $link, string $text): string { + return ' + +
+ + + + +
+ + '. $text .' + +
+ + '; + + return ' From c1763be6abcc62a4440c9b025e8d7b0fce82cc13 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 21:09:50 +1100 Subject: [PATCH 41/72] Fixes for designs --- app/Mail/Engine/PaymentEmailEngine.php | 33 ++-- app/Utils/HtmlEngine.php | 6 +- app/Utils/VendorHtmlEngine.php | 33 ++-- resources/views/email/admin/generic.blade.php | 25 ++- .../views/email/template/admin.blade.php | 143 ++++++++---------- .../views/email/template/client.blade.php | 59 ++++---- .../views/email/template/master.blade.php | 19 +-- 7 files changed, 158 insertions(+), 160 deletions(-) diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php index 0a78f8b4caf9..cae4251c57b7 100644 --- a/app/Mail/Engine/PaymentEmailEngine.php +++ b/app/Mail/Engine/PaymentEmailEngine.php @@ -390,19 +390,28 @@ class PaymentEmailEngine extends BaseEmailEngine { return ' - -
- - - - -
- - '. $text .' - -
- + + + + + + +
+ + '. $text .' + +
+ '; + return ' diff --git a/app/Utils/HtmlEngine.php b/app/Utils/HtmlEngine.php index dacb2972383f..e4ea76dcc968 100644 --- a/app/Utils/HtmlEngine.php +++ b/app/Utils/HtmlEngine.php @@ -984,10 +984,10 @@ html {
- +
- diff --git a/app/Utils/VendorHtmlEngine.php b/app/Utils/VendorHtmlEngine.php index b40944ba8c0b..95112fc6bda1 100644 --- a/app/Utils/VendorHtmlEngine.php +++ b/app/Utils/VendorHtmlEngine.php @@ -808,21 +808,30 @@ html { private function buildViewButton(string $link, string $text): string { return ' - -
- + + '. $text .'
- - - - -
- - '. $text .' - -
- + + + + + + +
+ + '. $text .' + +
+ '; + return ' diff --git a/resources/views/email/admin/generic.blade.php b/resources/views/email/admin/generic.blade.php index 2f18f3d4b6c3..ece82a8c9057 100644 --- a/resources/views/email/admin/generic.blade.php +++ b/resources/views/email/admin/generic.blade.php @@ -27,17 +27,28 @@ @endisset @isset($url) - - -
- -
- - {{ ctrans($button) }} + + + + + + +
+ + {{ ctrans($button) }} +
+ + @endisset diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index 34f9de1e7858..814b1cbd67fa 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -1,5 +1,6 @@ @php $primary_color = isset($settings) ? $settings->primary_color : '#4caf50'; + $email_alignment = isset($settings) ? $settings->email_alignment : 'center'; @endphp email_style === 'dark') body, [data-ogsc] { background-color: #1a1a1a !important; color: #ffffff !important; } - div, tr, td, [data-ogsc] div, [data-ogsc] tr, [data-ogsc] td { border-color: #222222 !important; } - h1, h2, h3, p, td, [data-ogsc] h1, [data-ogsc] h2, [data-ogsc] h3, [data-ogsc] p, [data-ogsc] td, { color: #ffffff !important; } - p, [data-ogsc] p { color: #bbbbbc !important; } - .dark-bg-base, [data-ogsc] .dark-bg-base { background-color: #222222 !important; } - .dark-bg, [data-ogsc] .dark-bg { background-color: #3a3a3c !important; } - .logo-dark, [data-ogsc] .logo-dark { display: block !important; } - .logo-light, [data-ogsc] .logo-light { display: none !important; } - .btn-white, [data-ogsc] .btn-white { - background-color: #fefefe !important; + background-color: #000 !important; mso-padding-alt: 40px; mso-border-alt: 40px solid #fefefe; mso-padding-alt: 0; @@ -77,17 +69,6 @@ mso-border-right-alt: 20 #fefefe 0; } @endif - - .btn-white { - mso-padding-alt: 40px; - mso-border-alt: 40px solid #fefefe; - mso-padding-alt: 0; - mso-ansi-font-size:20px !important; - mso-line-height-alt:150%; - mso-border-left-alt: 20 #FFFFFF 0; - mso-border-right-alt: 20 #FFFFFF 0; - } - /** Content-specific styles. **/ #content .button { display: inline-block; @@ -101,7 +82,6 @@ font-weight: 600; margin-bottom: 30px; } - #content h1 { font-family: 'canada-type-gibson', 'roboto', Arial, Helvetica, sans-serif; font-weight: 600; @@ -109,16 +89,13 @@ margin-top: 5px; margin-bottom: 30px; } - #content > p { font-size: 16px; color: red; } - #content .center { text-align: center; } - .stamp { transform: rotate(12deg); color: #555; @@ -135,7 +112,6 @@ position: fixed; text-align: center; } - .is-paid { color: #D23; border: 1rem double #D23; @@ -149,14 +125,10 @@ position: fixed; } - .new_button, a { + .new_button a { background-color: {{ $primary_color }}; } - a:visited { - color:#ffffff !important; - } - @@ -165,18 +137,35 @@
- +
- + + @@ -189,76 +178,78 @@ -
-
- alt_text +
+ +
+
+
+ + + + + +
+ style="padding: 20px; text-align: {{ $email_alignment }}"> {{ $slot }}
+ style="background-color: {{ $primary_color }};" width="100%"> +

Questions? We're here to help!

-
+ + + Support Docs + -
+ style="background-color: #242424;">

© {{ date('Y') }} Invoice Ninja, All Rights Reserved @@ -272,4 +263,4 @@

- + \ No newline at end of file diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index d5b3871ad519..f50d6327e54c 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -82,7 +82,6 @@ #content .left { text-align: left !important; } - .stamp { transform: rotate(12deg); color: #555; @@ -96,7 +95,6 @@ z-index:200 !important; position: relative; } - .is-paid { color: #D23; border: 1rem double #D23; @@ -109,20 +107,15 @@ z-index:200 !important; position: relative; } - a.doc_links { text-decoration: none; padding-bottom: 10px; display: inline-block; color: inherit !important; } - - .new_button, a { - background-color: {{ $primary_color }} !important; - } - - a:visited { - color:#ffffff !important; + + .new_button a { + background-color: {{ $primary_color }}; } @@ -139,38 +132,46 @@ - +
- +
- + + - - - From e479275335f5d2a79cbb0709b6e89a805ee6b576 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 21:23:36 +1100 Subject: [PATCH 43/72] Fixes for admin template --- resources/views/email/template/admin.blade.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index 307f440a2a84..34ac8cabc82c 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -149,7 +149,7 @@
- alt_text + alt_text
From fa43f86e561df409abc9e2e8bbd81b06b9425219 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 21:25:14 +1100 Subject: [PATCH 44/72] Fixes for admin template --- resources/views/email/template/admin.blade.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index 34ac8cabc82c..c27f40a80949 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -149,7 +149,7 @@
- alt_text + alt_text
From ea0abcc37e74111a674d373f40e2a941aad7db76 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 21:32:09 +1100 Subject: [PATCH 45/72] Fixes for admin template --- resources/views/email/template/admin.blade.php | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index c27f40a80949..10d7d2abdc8a 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -139,15 +139,18 @@
-
- alt_text +
+
+
+ + + +
-
+
+
+
{{ $slot ?? '' }} {!! $body ?? '' !!}
@isset($links) - - @if(count($links) >=1) -

{{ ctrans('texts.attachments') }}

- @endif - @foreach($links as $link) {!! $link ?? '' !!}
@endforeach @@ -182,20 +183,14 @@
-
+
+ style="text-align: center; padding-top: 10px; padding-bottom: 25px; background-color: #f9f9f9; border: 1px solid #c2c2c2; border-top: none; border-bottom-color: #f9f9f9;"> @isset($signature)

{!! nl2br($signature) !!} @@ -217,7 +212,7 @@

+ style="padding-top: 10px;padding-bottom: 10px; background-color: #242424; border: 1px solid #c2c2c2; border-top-color: #242424; border-bottom-color: #242424;"> @if(isset($company)) @if($company->account->isPaid())

- - - - + alt_text

- -
- -
+ + + +
+ style="background-color:#f9f9f9; padding-bottom: 20px; margin-top:20px;"> alt_text From 1b82c0b5e42d32a39d0c7caf9298aae4d587bec5 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 21:34:36 +1100 Subject: [PATCH 46/72] Fixes for admin template --- resources/views/email/template/admin.blade.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index 10d7d2abdc8a..715d6927702e 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -141,7 +141,7 @@ style="border: 1px solid #c2c2c2; background-color:#f9f9f9"> From 7d4e2d9e415a9c9a3c0e5da981d461314c6e80dc Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 21:41:16 +1100 Subject: [PATCH 47/72] Fixes for admin template --- resources/views/email/template/admin.blade.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index 715d6927702e..2c06655828d4 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -137,11 +137,11 @@
- From 7fb82536e8946bc7e64afbbab9f47e6a80b97df4 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Thu, 16 Feb 2023 21:44:41 +1100 Subject: [PATCH 48/72] Fixes for admin template --- resources/views/email/template/client.blade.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index f50d6327e54c..05ee427e1a7f 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -137,9 +137,13 @@
- -
+ + + diff --git a/resources/views/email/template/client.blade.php b/resources/views/email/template/client.blade.php index 05ee427e1a7f..f67b976b5b58 100644 --- a/resources/views/email/template/client.blade.php +++ b/resources/views/email/template/client.blade.php @@ -148,14 +148,7 @@ From 2e6a47c3888936f409e1fab3e25c5636b94eae61 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 08:41:07 +1100 Subject: [PATCH 52/72] Point releases to v5-develop --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5bf89ecafa62..6b5489f6e390 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,7 @@ jobs: - name: Checkout code uses: actions/checkout@v1 with: - ref: v5-stable + ref: v5-develop - name: Copy .env file run: | From bc065e21322a12e4b1416e7b8461047197d08d8a Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 08:59:19 +1100 Subject: [PATCH 53/72] Update scheduler date ranges --- app/DataMapper/Schedule/ClientStatement.php | 18 +++--- app/Services/Scheduler/SchedulerService.php | 26 ++++---- tests/Feature/Scheduler/SchedulerTest.php | 69 +++++++++++---------- 3 files changed, 63 insertions(+), 50 deletions(-) diff --git a/app/DataMapper/Schedule/ClientStatement.php b/app/DataMapper/Schedule/ClientStatement.php index a51cc15154fd..f6fd6e4ff734 100644 --- a/app/DataMapper/Schedule/ClientStatement.php +++ b/app/DataMapper/Schedule/ClientStatement.php @@ -32,13 +32,17 @@ class ClientStatement /** * The consts to be used to define the date_range variable of the statement */ - public const THIS_MONTH = 'this_month'; - public const THIS_QUARTER = 'this_quarter'; - public const THIS_YEAR = 'this_year'; - public const PREVIOUS_MONTH = 'previous_month'; - public const PREVIOUS_QUARTER = 'previous_quarter'; - public const PREVIOUS_YEAR = 'previous_year'; - public const CUSTOM_RANGE = "custom_range"; + public const LAST7 = "last7_days"; + public const LAST30 = "last30_days"; + public const LAST365 = "last365_days"; + public const THIS_MONTH = "this_month"; + public const LAST_MONTH = "last_month"; + public const THIS_QUARTER = "this_quarter"; + public const LAST_QUARTER = "last_quarter"; + public const THIS_YEAR = "this_year"; + public const LAST_YEAR = "last_year"; + public const CUSTOM_RANGE = "custom"; + /** * The date range the statement should include diff --git a/app/Services/Scheduler/SchedulerService.php b/app/Services/Scheduler/SchedulerService.php index 854ff8efce4c..23275c303e2c 100644 --- a/app/Services/Scheduler/SchedulerService.php +++ b/app/Services/Scheduler/SchedulerService.php @@ -12,10 +12,12 @@ namespace App\Services\Scheduler; use App\Models\Client; -use App\Models\RecurringInvoice; use App\Models\Scheduler; -use App\Utils\Traits\MakesDates; use App\Utils\Traits\MakesHash; +use App\Models\RecurringInvoice; +use App\Utils\Traits\MakesDates; +use App\DataMapper\Schedule\ClientStatement; +use Symfony\Component\HttpClient\Internal\ClientState; class SchedulerService { @@ -82,7 +84,7 @@ class SchedulerService 'status' => $this->scheduler->parameters['status'] ]; } - + /** * Start and end date of the statement * @@ -91,18 +93,20 @@ class SchedulerService private function calculateStartAndEndDates(): array { return match ($this->scheduler->parameters['date_range']) { - 'this_month' => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], - 'this_quarter' => [now()->startOfDay()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->lastOfQuarter()->format('Y-m-d')], - 'this_year' => [now()->startOfDay()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->lastOfYear()->format('Y-m-d')], - 'previous_month' => [now()->startOfDay()->subMonthNoOverflow()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->subMonthNoOverflow()->lastOfMonth()->format('Y-m-d')], - 'previous_quarter' => [now()->startOfDay()->subQuarterNoOverflow()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->subQuarterNoOverflow()->lastOfQuarter()->format('Y-m-d')], - 'previous_year' => [now()->startOfDay()->subYearNoOverflow()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->subYearNoOverflow()->lastOfYear()->format('Y-m-d')], - 'custom_range' => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']], + ClientStatement::LAST7 => [now()->startOfDay()->subDays(7)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + ClientStatement::LAST30 => [now()->startOfDay()->subDays(30)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + ClientStatement::LAST365 => [now()->startOfDay()->subDays(365)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + ClientStatement::THIS_MONTH => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], + ClientStatement::LAST_MONTH => [now()->startOfDay()->subMonthNoOverflow()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->subMonthNoOverflow()->lastOfMonth()->format('Y-m-d')], + ClientStatement::THIS_QUARTER => [now()->startOfDay()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->lastOfQuarter()->format('Y-m-d')], + ClientStatement::LAST_QUARTER => [now()->startOfDay()->subQuarterNoOverflow()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->subQuarterNoOverflow()->lastOfQuarter()->format('Y-m-d')], + ClientStatement::THIS_YEAR => [now()->startOfDay()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->lastOfYear()->format('Y-m-d')], + ClientStatement::LAST_YEAR => [now()->startOfDay()->subYearNoOverflow()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->subYearNoOverflow()->lastOfYear()->format('Y-m-d')], + ClientStatement::CUSTOM_RANGE => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']], default => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], }; } - /** * Sets the next run date of the scheduled task * diff --git a/tests/Feature/Scheduler/SchedulerTest.php b/tests/Feature/Scheduler/SchedulerTest.php index d2ec6eee0931..6fba294959f6 100644 --- a/tests/Feature/Scheduler/SchedulerTest.php +++ b/tests/Feature/Scheduler/SchedulerTest.php @@ -11,20 +11,21 @@ namespace Tests\Feature\Scheduler; -use App\Factory\SchedulerFactory; -use App\Models\Client; -use App\Models\RecurringInvoice; -use App\Models\Scheduler; -use App\Services\Scheduler\SchedulerService; -use App\Utils\Traits\MakesHash; use Carbon\Carbon; +use Tests\TestCase; +use App\Models\Client; +use App\Models\Scheduler; +use Tests\MockAccountData; +use App\Utils\Traits\MakesHash; +use App\Models\RecurringInvoice; +use App\Factory\SchedulerFactory; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Session; +use App\DataMapper\Schedule\ClientStatement; +use App\Services\Scheduler\SchedulerService; +use Illuminate\Validation\ValidationException; use Illuminate\Foundation\Testing\WithoutEvents; use Illuminate\Routing\Middleware\ThrottleRequests; -use Illuminate\Support\Facades\Session; -use Illuminate\Validation\ValidationException; -use Tests\MockAccountData; -use Tests\TestCase; /** * @test @@ -75,7 +76,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => 'previous_month', + 'date_range' => ClientStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -138,7 +139,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => 'previous_month', + 'date_range' => ClientStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -170,7 +171,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->addDay()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => 'previous_month', + 'date_range' => ClientStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -194,7 +195,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => 'previous_month', + 'date_range' => ClientStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -223,7 +224,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => 'previous_month', + 'date_range' => ClientStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -258,7 +259,7 @@ class SchedulerTest extends TestCase 'next_run' => "2023-01-01", 'template' => 'client_statement', 'parameters' => [ - 'date_range' => 'previous_month', + 'date_range' => ClientStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -277,7 +278,7 @@ class SchedulerTest extends TestCase $this->assertIsArray($method); - $this->assertEquals('previous_month', $scheduler->parameters['date_range']); + $this->assertEquals(ClientStatement::LAST_MONTH, $scheduler->parameters['date_range']); $this->assertEqualsCanonicalizing(['2022-12-01','2022-12-31'], $method); } @@ -292,7 +293,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => 'previous_month', + 'date_range' => ClientStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -323,13 +324,13 @@ class SchedulerTest extends TestCase { $this->travelTo(Carbon::parse('2023-01-14')); - $this->assertEqualsCanonicalizing(['2023-01-01','2023-01-31'], $this->getDateRange('this_month')); - $this->assertEqualsCanonicalizing(['2023-01-01','2023-03-31'], $this->getDateRange('this_quarter')); - $this->assertEqualsCanonicalizing(['2023-01-01','2023-12-31'], $this->getDateRange('this_year')); + $this->assertEqualsCanonicalizing(['2023-01-01','2023-01-31'], $this->getDateRange(ClientStatement::THIS_MONTH)); + $this->assertEqualsCanonicalizing(['2023-01-01','2023-03-31'], $this->getDateRange(ClientStatement::THIS_QUARTER)); + $this->assertEqualsCanonicalizing(['2023-01-01','2023-12-31'], $this->getDateRange(ClientStatement::THIS_YEAR)); - $this->assertEqualsCanonicalizing(['2022-12-01','2022-12-31'], $this->getDateRange('previous_month')); - $this->assertEqualsCanonicalizing(['2022-10-01','2022-12-31'], $this->getDateRange('previous_quarter')); - $this->assertEqualsCanonicalizing(['2022-01-01','2022-12-31'], $this->getDateRange('previous_year')); + $this->assertEqualsCanonicalizing(['2022-12-01','2022-12-31'], $this->getDateRange(ClientStatement::LAST_MONTH)); + $this->assertEqualsCanonicalizing(['2022-10-01','2022-12-31'], $this->getDateRange(ClientStatement::LAST_QUARTER)); + $this->assertEqualsCanonicalizing(['2022-01-01','2022-12-31'], $this->getDateRange(ClientStatement::LAST_YEAR)); $this->travelBack(); } @@ -337,13 +338,17 @@ class SchedulerTest extends TestCase private function getDateRange($range) { return match ($range) { - 'this_month' => [now()->firstOfMonth()->format('Y-m-d'), now()->lastOfMonth()->format('Y-m-d')], - 'this_quarter' => [now()->firstOfQuarter()->format('Y-m-d'), now()->lastOfQuarter()->format('Y-m-d')], - 'this_year' => [now()->firstOfYear()->format('Y-m-d'), now()->lastOfYear()->format('Y-m-d')], - 'previous_month' => [now()->subMonth()->firstOfMonth()->format('Y-m-d'), now()->subMonth()->lastOfMonth()->format('Y-m-d')], - 'previous_quarter' => [now()->subQuarter()->firstOfQuarter()->format('Y-m-d'), now()->subQuarter()->lastOfQuarter()->format('Y-m-d')], - 'previous_year' => [now()->subYear()->firstOfYear()->format('Y-m-d'), now()->subYear()->lastOfYear()->format('Y-m-d')], - 'custom_range' => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']] + ClientStatement::LAST7 => [now()->startOfDay()->subDays(7)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + ClientStatement::LAST30 => [now()->startOfDay()->subDays(30)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + ClientStatement::LAST365 => [now()->startOfDay()->subDays(365)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + ClientStatement::THIS_MONTH => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], + ClientStatement::LAST_MONTH => [now()->startOfDay()->subMonthNoOverflow()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->subMonthNoOverflow()->lastOfMonth()->format('Y-m-d')], + ClientStatement::THIS_QUARTER => [now()->startOfDay()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->lastOfQuarter()->format('Y-m-d')], + ClientStatement::LAST_QUARTER => [now()->startOfDay()->subQuarterNoOverflow()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->subQuarterNoOverflow()->lastOfQuarter()->format('Y-m-d')], + ClientStatement::THIS_YEAR => [now()->startOfDay()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->lastOfYear()->format('Y-m-d')], + ClientStatement::LAST_YEAR => [now()->startOfDay()->subYearNoOverflow()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->subYearNoOverflow()->lastOfYear()->format('Y-m-d')], + ClientStatement::CUSTOM_RANGE => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']], + default => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], }; } @@ -355,7 +360,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => 'previous_month', + 'date_range' => ClientStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', From 88d5d14de3f4c70239daa05d475b9527f2fde5ba Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 09:34:50 +1100 Subject: [PATCH 54/72] Minor fixes for admin email templates --- app/DataMapper/CompanySettings.php | 3 + app/Models/Scheduler.php | 58 ++++++------------- .../MailCssInlinerServiceProvider.php | 6 +- ...act_settings_column_company_user_table.php | 9 ++- .../email/admin/download_credits.blade.php | 27 +++++---- .../email/admin/download_documents.blade.php | 28 +++++---- .../email/admin/download_files.blade.php | 23 ++++++-- .../email/admin/download_invoices.blade.php | 28 +++++---- .../admin/download_purchase_orders.blade.php | 28 +++++---- .../email/admin/download_quotes.blade.php | 27 +++++---- .../email/admin/download_report.blade.php | 2 +- .../views/email/admin/generic_email.blade.php | 25 ++++++-- tests/Feature/TaskApiTest.php | 10 ++++ 13 files changed, 162 insertions(+), 112 deletions(-) diff --git a/app/DataMapper/CompanySettings.php b/app/DataMapper/CompanySettings.php index fc3630d6646a..4219b6863c0d 100644 --- a/app/DataMapper/CompanySettings.php +++ b/app/DataMapper/CompanySettings.php @@ -463,7 +463,10 @@ class CompanySettings extends BaseSettings public $accept_client_input_quote_approval = false; + public $allow_billable_task_items = false; + public static $casts = [ + 'allow_billable_task_items' => 'bool', 'accept_client_input_quote_approval' => 'bool', 'custom_sending_email' => 'string', 'show_paid_stamp' => 'bool', diff --git a/app/Models/Scheduler.php b/app/Models/Scheduler.php index 569958ff6166..cc0f61a7c2f0 100644 --- a/app/Models/Scheduler.php +++ b/app/Models/Scheduler.php @@ -42,6 +42,7 @@ class Scheduler extends BaseModel 'template', 'is_paused', 'parameters', + 'remaining_cycles', ]; protected $casts = [ @@ -71,44 +72,21 @@ class Scheduler extends BaseModel { return $this->belongsTo(Company::class); } - - // public function nextScheduledDate(): ?Carbon - // { - // $offset = 0; - - // $entity_send_time = $this->company->settings->entity_send_time; - - // if ($entity_send_time != 0) { - // $timezone = $this->company->timezone(); - - // $offset -= $timezone->utc_offset; - // $offset += ($entity_send_time * 3600); - // } - - // /* - // As we are firing at UTC+0 if our offset is negative it is technically firing the day before so we always need - // to add ON a day - a day = 86400 seconds - // */ - - // if ($offset < 0) { - // $offset += 86400; - // } - - // switch ($this->repeat_every) { - // case self::DAILY: - // return Carbon::parse($this->scheduled_run)->startOfDay()->addDay()->addSeconds($offset); - // case self::WEEKLY: - // return Carbon::parse($this->scheduled_run)->startOfDay()->addWeek()->addSeconds($offset); - // case self::BIWEEKLY: - // return Carbon::parse($this->scheduled_run)->startOfDay()->addWeeks(2)->addSeconds($offset); - // case self::MONTHLY: - // return Carbon::parse($this->scheduled_run)->startOfDay()->addMonthNoOverflow()->addSeconds($offset); - // case self::QUARTERLY: - // return Carbon::parse($this->scheduled_run)->startOfDay()->addMonthsNoOverflow(3)->addSeconds($offset); - // case self::ANNUALLY: - // return Carbon::parse($this->scheduled_run)->startOfDay()->addYearNoOverflow()->addSeconds($offset); - // default: - // return null; - // } - // } + + /** + * remainingCycles + * + * @return int + */ + public function remainingCycles() : int + { + if ($this->remaining_cycles == 0) { + return 0; + } elseif ($this->remaining_cycles == -1) { + return -1; + } else { + return $this->remaining_cycles - 1; + } + } + } diff --git a/app/Providers/MailCssInlinerServiceProvider.php b/app/Providers/MailCssInlinerServiceProvider.php index c1c5984c1c93..e47be7180aee 100644 --- a/app/Providers/MailCssInlinerServiceProvider.php +++ b/app/Providers/MailCssInlinerServiceProvider.php @@ -45,8 +45,8 @@ class MailCssInlinerServiceProvider extends ServiceProvider // return new CssInlinerPlugin([]); // }); - $this->app->bind(CssInlinerPlugin::class, function ($app) { - return new CssInlinerPlugin([]); - }); + // $this->app->bind(CssInlinerPlugin::class, function ($app) { + // return new CssInlinerPlugin([]); + // }); } } diff --git a/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php b/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php index a763630ffbf8..aa6eb0e6db18 100644 --- a/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php +++ b/database/migrations/2023_02_14_064135_create_react_settings_column_company_user_table.php @@ -1,7 +1,6 @@ mediumText('react_settings')->nullable(); + }); - \Illuminate\Support\Facades\Artisan::call('ninja:design-update'); + \Illuminate\Support\Facades\Artisan::call('ninja:design-update'); + + Schema::table('schedulers', function (Illuminate\Database\Schema\Blueprint $table) { + $table->integer('remaining_cycles')->nullable(); }); } diff --git a/resources/views/email/admin/download_credits.blade.php b/resources/views/email/admin/download_credits.blade.php index c9c9e4abb608..a715ab6df337 100644 --- a/resources/views/email/admin/download_credits.blade.php +++ b/resources/views/email/admin/download_credits.blade.php @@ -3,19 +3,26 @@

{{ ctrans('texts.credits_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

- - -
From e5017299c608e85158f169043c62a4048647bfd4 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 07:18:59 +1100 Subject: [PATCH 49/72] Add buildCache to clientcontact --- app/Models/ClientContact.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/Models/ClientContact.php b/app/Models/ClientContact.php index 9c91224b4825..a4f6320f4856 100644 --- a/app/Models/ClientContact.php +++ b/app/Models/ClientContact.php @@ -17,6 +17,7 @@ use App\Jobs\Mail\NinjaMailerObject; use App\Mail\ClientContact\ClientContactResetPasswordObject; use App\Models\Presenters\ClientContactPresenter; use App\Utils\Ninja; +use App\Utils\Traits\AppSetup; use App\Utils\Traits\MakesHash; use Illuminate\Contracts\Translation\HasLocalePreference; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -39,7 +40,8 @@ class ClientContact extends Authenticatable implements HasLocalePreference use PresentableTrait; use SoftDeletes; use HasFactory; - + use AppSetup; + /* Used to authenticate a contact */ protected $guard = 'contact'; From 995cf73bde7ab233290fdbbd068c5d5d742194ea Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 07:21:00 +1100 Subject: [PATCH 50/72] Remove mail css inliner --- config/app.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/app.php b/config/app.php index 40e80de7fa27..87b04d3f4f45 100644 --- a/config/app.php +++ b/config/app.php @@ -201,7 +201,7 @@ return [ App\Providers\MultiDBProvider::class, App\Providers\ClientPortalServiceProvider::class, App\Providers\NinjaTranslationServiceProvider::class, - App\Providers\MailCssInlinerServiceProvider::class, + // App\Providers\MailCssInlinerServiceProvider::class, ], /* From d0dc0df77b0353e8366e6523756cf38d01db31fd Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 08:34:19 +1100 Subject: [PATCH 51/72] Remove logo from CSV importer --- app/Mail/Import/CsvImportCompleted.php | 2 -- resources/views/email/import/csv_completed.blade.php | 2 -- resources/views/email/template/admin.blade.php | 2 +- resources/views/email/template/client.blade.php | 9 +-------- 4 files changed, 2 insertions(+), 13 deletions(-) diff --git a/app/Mail/Import/CsvImportCompleted.php b/app/Mail/Import/CsvImportCompleted.php index ac00b1a31c9e..78cb33d1a19d 100644 --- a/app/Mail/Import/CsvImportCompleted.php +++ b/app/Mail/Import/CsvImportCompleted.php @@ -14,9 +14,7 @@ namespace App\Mail\Import; use App\Models\Company; use App\Utils\Ninja; -use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; -use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\App; class CsvImportCompleted extends Mailable diff --git a/resources/views/email/import/csv_completed.blade.php b/resources/views/email/import/csv_completed.blade.php index c61f56d2cde8..9b915a9e6129 100644 --- a/resources/views/email/import/csv_completed.blade.php +++ b/resources/views/email/import/csv_completed.blade.php @@ -2,8 +2,6 @@

{{ ctrans('texts.import_complete') }}

-

- @if($client_count)

{{ ctrans('texts.clients') }}: {{ $client_count }}

@endif diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index 2c06655828d4..c1398cabcf6e 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -152,7 +152,7 @@
- alt_text + alt_text
- - - + alt_text
- -
- - {{ ctrans('texts.download') }} - + + + + + + +
+ + {{ ctrans('texts.download') }} +
+ @endcomponent diff --git a/resources/views/email/admin/download_documents.blade.php b/resources/views/email/admin/download_documents.blade.php index 3c8da4cb4434..f3fc42cc9dd0 100644 --- a/resources/views/email/admin/download_documents.blade.php +++ b/resources/views/email/admin/download_documents.blade.php @@ -3,19 +3,25 @@

{{ ctrans('texts.document_download_subject') }}

{{ ctrans('texts.download_timeframe') }}

- - - - - -
- - {{ ctrans('texts.download') }} - + + + + + + +
+ + {{ ctrans('texts.download') }} +
+ @endcomponent diff --git a/resources/views/email/admin/download_files.blade.php b/resources/views/email/admin/download_files.blade.php index 035c303e0608..08e0e6359b68 100644 --- a/resources/views/email/admin/download_files.blade.php +++ b/resources/views/email/admin/download_files.blade.php @@ -3,15 +3,26 @@

{{ ctrans('texts.download_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

- - -
- - {{ ctrans('texts.download') }} - + + + + + + +
+ + {{ ctrans('texts.download') }} +
+ @endcomponent diff --git a/resources/views/email/admin/download_invoices.blade.php b/resources/views/email/admin/download_invoices.blade.php index 600f04a4346a..dbae16a9f4bc 100644 --- a/resources/views/email/admin/download_invoices.blade.php +++ b/resources/views/email/admin/download_invoices.blade.php @@ -3,19 +3,25 @@

{{ ctrans('texts.invoices_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

- - - - - -
- - {{ ctrans('texts.download') }} - + + + + + + +
+ + {{ ctrans('texts.download') }} +
+ @endcomponent diff --git a/resources/views/email/admin/download_purchase_orders.blade.php b/resources/views/email/admin/download_purchase_orders.blade.php index e8d1d089efef..114ddf666d83 100644 --- a/resources/views/email/admin/download_purchase_orders.blade.php +++ b/resources/views/email/admin/download_purchase_orders.blade.php @@ -3,19 +3,25 @@

{{ ctrans('texts.purchase_orders_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

- - - - - -
- - {{ ctrans('texts.download') }} - + + + + + + +
+ + {{ ctrans('texts.download') }} +
+ @endcomponent diff --git a/resources/views/email/admin/download_quotes.blade.php b/resources/views/email/admin/download_quotes.blade.php index c54446e42487..3517e4ddbade 100644 --- a/resources/views/email/admin/download_quotes.blade.php +++ b/resources/views/email/admin/download_quotes.blade.php @@ -2,20 +2,27 @@

{{ ctrans('texts.quotes_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

- - - - - +
- - {{ ctrans('texts.download') }} + + + + + + +
+ + {{ ctrans('texts.download') }} +
+ @endcomponent diff --git a/resources/views/email/admin/download_report.blade.php b/resources/views/email/admin/download_report.blade.php index 132d2ff6507a..93e7e88d52a4 100644 --- a/resources/views/email/admin/download_report.blade.php +++ b/resources/views/email/admin/download_report.blade.php @@ -1,6 +1,6 @@ @component('email.template.admin', ['logo' => $logo, 'settings' => $settings])
-

{{ ctrans('texts.download_files') }}

+

{{ ctrans('texts.reports') }}

{{ ctrans('texts.download_report_description') }}

@endcomponent diff --git a/resources/views/email/admin/generic_email.blade.php b/resources/views/email/admin/generic_email.blade.php index be32dcf1aa21..7b0d776f8777 100644 --- a/resources/views/email/admin/generic_email.blade.php +++ b/resources/views/email/admin/generic_email.blade.php @@ -6,13 +6,26 @@ @isset($view_link) - - - + +
- {{ $view_text }} -
+ + -
+ + {{ $view_text }} + +
+
+ @endisset diff --git a/tests/Feature/TaskApiTest.php b/tests/Feature/TaskApiTest.php index 24a5de247f58..ae396b069577 100644 --- a/tests/Feature/TaskApiTest.php +++ b/tests/Feature/TaskApiTest.php @@ -220,6 +220,16 @@ class TaskApiTest extends TestCase } + public function testTimeLogChecker12() + { + $log = [ + [1,2,'a',true], + [3,4,'d',false], + ]; + + $this->assertTrue($this->checkTimeLog($log)); + } + public function testTaskListClientStatus() { $response = $this->withHeaders([ From f38c3f93c69f6e15fa15cb3dbc7292d9586740ed Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 09:54:26 +1100 Subject: [PATCH 55/72] Fixes for admin email tempaltes --- app/Jobs/Company/CompanyExport.php | 1 - resources/views/email/admin/download_credits.blade.php | 2 +- resources/views/email/admin/download_documents.blade.php | 2 +- resources/views/email/admin/download_files.blade.php | 5 +++-- resources/views/email/admin/download_invoices.blade.php | 2 +- .../views/email/admin/download_purchase_orders.blade.php | 2 +- resources/views/email/admin/download_quotes.blade.php | 2 +- resources/views/email/admin/generic_email.blade.php | 2 +- resources/views/email/template/admin.blade.php | 4 ++-- 9 files changed, 11 insertions(+), 11 deletions(-) diff --git a/app/Jobs/Company/CompanyExport.php b/app/Jobs/Company/CompanyExport.php index 574a6b3257de..1eef769f893f 100644 --- a/app/Jobs/Company/CompanyExport.php +++ b/app/Jobs/Company/CompanyExport.php @@ -471,7 +471,6 @@ class CompanyExport implements ShouldQueue $t->replace(Ninja::transformTranslations($this->company->settings)); $company_reference = Company::find($this->company->id); - ; $nmo = new NinjaMailerObject; $nmo->mailable = new DownloadBackup($storage_file_path, $company_reference); diff --git a/resources/views/email/admin/download_credits.blade.php b/resources/views/email/admin/download_credits.blade.php index a715ab6df337..e5432328fb93 100644 --- a/resources/views/email/admin/download_credits.blade.php +++ b/resources/views/email/admin/download_credits.blade.php @@ -11,7 +11,7 @@ diff --git a/resources/views/email/admin/download_documents.blade.php b/resources/views/email/admin/download_documents.blade.php index f3fc42cc9dd0..3fcb530eae41 100644 --- a/resources/views/email/admin/download_documents.blade.php +++ b/resources/views/email/admin/download_documents.blade.php @@ -11,7 +11,7 @@
- + {{ ctrans('texts.download') }}
diff --git a/resources/views/email/admin/download_files.blade.php b/resources/views/email/admin/download_files.blade.php index 08e0e6359b68..e0c385825ab4 100644 --- a/resources/views/email/admin/download_files.blade.php +++ b/resources/views/email/admin/download_files.blade.php @@ -1,4 +1,5 @@ @component('email.template.admin', ['logo' => $logo, 'settings' => $settings]) +

{{ ctrans('texts.download_backup_subject') }}

{{ ctrans('texts.download_timeframe') }}

@@ -10,8 +11,8 @@
- + {{ ctrans('texts.download') }}
- diff --git a/resources/views/email/admin/download_invoices.blade.php b/resources/views/email/admin/download_invoices.blade.php index dbae16a9f4bc..5e0d2a139905 100644 --- a/resources/views/email/admin/download_invoices.blade.php +++ b/resources/views/email/admin/download_invoices.blade.php @@ -11,7 +11,7 @@
- + + {{ ctrans('texts.download') }}
diff --git a/resources/views/email/admin/download_purchase_orders.blade.php b/resources/views/email/admin/download_purchase_orders.blade.php index 114ddf666d83..772f02e49806 100644 --- a/resources/views/email/admin/download_purchase_orders.blade.php +++ b/resources/views/email/admin/download_purchase_orders.blade.php @@ -11,7 +11,7 @@
- + {{ ctrans('texts.download') }}
diff --git a/resources/views/email/admin/download_quotes.blade.php b/resources/views/email/admin/download_quotes.blade.php index 3517e4ddbade..8b1acb586e1a 100644 --- a/resources/views/email/admin/download_quotes.blade.php +++ b/resources/views/email/admin/download_quotes.blade.php @@ -11,7 +11,7 @@
- + {{ ctrans('texts.download') }}
diff --git a/resources/views/email/admin/generic_email.blade.php b/resources/views/email/admin/generic_email.blade.php index 7b0d776f8777..f55411056e41 100644 --- a/resources/views/email/admin/generic_email.blade.php +++ b/resources/views/email/admin/generic_email.blade.php @@ -14,7 +14,7 @@
- + {{ ctrans('texts.download') }}
diff --git a/resources/views/email/template/admin.blade.php b/resources/views/email/template/admin.blade.php index c1398cabcf6e..fb5372cf00fb 100644 --- a/resources/views/email/template/admin.blade.php +++ b/resources/views/email/template/admin.blade.php @@ -151,9 +151,9 @@ From 94670413ab20245c882eae2d6e4c85f204434308 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 09:58:49 +1100 Subject: [PATCH 56/72] Minor fix for bulk purchase order download file naming --- app/Jobs/PurchaseOrder/ZipPurchaseOrders.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php b/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php index 07d37172b28d..8d9a14a76026 100644 --- a/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php +++ b/app/Jobs/PurchaseOrder/ZipPurchaseOrders.php @@ -72,7 +72,7 @@ class ZipPurchaseOrders implements ShouldQueue // create new zip object $zipFile = new \PhpZip\ZipFile(); - $file_name = date('Y-m-d').'_'.str_replace(' ', '_', trans('texts.invoices')).'.zip'; + $file_name = date('Y-m-d').'_'.str_replace(' ', '_', trans('texts.purchase_orders')).'.zip'; $invitation = $this->purchase_orders->first()->invitations->first(); $path = $this->purchase_orders->first()->vendor->purchase_order_filepath($invitation); From 75335ba8e42d0361312f6f02dec7313f52fd8d50 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 10:17:05 +1100 Subject: [PATCH 57/72] Ensure when merging, we purge empty contacts --- app/Services/Client/Merge.php | 2 +- tests/Feature/ClientTest.php | 56 +++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/app/Services/Client/Merge.php b/app/Services/Client/Merge.php index eeef8e5632e5..a2f830a1bb8a 100644 --- a/app/Services/Client/Merge.php +++ b/app/Services/Client/Merge.php @@ -53,7 +53,7 @@ class Merge extends AbstractService /* Loop through contacts an only merge distinct contacts by email */ $this->mergable_client->contacts->each(function ($contact) { $exist = $this->client->contacts->contains(function ($client_contact) use ($contact) { - return $client_contact->email == $contact->email; + return $client_contact->email == $contact->email || empty($contact->email) || $contact->email == ' '; }); if ($exist) { diff --git a/tests/Feature/ClientTest.php b/tests/Feature/ClientTest.php index 17927bb747fb..83c84201617a 100644 --- a/tests/Feature/ClientTest.php +++ b/tests/Feature/ClientTest.php @@ -63,6 +63,62 @@ class ClientTest extends TestCase $this->makeTestData(); } + + public function testClientMergeContactDrop() + { + + $c = Client::factory()->create(['user_id' => $this->user->id, 'company_id' => $this->company->id]); + + ClientContact::factory()->create([ + 'user_id' => $this->user->id, + 'client_id' => $c->id, + 'company_id' => $this->company->id, + 'is_primary' => 1, + ]); + + ClientContact::factory()->create([ + 'user_id' => $this->user->id, + 'client_id' => $c->id, + 'company_id' => $this->company->id, + ]); + + + $c1 = Client::factory()->create(['user_id' => $this->user->id, 'company_id' => $this->company->id]); + + ClientContact::factory()->create([ + 'user_id' => $this->user->id, + 'client_id' => $c1->id, + 'company_id' => $this->company->id, + 'is_primary' => 1, + ]); + + ClientContact::factory()->create([ + 'user_id' => $this->user->id, + 'client_id' => $c1->id, + 'company_id' => $this->company->id, + ]); + + ClientContact::factory()->create([ + 'user_id' => $this->user->id, + 'client_id' => $c1->id, + 'company_id' => $this->company->id, + 'email' => '' + ]); + + + $this->assertEquals(2, $c->contacts->count()); + $this->assertEquals(3, $c1->contacts->count()); + + $c->service()->merge($c1); + + $c = $c->fresh(); + + nlog($c->contacts->pluck('email')); + + $this->assertEquals(4, $c->contacts->count()); + + } + private function buildLineItems($number = 2) { $line_items = []; From 7f1a98484820707fa16a2ad692c22fe3ebf9e1b3 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 13:51:24 +1100 Subject: [PATCH 58/72] Remove unnessary touching of file --- app/Listeners/Invoice/InvoicePaidActivity.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/Listeners/Invoice/InvoicePaidActivity.php b/app/Listeners/Invoice/InvoicePaidActivity.php index 998783e4c200..e33c837bce10 100644 --- a/app/Listeners/Invoice/InvoicePaidActivity.php +++ b/app/Listeners/Invoice/InvoicePaidActivity.php @@ -57,10 +57,10 @@ class InvoicePaidActivity implements ShouldQueue $event->invoice->subscription->service()->planPaid($event->invoice); } - try { - $event->invoice->service()->touchPdf(); - } catch (\Exception $e) { - nlog(print_r($e->getMessage(), 1)); - } + // try { + // $event->invoice->service()->touchPdf(); + // } catch (\Exception $e) { + // nlog(print_r($e->getMessage(), 1)); + // } } } From 8ae40d70975a01778a9096f212b0aad27bf57ec2 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 14:47:52 +1100 Subject: [PATCH 59/72] Refactors for webhooks --- app/Events/Invoice/InvoiceWasPaid.php | 1 + app/Jobs/Util/WebhookSingle.php | 42 +++++++++++++++----------- app/Providers/EventServiceProvider.php | 2 -- 3 files changed, 25 insertions(+), 20 deletions(-) diff --git a/app/Events/Invoice/InvoiceWasPaid.php b/app/Events/Invoice/InvoiceWasPaid.php index dffe4343d2c2..af1ff64011fa 100644 --- a/app/Events/Invoice/InvoiceWasPaid.php +++ b/app/Events/Invoice/InvoiceWasPaid.php @@ -48,4 +48,5 @@ class InvoiceWasPaid $this->company = $company; $this->event_vars = $event_vars; } + } diff --git a/app/Jobs/Util/WebhookSingle.php b/app/Jobs/Util/WebhookSingle.php index b780fcd523aa..23749f84c64e 100644 --- a/app/Jobs/Util/WebhookSingle.php +++ b/app/Jobs/Util/WebhookSingle.php @@ -46,6 +46,7 @@ class WebhookSingle implements ShouldQueue private string $includes; private Company $company; + /** * Create a new job instance. * @@ -121,41 +122,47 @@ class WebhookSingle implements ShouldQueue RequestOptions::JSON => $data, // or 'json' => [...] ]); - SystemLogger::dispatch( + (new SystemLogger( array_merge((array) $response, $data), SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_SUCCESS, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company - ); + ))->handle(); } catch(\GuzzleHttp\Exception\ConnectException $e) { nlog("connection problem"); nlog($e->getCode()); nlog($e->getMessage()); - SystemLogger::dispatch( + (new SystemLogger( ['message' => "Error connecting to ". $subscription->target_url], SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_FAILURE, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company - ); + ))->handle(); } catch (BadResponseException $e) { if ($e->getResponse()->getStatusCode() >= 400 && $e->getResponse()->getStatusCode() < 500) { - $message = "Server encountered a problem when connecting to {$subscription->target_url} => status code ". $e->getResponse()->getStatusCode(). " scheduling retry."; + $message = "There was a problem when connecting to {$subscription->target_url} => status code ". $e->getResponse()->getStatusCode(); nlog($message); - SystemLogger::dispatch( + (new SystemLogger( ['message' => $message], SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_FAILURE, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company - ); + ))->handle(); + + /* Some 400's should never be repeated */ + if(in_array($e->getResponse()->getStatusCode(), [404, 410])){ + $this->fail(); + return; + } $this->release($this->backoff()[$this->attempts()-1]); } @@ -163,16 +170,16 @@ class WebhookSingle implements ShouldQueue if ($e->getResponse()->getStatusCode() >= 500) { nlog("endpoint returned a 500, failing"); - $message = "Server encountered a problem when connecting to {$subscription->target_url} => status code ". $e->getResponse()->getStatusCode(). " no retry attempted."; + $message = "The was a problem when connecting to {$subscription->target_url} => status code ". $e->getResponse()->getStatusCode(). " no retry attempted."; - SystemLogger::dispatch( + (new SystemLogger( ['message' => $message], SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_FAILURE, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company - ); + ))->handle(); $this->fail(); return; @@ -181,38 +188,38 @@ class WebhookSingle implements ShouldQueue nlog("Server exception"); $error = json_decode($e->getResponse()->getBody()->getContents()); - SystemLogger::dispatch( + (new SystemLogger( ['message' => $error], SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_FAILURE, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company - ); + ))->handle(); } catch (ClientException $e) { nlog("Client exception"); $error = json_decode($e->getResponse()->getBody()->getContents()); - SystemLogger::dispatch( + (new SystemLogger( ['message' => $error], SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_FAILURE, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company - ); + ))->handle(); } catch (\Exception $e) { nlog("Exception handler => " . $e->getMessage()); nlog($e->getCode()); - SystemLogger::dispatch( + (new SystemLogger( $e->getMessage(), SystemLog::CATEGORY_WEBHOOK, SystemLog::EVENT_WEBHOOK_FAILURE, SystemLog::TYPE_WEBHOOK_RESPONSE, $this->resolveClient(), $this->company, - ); + ))->handle(); $this->release($this->backoff()[$this->attempts()-1]); } @@ -220,7 +227,6 @@ class WebhookSingle implements ShouldQueue private function resolveClient() { - nlog(get_class($this->entity)); //make sure it isn't an instance of the Client Model if (!$this->entity instanceof \App\Models\Client && @@ -230,9 +236,9 @@ class WebhookSingle implements ShouldQueue $this->entity->client()->exists()) { return $this->entity->client; } - return null; + } public function failed($exception = null) diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index 1b7d2ba1a4d4..b0949dc593df 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -416,7 +416,6 @@ class EventServiceProvider extends ServiceProvider ], InvoiceWasPaid::class => [ InvoicePaidActivity::class, - CreateInvoicePdf::class, ], InvoiceWasViewed::class => [ InvoiceViewedActivity::class, @@ -434,7 +433,6 @@ class EventServiceProvider extends ServiceProvider ], InvoiceWasDeleted::class => [ InvoiceDeletedActivity::class, - CreateInvoicePdf::class, ], InvoiceWasArchived::class => [ InvoiceArchivedActivity::class, From 08fff15f8ed73359622cc14b746b9f00d63f0745 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 15:10:38 +1100 Subject: [PATCH 60/72] Run GH actions on stable branch --- .github/workflows/phpunit.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/phpunit.yml b/.github/workflows/phpunit.yml index 1847b94d1404..c47bc0f88be3 100644 --- a/.github/workflows/phpunit.yml +++ b/.github/workflows/phpunit.yml @@ -2,6 +2,7 @@ on: push: branches: - v5-develop + - v5-stable pull_request: branches: - v5-develop From 93a9e207eea652e9f052b951b224accb2daa3e8c Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 15:25:18 +1100 Subject: [PATCH 61/72] minor fixes for play store --- config/purchase.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/purchase.php b/config/purchase.php index b461c41559c8..e3e4f2fb08b8 100644 --- a/config/purchase.php +++ b/config/purchase.php @@ -29,7 +29,7 @@ use Imdhemy\Purchases\Events\GooglePlay\SubscriptionRevoked; return [ 'routing' => [], - 'google_play_package_name' => env('GOOGLE_PLAY_PACKAGE_NAME', 'com.example.name'), + 'google_play_package_name' => env('GOOGLE_PLAY_PACKAGE_NAME', 'com.invoiceninja.app'), 'appstore_password' => env('APPSTORE_PASSWORD', ''), From d4943703c89d3438faa370b9fe0ddf7bfe8a85e3 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 15:46:07 +1100 Subject: [PATCH 62/72] Move google play listener in place --- .../AppStoreRenewSubscription.php | 3 -- .../PlayStoreRenewSubscription.php | 49 +++++++++++++++++++ .../Ninja/RenewalFailureNotification.php | 2 +- config/purchase.php | 37 +++++++------- 4 files changed, 69 insertions(+), 22 deletions(-) create mode 100644 app/Listeners/Subscription/PlayStoreRenewSubscription.php diff --git a/app/Listeners/Subscription/AppStoreRenewSubscription.php b/app/Listeners/Subscription/AppStoreRenewSubscription.php index 26c2b41df179..8b6ee587dae0 100644 --- a/app/Listeners/Subscription/AppStoreRenewSubscription.php +++ b/app/Listeners/Subscription/AppStoreRenewSubscription.php @@ -59,8 +59,5 @@ class AppStoreRenewSubscription implements ShouldQueue $account->save(); - // $server_notification = $event->getServerNotification(); - // $subscription = $event->getSubscription(); - // $subscription_identifier = $event->getSubscriptionIdentifier(); } } diff --git a/app/Listeners/Subscription/PlayStoreRenewSubscription.php b/app/Listeners/Subscription/PlayStoreRenewSubscription.php new file mode 100644 index 000000000000..75a1561c9151 --- /dev/null +++ b/app/Listeners/Subscription/PlayStoreRenewSubscription.php @@ -0,0 +1,49 @@ +getServerNotification(); + nlog("google"); + nlog($notification); + $in_app_identifier = $event->getSubscriptionIdentifier(); + + MultiDB::findAndSetDbByInappTransactionId($in_app_identifier); + + $expirationTime = $event->getSubscription()->getExpiryTime(); + + $account = Account::where('inapp_transaction_id', $in_app_identifier)->first(); + + if ($account) { + $account->update(['plan_expires' => Carbon::parse($expirationTime)]); + } + + if (!$account) { + $ninja_company = Company::on('db-ninja-01')->find(config('ninja.ninja_default_company_id')); + $ninja_company->notification(new RenewalFailureNotification("{$in_app_identifier}"))->ninja(); + return; + } + } + + +} diff --git a/app/Notifications/Ninja/RenewalFailureNotification.php b/app/Notifications/Ninja/RenewalFailureNotification.php index 1ed7b15aed1f..34a5942feb25 100644 --- a/app/Notifications/Ninja/RenewalFailureNotification.php +++ b/app/Notifications/Ninja/RenewalFailureNotification.php @@ -23,7 +23,7 @@ class RenewalFailureNotification extends Notification * @return void */ - public function __construct(protected string $notification_message) + public function __construct(protected ?string $notification_message) { } diff --git a/config/purchase.php b/config/purchase.php index e3e4f2fb08b8..4b735d6457ef 100644 --- a/config/purchase.php +++ b/config/purchase.php @@ -1,30 +1,31 @@ [], @@ -40,7 +41,7 @@ return [ * -------------------------------------------------------- */ SubscriptionPurchased::class => [], - SubscriptionRenewed::class => [], + SubscriptionRenewed::class => [PlayStoreRenewSubscription::class], SubscriptionInGracePeriod::class => [], SubscriptionExpired::class => [], SubscriptionCanceled::class => [], From 2f3cee2fc27d784fc463c8f675fd02e43d280be3 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 16:02:46 +1100 Subject: [PATCH 63/72] Update naming of email statement scheduler --- app/DataMapper/Schedule/ClientStatement.php | 2 +- app/Services/Scheduler/SchedulerService.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/DataMapper/Schedule/ClientStatement.php b/app/DataMapper/Schedule/ClientStatement.php index f6fd6e4ff734..ea97f8b636a1 100644 --- a/app/DataMapper/Schedule/ClientStatement.php +++ b/app/DataMapper/Schedule/ClientStatement.php @@ -18,7 +18,7 @@ class ClientStatement * * @var string */ - public string $template = 'client_statement'; + public string $template = 'email_statement'; /** * An array of clients hashed_ids diff --git a/app/Services/Scheduler/SchedulerService.php b/app/Services/Scheduler/SchedulerService.php index 23275c303e2c..72113dd32d02 100644 --- a/app/Services/Scheduler/SchedulerService.php +++ b/app/Services/Scheduler/SchedulerService.php @@ -42,7 +42,7 @@ class SchedulerService $this->{$this->scheduler->template}(); } - private function client_statement() + private function email_statement() { $query = Client::query() ->where('company_id', $this->scheduler->company_id) From 681fc47a68d67c467d75a428d99fd9a5c5b3c9fb Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 17:19:33 +1100 Subject: [PATCH 64/72] Fixes for displaying negative currencies --- app/Utils/Number.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/app/Utils/Number.php b/app/Utils/Number.php index 4d23798394c6..f19aefc690f1 100644 --- a/app/Utils/Number.php +++ b/app/Utils/Number.php @@ -137,6 +137,8 @@ class Number { $value = floatval($value); + $_value = $value; + $currency = $entity->currency(); $thousand = $currency->thousand_separator; @@ -177,6 +179,15 @@ class Number } elseif ($swapSymbol) { return "{$value} ".trim($symbol); } elseif ($entity->getSetting('show_currency_code') === false) { + + /* Ensures we place the negative symbol ahead of the currency symbol*/ + if($_value < 0){ + + $value = substr($value, 1); + $symbol = "-{$symbol}"; + + } + return "{$symbol}{$value}"; } else { return self::formatValue($value, $currency); From 1de91c9e3357f4c847b47dcb6abbad43bc084f58 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 19:58:30 +1100 Subject: [PATCH 65/72] Reducing the quantity of jobs dispatched --- VERSION.txt | 2 +- app/Jobs/Entity/CreateEntityPdf.php | 4 --- app/Jobs/Ledger/ClientLedgerBalanceUpdate.php | 22 ++++++------ app/Jobs/Quote/QuoteWorkflowSettings.php | 4 --- .../Credit/CreditCreatedNotification.php | 6 ++-- .../Credit/CreditEmailedNotification.php | 6 +--- .../Invoice/InvoiceCreatedNotification.php | 4 +-- .../Invoice/InvoiceEmailedNotification.php | 4 +-- .../InvoiceFailedEmailNotification.php | 4 ++- app/Listeners/Invoice/InvoicePaidActivity.php | 5 --- .../Misc/InvitationViewedListener.php | 2 +- .../Payment/PaymentEmailedActivity.php | 1 - app/Listeners/Payment/PaymentNotification.php | 4 +-- .../PurchaseOrderAcceptedListener.php | 2 +- .../PurchaseOrderCreatedListener.php | 4 ++- .../PurchaseOrderEmailedNotification.php | 2 +- .../Quote/QuoteApprovedNotification.php | 4 +-- .../Quote/QuoteCreatedNotification.php | 2 +- .../Quote/QuoteEmailedNotification.php | 8 +---- app/Mail/Admin/EntityPaidObject.php | 3 +- app/Mail/Engine/PaymentEmailEngine.php | 2 +- app/Models/CompanyGateway.php | 4 +++ app/Models/CreditInvitation.php | 34 ------------------- app/Models/QuoteInvitation.php | 1 - app/Providers/EventServiceProvider.php | 4 +-- app/Services/Bank/BankMatchingService.php | 1 - app/Services/Credit/ApplyPayment.php | 1 + config/ninja.php | 4 +-- 28 files changed, 45 insertions(+), 99 deletions(-) diff --git a/VERSION.txt b/VERSION.txt index f4a6c6023301..dd7e5a287cd6 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -5.5.70 \ No newline at end of file +5.5.71 \ No newline at end of file diff --git a/app/Jobs/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php index b59e3529fdb4..9217bdce5967 100644 --- a/app/Jobs/Entity/CreateEntityPdf.php +++ b/app/Jobs/Entity/CreateEntityPdf.php @@ -73,19 +73,15 @@ class CreateEntityPdf implements ShouldQueue $this->invitation = $invitation; if ($invitation instanceof InvoiceInvitation) { - // $invitation->load('contact.client.company','invoice.client','invoice.user.account'); $this->entity = $invitation->invoice; $this->entity_string = 'invoice'; } elseif ($invitation instanceof QuoteInvitation) { - // $invitation->load('contact.client.company','quote.client','quote.user.account'); $this->entity = $invitation->quote; $this->entity_string = 'quote'; } elseif ($invitation instanceof CreditInvitation) { - // $invitation->load('contact.client.company','credit.client','credit.user.account'); $this->entity = $invitation->credit; $this->entity_string = 'credit'; } elseif ($invitation instanceof RecurringInvoiceInvitation) { - // $invitation->load('contact.client.company','recurring_invoice'); $this->entity = $invitation->recurring_invoice; $this->entity_string = 'recurring_invoice'; } diff --git a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php index 731ec0872a77..8dc45cf74f8d 100644 --- a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php +++ b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php @@ -19,25 +19,16 @@ use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Queue\Middleware\WithoutOverlapping; use Illuminate\Queue\SerializesModels; class ClientLedgerBalanceUpdate implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - public $tries = 1; - - public $company; - - public $client; - public $deleteWhenMissingModels = true; - - public function __construct(Company $company, Client $client) - { - $this->company = $company; - $this->client = $client; - } + public function __construct(public Company $company, public Client $client) + {} /** * Execute the job. @@ -71,4 +62,11 @@ class ClientLedgerBalanceUpdate implements ShouldQueue $company_ledger->save(); }); } + + + public function middleware() + { + return [(new WithoutOverlapping($this->client->id))->dontRelease()]; + } + } diff --git a/app/Jobs/Quote/QuoteWorkflowSettings.php b/app/Jobs/Quote/QuoteWorkflowSettings.php index ec95340a7043..9090dc2b9c4c 100644 --- a/app/Jobs/Quote/QuoteWorkflowSettings.php +++ b/app/Jobs/Quote/QuoteWorkflowSettings.php @@ -56,9 +56,5 @@ class QuoteWorkflowSettings implements ShouldQueue $this->quote->service()->sendEmail($invitation->contact); }); } - - // if ($this->client->getSetting('auto_archive_quote')) { - // $this->base_repository->archive($this->quote); - // } } } diff --git a/app/Listeners/Credit/CreditCreatedNotification.php b/app/Listeners/Credit/CreditCreatedNotification.php index 79dfa23d5358..19aca5a7c708 100644 --- a/app/Listeners/Credit/CreditCreatedNotification.php +++ b/app/Listeners/Credit/CreditCreatedNotification.php @@ -24,6 +24,8 @@ class CreditCreatedNotification implements ShouldQueue { use UserNotifies; + public $delay = 10; + public function __construct() { } @@ -64,10 +66,8 @@ class CreditCreatedNotification implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); - /* This prevents more than one notification being sent */ - // $first_notification_sent = false; } /* Override the methods in the Notification Class */ diff --git a/app/Listeners/Credit/CreditEmailedNotification.php b/app/Listeners/Credit/CreditEmailedNotification.php index a983fc6f7306..db09b5a6ae70 100644 --- a/app/Listeners/Credit/CreditEmailedNotification.php +++ b/app/Listeners/Credit/CreditEmailedNotification.php @@ -62,14 +62,10 @@ class CreditEmailedNotification implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); - // $first_notification_sent = false; } - // $notification->method = $methods; - - // $user->notify($notification); } } } diff --git a/app/Listeners/Invoice/InvoiceCreatedNotification.php b/app/Listeners/Invoice/InvoiceCreatedNotification.php index 92f507490168..1022a2f50713 100644 --- a/app/Listeners/Invoice/InvoiceCreatedNotification.php +++ b/app/Listeners/Invoice/InvoiceCreatedNotification.php @@ -24,7 +24,7 @@ class InvoiceCreatedNotification implements ShouldQueue { use UserNotifies; - public $delay = 5; + public $delay = 7; public function __construct() { @@ -70,7 +70,7 @@ class InvoiceCreatedNotification implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); /* This prevents more than one notification being sent */ $first_notification_sent = false; diff --git a/app/Listeners/Invoice/InvoiceEmailedNotification.php b/app/Listeners/Invoice/InvoiceEmailedNotification.php index 66cb02145cf2..e9012e0a8f31 100644 --- a/app/Listeners/Invoice/InvoiceEmailedNotification.php +++ b/app/Listeners/Invoice/InvoiceEmailedNotification.php @@ -24,7 +24,7 @@ class InvoiceEmailedNotification implements ShouldQueue { use UserNotifies; - public $delay = 5; + public $delay = 10; public function __construct() { @@ -68,7 +68,7 @@ class InvoiceEmailedNotification implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); /* This prevents more than one notification being sent */ $first_notification_sent = false; diff --git a/app/Listeners/Invoice/InvoiceFailedEmailNotification.php b/app/Listeners/Invoice/InvoiceFailedEmailNotification.php index 09d28f1870dc..85005e4503e0 100644 --- a/app/Listeners/Invoice/InvoiceFailedEmailNotification.php +++ b/app/Listeners/Invoice/InvoiceFailedEmailNotification.php @@ -26,6 +26,8 @@ class InvoiceFailedEmailNotification { use UserNotifies, Dispatchable, InteractsWithQueue, Queueable, SerializesModels; + public $delay = 7; + public function __construct() { } @@ -60,7 +62,7 @@ class InvoiceFailedEmailNotification $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); $first_notification_sent = false; } diff --git a/app/Listeners/Invoice/InvoicePaidActivity.php b/app/Listeners/Invoice/InvoicePaidActivity.php index e33c837bce10..f2d64a0c8103 100644 --- a/app/Listeners/Invoice/InvoicePaidActivity.php +++ b/app/Listeners/Invoice/InvoicePaidActivity.php @@ -57,10 +57,5 @@ class InvoicePaidActivity implements ShouldQueue $event->invoice->subscription->service()->planPaid($event->invoice); } - // try { - // $event->invoice->service()->touchPdf(); - // } catch (\Exception $e) { - // nlog(print_r($e->getMessage(), 1)); - // } } } diff --git a/app/Listeners/Misc/InvitationViewedListener.php b/app/Listeners/Misc/InvitationViewedListener.php index fb8d28afee29..885b4c9c7b2b 100644 --- a/app/Listeners/Misc/InvitationViewedListener.php +++ b/app/Listeners/Misc/InvitationViewedListener.php @@ -74,7 +74,7 @@ class InvitationViewedListener implements ShouldQueue unset($methods[$key]); $nmo->to_user = $company_user->user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); } } } diff --git a/app/Listeners/Payment/PaymentEmailedActivity.php b/app/Listeners/Payment/PaymentEmailedActivity.php index b4d75181fa13..52ee83b3feaa 100644 --- a/app/Listeners/Payment/PaymentEmailedActivity.php +++ b/app/Listeners/Payment/PaymentEmailedActivity.php @@ -39,7 +39,6 @@ class PaymentEmailedActivity implements ShouldQueue public function handle($event) { MultiDB::setDb($event->company->db); - $payment = $event->payment; } } diff --git a/app/Listeners/Payment/PaymentNotification.php b/app/Listeners/Payment/PaymentNotification.php index 1899c9ed35f1..5dbe0374e519 100644 --- a/app/Listeners/Payment/PaymentNotification.php +++ b/app/Listeners/Payment/PaymentNotification.php @@ -24,7 +24,7 @@ class PaymentNotification implements ShouldQueue { use UserNotifies; - public $delay = 5; + public $delay = 20; /** * Create the event listener. @@ -75,7 +75,7 @@ class PaymentNotification implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); } } diff --git a/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php b/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php index d83b7223d573..2803f82379a6 100644 --- a/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php +++ b/app/Listeners/PurchaseOrder/PurchaseOrderAcceptedListener.php @@ -64,7 +64,7 @@ class PurchaseOrderAcceptedListener implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); /* This prevents more than one notification being sent */ $first_notification_sent = false; diff --git a/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php b/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php index 6b7e146defed..61178815573f 100644 --- a/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php +++ b/app/Listeners/PurchaseOrder/PurchaseOrderCreatedListener.php @@ -25,6 +25,8 @@ class PurchaseOrderCreatedListener implements ShouldQueue { use UserNotifies; + public $delay = 7; + public function __construct() { } @@ -69,7 +71,7 @@ class PurchaseOrderCreatedListener implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); /* This prevents more than one notification being sent */ $first_notification_sent = false; diff --git a/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php b/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php index 22541380768c..82c3b3b0cf18 100644 --- a/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php +++ b/app/Listeners/PurchaseOrder/PurchaseOrderEmailedNotification.php @@ -68,7 +68,7 @@ class PurchaseOrderEmailedNotification implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); /* This prevents more than one notification being sent */ $first_notification_sent = false; diff --git a/app/Listeners/Quote/QuoteApprovedNotification.php b/app/Listeners/Quote/QuoteApprovedNotification.php index eae4d21e417a..adedab41f90c 100644 --- a/app/Listeners/Quote/QuoteApprovedNotification.php +++ b/app/Listeners/Quote/QuoteApprovedNotification.php @@ -23,7 +23,7 @@ class QuoteApprovedNotification implements ShouldQueue { use UserNotifies; - public $delay = 5; + public $delay = 8; public function __construct() { @@ -66,7 +66,7 @@ class QuoteApprovedNotification implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); /* This prevents more than one notification being sent */ $first_notification_sent = false; diff --git a/app/Listeners/Quote/QuoteCreatedNotification.php b/app/Listeners/Quote/QuoteCreatedNotification.php index 6c636605f127..5af1a1943e69 100644 --- a/app/Listeners/Quote/QuoteCreatedNotification.php +++ b/app/Listeners/Quote/QuoteCreatedNotification.php @@ -70,7 +70,7 @@ class QuoteCreatedNotification implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); /* This prevents more than one notification being sent */ $first_notification_sent = false; diff --git a/app/Listeners/Quote/QuoteEmailedNotification.php b/app/Listeners/Quote/QuoteEmailedNotification.php index 8c67b1e84e78..296e7df119d0 100644 --- a/app/Listeners/Quote/QuoteEmailedNotification.php +++ b/app/Listeners/Quote/QuoteEmailedNotification.php @@ -54,8 +54,6 @@ class QuoteEmailedNotification implements ShouldQueue foreach ($event->invitation->company->company_users as $company_user) { $user = $company_user->user; - // $notification = new EntitySentNotification($event->invitation, 'quote'); - $methods = $this->findUserNotificationTypes($event->invitation, $company_user, 'quote', ['all_notifications', 'quote_sent', 'quote_sent_all', 'quote_sent_user']); if (($key = array_search('mail', $methods)) !== false) { @@ -63,14 +61,10 @@ class QuoteEmailedNotification implements ShouldQueue $nmo->to_user = $user; - NinjaMailerJob::dispatch($nmo); + (new NinjaMailerJob($nmo))->handle(); - // $first_notification_sent = false; } - // $notification->method = $methods; - - // $user->notify($notification); } } } diff --git a/app/Mail/Admin/EntityPaidObject.php b/app/Mail/Admin/EntityPaidObject.php index eb3c8153d0b5..aa806d66e4a6 100644 --- a/app/Mail/Admin/EntityPaidObject.php +++ b/app/Mail/Admin/EntityPaidObject.php @@ -16,6 +16,7 @@ use App\Utils\Ninja; use App\Utils\Number; use Illuminate\Support\Facades\App; use stdClass; +use App\Models\Payment; class EntityPaidObject { @@ -29,7 +30,7 @@ class EntityPaidObject public $settings; - public function __construct($payment) + public function __construct(public Payment $payment) { $this->payment = $payment; $this->company = $payment->company; diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php index cae4251c57b7..a8f7d44f46d7 100644 --- a/app/Mail/Engine/PaymentEmailEngine.php +++ b/app/Mail/Engine/PaymentEmailEngine.php @@ -323,7 +323,7 @@ class PaymentEmailEngine extends BaseEmailEngine $invoice_list = '

'; foreach ($this->payment->invoices as $invoice) { - $invoice_list .= ctrans('texts.invoice_number_short')." {$invoice->number} - ".Number::formatMoney($invoice->pivot->amount, $this->client).'
'; + $invoice_list .= ctrans('texts.invoice_number_short')." {$invoice->number} ".Number::formatMoney($invoice->pivot->amount, $this->client).'
'; } return $invoice_list; diff --git a/app/Models/CompanyGateway.php b/app/Models/CompanyGateway.php index 9dc1f03c2453..7bded57017a0 100644 --- a/app/Models/CompanyGateway.php +++ b/app/Models/CompanyGateway.php @@ -74,6 +74,8 @@ class CompanyGateway extends BaseModel // const TYPE_WEPAY = 309; // const TYPE_PAYFAST = 310; // const TYPE_PAYTRACE = 311; + // const TYPE_MOLLIE = 312; + // const TYPE_EWAY = 313; // const TYPE_FORTE = 314; public $gateway_consts = [ @@ -87,6 +89,8 @@ class CompanyGateway extends BaseModel '8fdeed552015b3c7b44ed6c8ebd9e992' => 309, 'd6814fc83f45d2935e7777071e629ef9' => 310, 'bbd736b3254b0aabed6ad7fda1298c88' => 311, + '1bd651fb213ca0c9d66ae3c336dc77e7' => 312, + '944c20175bbe6b9972c05bcfe294c2c7' => 313, 'kivcvjexxvdiyqtj3mju5d6yhpeht2xs' => 314, '65faab2ab6e3223dbe848b1686490baz' => 320, 'b9886f9257f0c6ee7c302f1c74475f6c' => 321, diff --git a/app/Models/CreditInvitation.php b/app/Models/CreditInvitation.php index d029f915edee..1f600e19aff4 100644 --- a/app/Models/CreditInvitation.php +++ b/app/Models/CreditInvitation.php @@ -11,7 +11,6 @@ namespace App\Models; -use App\Events\Credit\CreditWasUpdated; use App\Jobs\Entity\CreateEntityPdf; use App\Utils\Ninja; use App\Utils\Traits\Inviteable; @@ -44,38 +43,6 @@ class CreditInvitation extends BaseModel return self::class; } - // public function getSignatureDateAttribute($value) - // { - // if (!$value) { - // return (new Carbon($value))->format('Y-m-d'); - // } - // return $value; - // } - - // public function getSentDateAttribute($value) - // { - // if (!$value) { - // return (new Carbon($value))->format('Y-m-d'); - // } - // return $value; - // } - - // public function getViewedDateAttribute($value) - // { - // if (!$value) { - // return (new Carbon($value))->format('Y-m-d'); - // } - // return $value; - // } - - // public function getOpenedDateAttribute($value) - // { - // if (!$value) { - // return (new Carbon($value))->format('Y-m-d'); - // } - // return $value; - // } - public function entityType() { return Credit::class; @@ -129,7 +96,6 @@ class CreditInvitation extends BaseModel $storage_path = Storage::url($this->credit->client->quote_filepath($this).$this->credit->numberFormatter().'.pdf'); if (! Storage::exists($this->credit->client->credit_filepath($this).$this->credit->numberFormatter().'.pdf')) { - event(new CreditWasUpdated($this->credit, $this->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); (new CreateEntityPdf($this))->handle(); } diff --git a/app/Models/QuoteInvitation.php b/app/Models/QuoteInvitation.php index c3508b23fa0e..d5cb22710a89 100644 --- a/app/Models/QuoteInvitation.php +++ b/app/Models/QuoteInvitation.php @@ -101,7 +101,6 @@ class QuoteInvitation extends BaseModel $storage_path = Storage::url($this->quote->client->quote_filepath($this).$this->quote->numberFormatter().'.pdf'); if (! Storage::exists($this->quote->client->quote_filepath($this).$this->quote->numberFormatter().'.pdf')) { - event(new QuoteWasUpdated($this->quote, $this->company, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); (new CreateEntityPdf($this))->handle(); } diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index b0949dc593df..a9434ea7f937 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -407,12 +407,10 @@ class EventServiceProvider extends ServiceProvider ], InvoiceWasUpdated::class => [ UpdateInvoiceActivity::class, - CreateInvoicePdf::class, ], InvoiceWasCreated::class => [ CreateInvoiceActivity::class, InvoiceCreatedNotification::class, - // CreateInvoicePdf::class, ], InvoiceWasPaid::class => [ InvoicePaidActivity::class, @@ -451,7 +449,7 @@ class EventServiceProvider extends ServiceProvider InvitationViewedListener::class, ], PaymentWasEmailed::class => [ - PaymentEmailedActivity::class, + // PaymentEmailedActivity::class, ], PaymentWasEmailedAndFailed::class => [ // PaymentEmailFailureActivity::class, diff --git a/app/Services/Bank/BankMatchingService.php b/app/Services/Bank/BankMatchingService.php index 906e21fe918d..df013e77cc29 100644 --- a/app/Services/Bank/BankMatchingService.php +++ b/app/Services/Bank/BankMatchingService.php @@ -23,7 +23,6 @@ use Illuminate\Queue\SerializesModels; class BankMatchingService implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - public function __construct(public $company_id, public $db) { } diff --git a/app/Services/Credit/ApplyPayment.php b/app/Services/Credit/ApplyPayment.php index f9eeb7ec46e8..0f8af8b4aef7 100644 --- a/app/Services/Credit/ApplyPayment.php +++ b/app/Services/Credit/ApplyPayment.php @@ -137,6 +137,7 @@ class ApplyPayment ->updateBalance($this->amount_applied * -1) ->updatePaidToDate($this->amount_applied) ->updateStatus() + ->touchPdf() ->save(); $this->credit diff --git a/config/ninja.php b/config/ninja.php index 54370ef71469..6cfd2e5814a1 100644 --- a/config/ninja.php +++ b/config/ninja.php @@ -14,8 +14,8 @@ return [ 'require_https' => env('REQUIRE_HTTPS', true), 'app_url' => rtrim(env('APP_URL', ''), '/'), 'app_domain' => env('APP_DOMAIN', 'invoicing.co'), - 'app_version' => '5.5.70', - 'app_tag' => '5.5.70', + 'app_version' => '5.5.71', + 'app_tag' => '5.5.71', 'minimum_client_version' => '5.0.16', 'terms_version' => '1.0.1', 'api_secret' => env('API_SECRET', ''), From 419df4c510f524ad4524b43cdbc1c3e57feb0678 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 20:33:47 +1100 Subject: [PATCH 66/72] Fixes for basedriver --- app/PaymentDrivers/BaseDriver.php | 97 +++++++++++++++++++------------ 1 file changed, 59 insertions(+), 38 deletions(-) diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index 8321961048ad..83a1ced0c5fd 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -11,34 +11,39 @@ namespace App\PaymentDrivers; -use App\Events\Invoice\InvoiceWasPaid; -use App\Events\Payment\PaymentWasCreated; -use App\Exceptions\PaymentFailed; -use App\Factory\PaymentFactory; -use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; -use App\Jobs\Mail\NinjaMailer; -use App\Jobs\Mail\NinjaMailerJob; -use App\Jobs\Mail\NinjaMailerObject; -use App\Jobs\Mail\PaymentFailedMailer; -use App\Jobs\Util\SystemLogger; -use App\Mail\Admin\ClientPaymentFailureObject; +use Exception; +use App\Utils\Ninja; use App\Models\Client; -use App\Models\ClientContact; -use App\Models\ClientGatewayToken; -use App\Models\CompanyGateway; -use App\Models\GatewayType; +use App\Utils\Helpers; use App\Models\Invoice; use App\Models\Payment; -use App\Models\PaymentHash; use App\Models\SystemLog; -use App\Services\Subscription\SubscriptionService; -use App\Utils\Helpers; -use App\Utils\Ninja; -use App\Utils\Traits\MakesHash; -use App\Utils\Traits\SystemLogTrait; -use Illuminate\Http\Request; -use Illuminate\Support\Carbon; +use App\Models\GatewayType; +use App\Models\PaymentHash; +use App\Models\PaymentType; use Illuminate\Support\Str; +use Illuminate\Http\Request; +use App\Models\ClientContact; +use App\Jobs\Mail\NinjaMailer; +use App\Models\CompanyGateway; +use Illuminate\Support\Carbon; +use App\Factory\PaymentFactory; +use App\Jobs\Util\SystemLogger; +use App\Utils\Traits\MakesHash; +use App\Models\TransactionEvent; +use App\Exceptions\PaymentFailed; +use App\Jobs\Mail\NinjaMailerJob; +use App\Jobs\Ninja\TransactionLog; +use App\Models\ClientGatewayToken; +use App\Jobs\Mail\NinjaMailerObject; +use App\Utils\Traits\SystemLogTrait; +use App\Events\Invoice\InvoiceWasPaid; +use App\Jobs\Mail\PaymentFailedMailer; +use App\Events\Payment\PaymentWasCreated; +use App\Mail\Admin\ClientPaymentFailureObject; +use App\Services\Subscription\SubscriptionService; +use Checkout\Library\Exceptions\CheckoutHttpException; +use App\Http\Requests\ClientPortal\Payments\PaymentResponseRequest; /** * Class BaseDriver. @@ -54,6 +59,10 @@ class BaseDriver extends AbstractPaymentDriver /* The Invitation */ public $invitation; + + /* The client */ + public $client; + /* Gateway capabilities */ public $refundable = false; @@ -63,15 +72,17 @@ class BaseDriver extends AbstractPaymentDriver /* Authorise payment methods */ public $can_authorise_credit_card = false; - /* The client */ - public $client; - /* The initialized gateway driver class*/ public $payment_method; - /* PaymentHash */ + /** + * @var PaymentHash + */ public $payment_hash; + /** + * @var Helpers` + */ public $helpers; /* Array of payment methods */ @@ -80,7 +91,7 @@ class BaseDriver extends AbstractPaymentDriver /** @var array */ public $required_fields = []; - public function __construct(CompanyGateway $company_gateway, Client $client = null, $invitation = false) + public function __construct(CompanyGateway $company_gateway, ?Client $client = null, $invitation = false) { $this->company_gateway = $company_gateway; $this->invitation = $invitation; @@ -88,12 +99,6 @@ class BaseDriver extends AbstractPaymentDriver $this->helpers = new Helpers(); } - /** - * Required fields for client to fill, to proceed with gateway actions. - * - * @return array[] - */ - public function init() { return $this; @@ -104,6 +109,11 @@ class BaseDriver extends AbstractPaymentDriver return $this; } + /** + * Required fields for client to fill, to proceed with gateway actions. + * + * @return array[] + */ public function getClientRequiredFields(): array { $fields = []; @@ -145,24 +155,33 @@ class BaseDriver extends AbstractPaymentDriver } if ($this->company_gateway->require_custom_value1) { + $fields[] = ['name' => 'client_custom_value1', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client1'), 'type' => 'text', 'validation' => 'required']; + } if ($this->company_gateway->require_custom_value2) { + $fields[] = ['name' => 'client_custom_value2', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client2'), 'type' => 'text', 'validation' => 'required']; + } if ($this->company_gateway->require_custom_value3) { + $fields[] = ['name' => 'client_custom_value3', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client3'), 'type' => 'text', 'validation' => 'required']; + } if ($this->company_gateway->require_custom_value4) { + $fields[] = ['name' => 'client_custom_value4', 'label' => $this->helpers->makeCustomField($this->client->company->custom_fields, 'client4'), 'type' => 'text', 'validation' => 'required']; + } return $fields; + } /** @@ -355,11 +374,11 @@ class BaseDriver extends AbstractPaymentDriver event(new PaymentWasCreated($payment, $payment->company, Ninja::eventVars())); if (property_exists($this->payment_hash->data, 'billing_context') && $status == Payment::STATUS_COMPLETED) { - if (is_int($this->payment_hash->data->billing_context->subscription_id)) { + + if(is_int($this->payment_hash->data->billing_context->subscription_id)) $billing_subscription = \App\Models\Subscription::find($this->payment_hash->data->billing_context->subscription_id); - } else { + else $billing_subscription = \App\Models\Subscription::find($this->decodePrimaryKey($this->payment_hash->data->billing_context->subscription_id)); - } // To access campaign hash => $this->payment_hash->data->billing_context->campaign; // To access campaign data => Cache::get(CAMPAIGN_HASH) @@ -380,6 +399,7 @@ class BaseDriver extends AbstractPaymentDriver */ public function confirmGatewayFee() :void { + /*Payment invoices*/ $payment_invoices = $this->payment_hash->invoices(); @@ -393,6 +413,7 @@ class BaseDriver extends AbstractPaymentDriver if (collect($invoice->line_items)->contains('type_id', '3')) { $invoice->service()->toggleFeesPaid()->save(); } + }); } @@ -490,7 +511,7 @@ class BaseDriver extends AbstractPaymentDriver public function sendFailureMail($error) { - if (is_object($error)) { + if(is_object($error)){ $error = 'Payment Aborted'; } From 5bca8e9a107d418cd61c54c8849f83d596258b3d Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 20:43:00 +1100 Subject: [PATCH 67/72] MInor fixes for scheduler --- app/Transformers/SchedulerTransformer.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/Transformers/SchedulerTransformer.php b/app/Transformers/SchedulerTransformer.php index 7314457845fb..ddef7bb15b51 100644 --- a/app/Transformers/SchedulerTransformer.php +++ b/app/Transformers/SchedulerTransformer.php @@ -33,6 +33,7 @@ class SchedulerTransformer extends EntityTransformer 'updated_at' => (int) $scheduler->updated_at, 'created_at' => (int) $scheduler->created_at, 'archived_at' => (int) $scheduler->deleted_at, + 'remaining_cycles' => (int) $scheduler->remaining_cycles, ]; } } From 2196d8fc204d4f7aed5f864bafd8b9978063d08e Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 21:05:01 +1100 Subject: [PATCH 68/72] frequency_id optional for scheduler --- app/DataMapper/CompanySettings.php | 3 +++ app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php | 2 +- app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php | 2 +- app/PaymentDrivers/BaseDriver.php | 3 +-- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/app/DataMapper/CompanySettings.php b/app/DataMapper/CompanySettings.php index 4219b6863c0d..05b9ee944f6a 100644 --- a/app/DataMapper/CompanySettings.php +++ b/app/DataMapper/CompanySettings.php @@ -465,7 +465,10 @@ class CompanySettings extends BaseSettings public $allow_billable_task_items = false; + public $show_task_item_description = false; + public static $casts = [ + 'show_task_item_description' => 'bool', 'allow_billable_task_items' => 'bool', 'accept_client_input_quote_approval' => 'bool', 'custom_sending_email' => 'string', diff --git a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php index 9061d57912d6..fcc52ae8c302 100644 --- a/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/StoreSchedulerRequest.php @@ -34,7 +34,7 @@ class StoreSchedulerRequest extends Request $rules = [ 'name' => ['bail', 'required', Rule::unique('schedulers')->where('company_id', auth()->user()->company()->id)], 'is_paused' => 'bail|sometimes|boolean', - 'frequency_id' => 'bail|required|integer|digits_between:1,12', + 'frequency_id' => 'bail|sometimes|integer|digits_between:1,12', 'next_run' => 'bail|required|date:Y-m-d|after_or_equal:today', 'next_run_client' => 'bail|sometimes|date:Y-m-d', 'template' => 'bail|required|string', diff --git a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php index 02a5e69b5351..fab559b55bc4 100644 --- a/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php +++ b/app/Http/Requests/TaskScheduler/UpdateSchedulerRequest.php @@ -30,7 +30,7 @@ class UpdateSchedulerRequest extends Request $rules = [ 'name' => ['bail', 'sometimes', Rule::unique('schedulers')->where('company_id', auth()->user()->company()->id)->ignore($this->task_scheduler->id)], 'is_paused' => 'bail|sometimes|boolean', - 'frequency_id' => 'bail|required|integer|digits_between:1,12', + 'frequency_id' => 'bail|sometimes|integer|digits_between:1,12', 'next_run' => 'bail|required|date:Y-m-d|after_or_equal:today', 'next_run_client' => 'bail|sometimes|date:Y-m-d', 'template' => 'bail|required|string', diff --git a/app/PaymentDrivers/BaseDriver.php b/app/PaymentDrivers/BaseDriver.php index 83a1ced0c5fd..b15e78de4d2d 100644 --- a/app/PaymentDrivers/BaseDriver.php +++ b/app/PaymentDrivers/BaseDriver.php @@ -59,7 +59,6 @@ class BaseDriver extends AbstractPaymentDriver /* The Invitation */ public $invitation; - /* The client */ public $client; @@ -91,7 +90,7 @@ class BaseDriver extends AbstractPaymentDriver /** @var array */ public $required_fields = []; - public function __construct(CompanyGateway $company_gateway, ?Client $client = null, $invitation = false) + public function __construct(CompanyGateway $company_gateway, ?Client $client = null, $invitation = null) { $this->company_gateway = $company_gateway; $this->invitation = $invitation; From da52554e71222b8442f5b6279cdf88067286f59c Mon Sep 17 00:00:00 2001 From: David Bomba Date: Fri, 17 Feb 2023 21:27:38 +1100 Subject: [PATCH 69/72] Bump cypress version --- package-lock.json | 110 +++++++++++++++++++++++----------------------- package.json | 2 +- 2 files changed, 56 insertions(+), 56 deletions(-) diff --git a/package-lock.json b/package-lock.json index d405d23ff917..e2570e6e2ba9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,7 +28,7 @@ "@babel/compat-data": "7.15.0", "@babel/plugin-proposal-class-properties": "^7.14.5", "@tailwindcss/aspect-ratio": "^0.4.2", - "cypress": "^12.3.0", + "cypress": "^12.5.1", "laravel-mix-purgecss": "^6.0.0", "vue-template-compiler": "^2.6.14" } @@ -3906,9 +3906,9 @@ } }, "node_modules/cypress": { - "version": "12.3.0", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-12.3.0.tgz", - "integrity": "sha512-ZQNebibi6NBt51TRxRMYKeFvIiQZ01t50HSy7z/JMgRVqBUey3cdjog5MYEbzG6Ktti5ckDt1tfcC47lmFwXkw==", + "version": "12.5.1", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-12.5.1.tgz", + "integrity": "sha512-ZmCmJ3lsyeOpBfh410m5+AO2CO1AxAzFBt7k6/uVbNcrNZje1vdiwYTpj2ksPKg9mjr9lR6V8tmlDNMvr4H/YQ==", "dev": true, "hasInstallScript": true, "dependencies": { @@ -5548,9 +5548,9 @@ } }, "node_modules/html-minifier-terser/node_modules/terser": { - "version": "4.8.0", - "resolved": "https://registry.npmjs.org/terser/-/terser-4.8.0.tgz", - "integrity": "sha512-EAPipTNeWsb/3wLPeup1tVPaXfIaU68xMnVdPafIL1TV05OhASArYyIfFvnvJCNrR2NIOvDVNNTFRa+Re2MWyw==", + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/terser/-/terser-4.8.1.tgz", + "integrity": "sha512-4GnLC0x667eJG0ewJTa6z/yXrbLGv80D9Ru6HIpCQmO+Q4PfEtBFi0ObSckqwL6VyQv/7ENJieXHo2ANmdQwgw==", "dependencies": { "commander": "^2.20.0", "source-map": "~0.6.1", @@ -5759,9 +5759,9 @@ } }, "node_modules/img-loader/node_modules/json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", "dependencies": { "minimist": "^1.2.0" }, @@ -5770,9 +5770,9 @@ } }, "node_modules/img-loader/node_modules/loader-utils": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz", - "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==", + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.2.tgz", + "integrity": "sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg==", "dependencies": { "big.js": "^5.2.2", "emojis-list": "^3.0.0", @@ -6175,9 +6175,9 @@ "dev": true }, "node_modules/json5": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", - "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", "bin": { "json5": "lib/cli.js" }, @@ -6474,9 +6474,9 @@ } }, "node_modules/loader-utils": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.2.tgz", - "integrity": "sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz", + "integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==", "dependencies": { "big.js": "^5.2.2", "emojis-list": "^3.0.0", @@ -9543,9 +9543,9 @@ } }, "node_modules/terser": { - "version": "5.14.0", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.14.0.tgz", - "integrity": "sha512-JC6qfIEkPBd9j1SMO3Pfn+A6w2kQV54tv+ABQLgZr7dA3k/DL/OBoYSWxzVpZev3J+bUHXfr55L8Mox7AaNo6g==", + "version": "5.16.3", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.16.3.tgz", + "integrity": "sha512-v8wWLaS/xt3nE9dgKEWhNUFP6q4kngO5B8eYFUuebsu7Dw/UNAnpUod6UHo04jSSkv8TzKHjZDSd7EXdDQAl8Q==", "dependencies": { "@jridgewell/source-map": "^0.3.2", "acorn": "^8.5.0", @@ -9942,9 +9942,9 @@ } }, "node_modules/vue-style-loader/node_modules/json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", "dependencies": { "minimist": "^1.2.0" }, @@ -9953,9 +9953,9 @@ } }, "node_modules/vue-style-loader/node_modules/loader-utils": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz", - "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==", + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.2.tgz", + "integrity": "sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg==", "dependencies": { "big.js": "^5.2.2", "emojis-list": "^3.0.0", @@ -13512,9 +13512,9 @@ } }, "cypress": { - "version": "12.3.0", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-12.3.0.tgz", - "integrity": "sha512-ZQNebibi6NBt51TRxRMYKeFvIiQZ01t50HSy7z/JMgRVqBUey3cdjog5MYEbzG6Ktti5ckDt1tfcC47lmFwXkw==", + "version": "12.5.1", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-12.5.1.tgz", + "integrity": "sha512-ZmCmJ3lsyeOpBfh410m5+AO2CO1AxAzFBt7k6/uVbNcrNZje1vdiwYTpj2ksPKg9mjr9lR6V8tmlDNMvr4H/YQ==", "dev": true, "requires": { "@cypress/request": "^2.88.10", @@ -14733,9 +14733,9 @@ "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==" }, "terser": { - "version": "4.8.0", - "resolved": "https://registry.npmjs.org/terser/-/terser-4.8.0.tgz", - "integrity": "sha512-EAPipTNeWsb/3wLPeup1tVPaXfIaU68xMnVdPafIL1TV05OhASArYyIfFvnvJCNrR2NIOvDVNNTFRa+Re2MWyw==", + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/terser/-/terser-4.8.1.tgz", + "integrity": "sha512-4GnLC0x667eJG0ewJTa6z/yXrbLGv80D9Ru6HIpCQmO+Q4PfEtBFi0ObSckqwL6VyQv/7ENJieXHo2ANmdQwgw==", "requires": { "commander": "^2.20.0", "source-map": "~0.6.1", @@ -14879,17 +14879,17 @@ }, "dependencies": { "json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", "requires": { "minimist": "^1.2.0" } }, "loader-utils": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz", - "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==", + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.2.tgz", + "integrity": "sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg==", "requires": { "big.js": "^5.2.2", "emojis-list": "^3.0.0", @@ -15182,9 +15182,9 @@ "dev": true }, "json5": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", - "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==" + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==" }, "jsonfile": { "version": "6.1.0", @@ -15387,9 +15387,9 @@ "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==" }, "loader-utils": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.2.tgz", - "integrity": "sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz", + "integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==", "requires": { "big.js": "^5.2.2", "emojis-list": "^3.0.0", @@ -17588,9 +17588,9 @@ "integrity": "sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==" }, "terser": { - "version": "5.14.0", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.14.0.tgz", - "integrity": "sha512-JC6qfIEkPBd9j1SMO3Pfn+A6w2kQV54tv+ABQLgZr7dA3k/DL/OBoYSWxzVpZev3J+bUHXfr55L8Mox7AaNo6g==", + "version": "5.16.3", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.16.3.tgz", + "integrity": "sha512-v8wWLaS/xt3nE9dgKEWhNUFP6q4kngO5B8eYFUuebsu7Dw/UNAnpUod6UHo04jSSkv8TzKHjZDSd7EXdDQAl8Q==", "requires": { "@jridgewell/source-map": "^0.3.2", "acorn": "^8.5.0", @@ -17892,17 +17892,17 @@ }, "dependencies": { "json5": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", - "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", "requires": { "minimist": "^1.2.0" } }, "loader-utils": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.0.tgz", - "integrity": "sha512-qH0WSMBtn/oHuwjy/NucEgbx5dbxxnxup9s4PVXJUDHZBQY+s0NWA9rJf53RBnQZxfch7euUui7hpoAPvALZdA==", + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.4.2.tgz", + "integrity": "sha512-I5d00Pd/jwMD2QCduo657+YM/6L3KZu++pmX9VFncxaxvHcru9jx1lBaFft+r4Mt2jK0Yhp41XlRAihzPxHNCg==", "requires": { "big.js": "^5.2.2", "emojis-list": "^3.0.0", diff --git a/package.json b/package.json index d2616e86e6b0..c18d3cc0a252 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "@babel/compat-data": "7.15.0", "@babel/plugin-proposal-class-properties": "^7.14.5", "@tailwindcss/aspect-ratio": "^0.4.2", - "cypress": "^12.3.0", + "cypress": "^12.5.1", "laravel-mix-purgecss": "^6.0.0", "vue-template-compiler": "^2.6.14" }, From 63a7a1185394ea7ad4157967462171815fafc849 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sat, 18 Feb 2023 08:06:53 +1100 Subject: [PATCH 70/72] Minor fixes for types --- ...ClientStatement.php => EmailStatement.php} | 2 +- app/Jobs/Mail/NinjaMailerJob.php | 4 +- app/Services/Email/EmailObject.php | 7 ++- app/Services/Scheduler/SchedulerService.php | 23 ++++---- tests/Feature/Scheduler/SchedulerTest.php | 52 +++++++++---------- 5 files changed, 45 insertions(+), 43 deletions(-) rename app/DataMapper/Schedule/{ClientStatement.php => EmailStatement.php} (99%) diff --git a/app/DataMapper/Schedule/ClientStatement.php b/app/DataMapper/Schedule/EmailStatement.php similarity index 99% rename from app/DataMapper/Schedule/ClientStatement.php rename to app/DataMapper/Schedule/EmailStatement.php index ea97f8b636a1..b9ece221c7ee 100644 --- a/app/DataMapper/Schedule/ClientStatement.php +++ b/app/DataMapper/Schedule/EmailStatement.php @@ -11,7 +11,7 @@ namespace App\DataMapper\Schedule; -class ClientStatement +class EmailStatement { /** * Defines the template name diff --git a/app/Jobs/Mail/NinjaMailerJob.php b/app/Jobs/Mail/NinjaMailerJob.php index 48844a200b28..82a3ec5255ef 100644 --- a/app/Jobs/Mail/NinjaMailerJob.php +++ b/app/Jobs/Mail/NinjaMailerJob.php @@ -207,7 +207,7 @@ class NinjaMailerJob implements ShouldQueue switch ($class) { case Invoice::class: - event(new InvoiceWasEmailedAndFailed($this->nmo->invitation, $this->nmo->company, $message, $this->nmo->reminder_template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); + event(new InvoiceWasEmailedAndFailed($this->nmo->invitation, $this->nmo->company, $message, $this->nmo->template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); break; case Payment::class: event(new PaymentWasEmailedAndFailed($this->nmo->entity, $this->nmo->company, $message, Ninja::eventVars(auth()->user() ? auth()->user()->id : null))); @@ -546,7 +546,7 @@ class NinjaMailerJob implements ShouldQueue * Logs any errors to the SystemLog * * @param string $errors - * @param App\Models\User | App\Models\Client $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/Services/Email/EmailObject.php b/app/Services/Email/EmailObject.php index a7da351727b6..4488fd02366f 100644 --- a/app/Services/Email/EmailObject.php +++ b/app/Services/Email/EmailObject.php @@ -11,10 +11,11 @@ namespace App\Services\Email; -use App\Models\Client; -use App\Models\ClientContact; use App\Models\User; +use App\Models\Client; use App\Models\Vendor; +use App\Models\Company; +use App\Models\ClientContact; use App\Models\VendorContact; use Illuminate\Mail\Mailables\Address; @@ -78,4 +79,6 @@ class EmailObject public ?string $entity_class = null; public array $variables = []; + + public ?Company $company = null; } diff --git a/app/Services/Scheduler/SchedulerService.php b/app/Services/Scheduler/SchedulerService.php index 72113dd32d02..ebb701e55e83 100644 --- a/app/Services/Scheduler/SchedulerService.php +++ b/app/Services/Scheduler/SchedulerService.php @@ -16,8 +16,7 @@ use App\Models\Scheduler; use App\Utils\Traits\MakesHash; use App\Models\RecurringInvoice; use App\Utils\Traits\MakesDates; -use App\DataMapper\Schedule\ClientStatement; -use Symfony\Component\HttpClient\Internal\ClientState; +use App\DataMapper\Schedule\EmailStatement; class SchedulerService { @@ -93,16 +92,16 @@ class SchedulerService private function calculateStartAndEndDates(): array { return match ($this->scheduler->parameters['date_range']) { - ClientStatement::LAST7 => [now()->startOfDay()->subDays(7)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], - ClientStatement::LAST30 => [now()->startOfDay()->subDays(30)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], - ClientStatement::LAST365 => [now()->startOfDay()->subDays(365)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], - ClientStatement::THIS_MONTH => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], - ClientStatement::LAST_MONTH => [now()->startOfDay()->subMonthNoOverflow()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->subMonthNoOverflow()->lastOfMonth()->format('Y-m-d')], - ClientStatement::THIS_QUARTER => [now()->startOfDay()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->lastOfQuarter()->format('Y-m-d')], - ClientStatement::LAST_QUARTER => [now()->startOfDay()->subQuarterNoOverflow()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->subQuarterNoOverflow()->lastOfQuarter()->format('Y-m-d')], - ClientStatement::THIS_YEAR => [now()->startOfDay()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->lastOfYear()->format('Y-m-d')], - ClientStatement::LAST_YEAR => [now()->startOfDay()->subYearNoOverflow()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->subYearNoOverflow()->lastOfYear()->format('Y-m-d')], - ClientStatement::CUSTOM_RANGE => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']], + EmailStatement::LAST7 => [now()->startOfDay()->subDays(7)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + EmailStatement::LAST30 => [now()->startOfDay()->subDays(30)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + EmailStatement::LAST365 => [now()->startOfDay()->subDays(365)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + EmailStatement::THIS_MONTH => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], + EmailStatement::LAST_MONTH => [now()->startOfDay()->subMonthNoOverflow()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->subMonthNoOverflow()->lastOfMonth()->format('Y-m-d')], + EmailStatement::THIS_QUARTER => [now()->startOfDay()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->lastOfQuarter()->format('Y-m-d')], + EmailStatement::LAST_QUARTER => [now()->startOfDay()->subQuarterNoOverflow()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->subQuarterNoOverflow()->lastOfQuarter()->format('Y-m-d')], + EmailStatement::THIS_YEAR => [now()->startOfDay()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->lastOfYear()->format('Y-m-d')], + EmailStatement::LAST_YEAR => [now()->startOfDay()->subYearNoOverflow()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->subYearNoOverflow()->lastOfYear()->format('Y-m-d')], + EmailStatement::CUSTOM_RANGE => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']], default => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], }; } diff --git a/tests/Feature/Scheduler/SchedulerTest.php b/tests/Feature/Scheduler/SchedulerTest.php index 6fba294959f6..a080ced33659 100644 --- a/tests/Feature/Scheduler/SchedulerTest.php +++ b/tests/Feature/Scheduler/SchedulerTest.php @@ -21,7 +21,7 @@ use App\Models\RecurringInvoice; use App\Factory\SchedulerFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Session; -use App\DataMapper\Schedule\ClientStatement; +use App\DataMapper\Schedule\EmailStatement; use App\Services\Scheduler\SchedulerService; use Illuminate\Validation\ValidationException; use Illuminate\Foundation\Testing\WithoutEvents; @@ -76,7 +76,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => ClientStatement::LAST_MONTH, + 'date_range' => EmailStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -139,7 +139,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => ClientStatement::LAST_MONTH, + 'date_range' => EmailStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -171,7 +171,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->addDay()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => ClientStatement::LAST_MONTH, + 'date_range' => EmailStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -195,7 +195,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => ClientStatement::LAST_MONTH, + 'date_range' => EmailStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -224,7 +224,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => ClientStatement::LAST_MONTH, + 'date_range' => EmailStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -259,7 +259,7 @@ class SchedulerTest extends TestCase 'next_run' => "2023-01-01", 'template' => 'client_statement', 'parameters' => [ - 'date_range' => ClientStatement::LAST_MONTH, + 'date_range' => EmailStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -278,7 +278,7 @@ class SchedulerTest extends TestCase $this->assertIsArray($method); - $this->assertEquals(ClientStatement::LAST_MONTH, $scheduler->parameters['date_range']); + $this->assertEquals(EmailStatement::LAST_MONTH, $scheduler->parameters['date_range']); $this->assertEqualsCanonicalizing(['2022-12-01','2022-12-31'], $method); } @@ -293,7 +293,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => ClientStatement::LAST_MONTH, + 'date_range' => EmailStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', @@ -324,13 +324,13 @@ class SchedulerTest extends TestCase { $this->travelTo(Carbon::parse('2023-01-14')); - $this->assertEqualsCanonicalizing(['2023-01-01','2023-01-31'], $this->getDateRange(ClientStatement::THIS_MONTH)); - $this->assertEqualsCanonicalizing(['2023-01-01','2023-03-31'], $this->getDateRange(ClientStatement::THIS_QUARTER)); - $this->assertEqualsCanonicalizing(['2023-01-01','2023-12-31'], $this->getDateRange(ClientStatement::THIS_YEAR)); + $this->assertEqualsCanonicalizing(['2023-01-01','2023-01-31'], $this->getDateRange(EmailStatement::THIS_MONTH)); + $this->assertEqualsCanonicalizing(['2023-01-01','2023-03-31'], $this->getDateRange(EmailStatement::THIS_QUARTER)); + $this->assertEqualsCanonicalizing(['2023-01-01','2023-12-31'], $this->getDateRange(EmailStatement::THIS_YEAR)); - $this->assertEqualsCanonicalizing(['2022-12-01','2022-12-31'], $this->getDateRange(ClientStatement::LAST_MONTH)); - $this->assertEqualsCanonicalizing(['2022-10-01','2022-12-31'], $this->getDateRange(ClientStatement::LAST_QUARTER)); - $this->assertEqualsCanonicalizing(['2022-01-01','2022-12-31'], $this->getDateRange(ClientStatement::LAST_YEAR)); + $this->assertEqualsCanonicalizing(['2022-12-01','2022-12-31'], $this->getDateRange(EmailStatement::LAST_MONTH)); + $this->assertEqualsCanonicalizing(['2022-10-01','2022-12-31'], $this->getDateRange(EmailStatement::LAST_QUARTER)); + $this->assertEqualsCanonicalizing(['2022-01-01','2022-12-31'], $this->getDateRange(EmailStatement::LAST_YEAR)); $this->travelBack(); } @@ -338,16 +338,16 @@ class SchedulerTest extends TestCase private function getDateRange($range) { return match ($range) { - ClientStatement::LAST7 => [now()->startOfDay()->subDays(7)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], - ClientStatement::LAST30 => [now()->startOfDay()->subDays(30)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], - ClientStatement::LAST365 => [now()->startOfDay()->subDays(365)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], - ClientStatement::THIS_MONTH => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], - ClientStatement::LAST_MONTH => [now()->startOfDay()->subMonthNoOverflow()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->subMonthNoOverflow()->lastOfMonth()->format('Y-m-d')], - ClientStatement::THIS_QUARTER => [now()->startOfDay()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->lastOfQuarter()->format('Y-m-d')], - ClientStatement::LAST_QUARTER => [now()->startOfDay()->subQuarterNoOverflow()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->subQuarterNoOverflow()->lastOfQuarter()->format('Y-m-d')], - ClientStatement::THIS_YEAR => [now()->startOfDay()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->lastOfYear()->format('Y-m-d')], - ClientStatement::LAST_YEAR => [now()->startOfDay()->subYearNoOverflow()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->subYearNoOverflow()->lastOfYear()->format('Y-m-d')], - ClientStatement::CUSTOM_RANGE => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']], + EmailStatement::LAST7 => [now()->startOfDay()->subDays(7)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + EmailStatement::LAST30 => [now()->startOfDay()->subDays(30)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + EmailStatement::LAST365 => [now()->startOfDay()->subDays(365)->format('Y-m-d'), now()->startOfDay()->format('Y-m-d')], + EmailStatement::THIS_MONTH => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], + EmailStatement::LAST_MONTH => [now()->startOfDay()->subMonthNoOverflow()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->subMonthNoOverflow()->lastOfMonth()->format('Y-m-d')], + EmailStatement::THIS_QUARTER => [now()->startOfDay()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->lastOfQuarter()->format('Y-m-d')], + EmailStatement::LAST_QUARTER => [now()->startOfDay()->subQuarterNoOverflow()->firstOfQuarter()->format('Y-m-d'), now()->startOfDay()->subQuarterNoOverflow()->lastOfQuarter()->format('Y-m-d')], + EmailStatement::THIS_YEAR => [now()->startOfDay()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->lastOfYear()->format('Y-m-d')], + EmailStatement::LAST_YEAR => [now()->startOfDay()->subYearNoOverflow()->firstOfYear()->format('Y-m-d'), now()->startOfDay()->subYearNoOverflow()->lastOfYear()->format('Y-m-d')], + EmailStatement::CUSTOM_RANGE => [$this->scheduler->parameters['start_date'], $this->scheduler->parameters['end_date']], default => [now()->startOfDay()->firstOfMonth()->format('Y-m-d'), now()->startOfDay()->lastOfMonth()->format('Y-m-d')], }; } @@ -360,7 +360,7 @@ class SchedulerTest extends TestCase 'next_run' => now()->format('Y-m-d'), 'template' => 'client_statement', 'parameters' => [ - 'date_range' => ClientStatement::LAST_MONTH, + 'date_range' => EmailStatement::LAST_MONTH, 'show_payments_table' => true, 'show_aging_table' => true, 'status' => 'paid', From 7d07cfb2f7009f8ebc3a0026c8e47289f1f6d440 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sat, 18 Feb 2023 08:12:43 +1100 Subject: [PATCH 71/72] Minor fixes for types --- lang/en/texts.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lang/en/texts.php b/lang/en/texts.php index 7c3a28af4e1b..96c46d70285d 100644 --- a/lang/en/texts.php +++ b/lang/en/texts.php @@ -4952,7 +4952,8 @@ $LANG = [ 'update_payment' => 'Update Payment', 'markup' => 'Markup', 'unlock_pro' => 'Unlock Pro', - 'preferences' => 'Preferences' + 'preferences' => 'Preferences', + 'click_to_variables' => 'Client here to see all variables.', ]; From e28b75e83fc98dd8e6c0f89d0b8043b947a7205c Mon Sep 17 00:00:00 2001 From: David Bomba Date: Sat, 18 Feb 2023 08:36:51 +1100 Subject: [PATCH 72/72] phpcs --- app/Events/Invoice/InvoiceWasPaid.php | 1 - .../Controllers/BankTransactionController.php | 1 - app/Jobs/Entity/CreateEntityPdf.php | 1 - app/Jobs/Ledger/ClientLedgerBalanceUpdate.php | 4 +- app/Jobs/Util/WebhookSingle.php | 6 +- .../Credit/CreditCreatedNotification.php | 1 - .../Credit/CreditEmailedNotification.php | 2 - app/Listeners/Invoice/InvoicePaidActivity.php | 1 - .../Quote/QuoteEmailedNotification.php | 3 - .../AppStoreRenewSubscription.php | 1 - .../PlayStoreRenewSubscription.php | 8 +-- app/Mail/Admin/EntityPaidObject.php | 2 +- app/Mail/Engine/PaymentEmailEngine.php | 1 - app/Models/CompanyGateway.php | 2 +- app/Models/CreditInvitation.php | 1 - app/Models/QuoteInvitation.php | 2 - app/Models/Scheduler.php | 2 - app/PaymentDrivers/BaseDriver.php | 70 +++++++------------ app/Services/Email/EmailObject.php | 6 +- app/Services/Email/MailEntity.php | 2 - app/Services/Scheduler/SchedulerService.php | 10 +-- app/Utils/Number.php | 13 ++-- 22 files changed, 49 insertions(+), 91 deletions(-) diff --git a/app/Events/Invoice/InvoiceWasPaid.php b/app/Events/Invoice/InvoiceWasPaid.php index af1ff64011fa..dffe4343d2c2 100644 --- a/app/Events/Invoice/InvoiceWasPaid.php +++ b/app/Events/Invoice/InvoiceWasPaid.php @@ -48,5 +48,4 @@ class InvoiceWasPaid $this->company = $company; $this->event_vars = $event_vars; } - } diff --git a/app/Http/Controllers/BankTransactionController.php b/app/Http/Controllers/BankTransactionController.php index 3967a969750e..ff223acdf0cf 100644 --- a/app/Http/Controllers/BankTransactionController.php +++ b/app/Http/Controllers/BankTransactionController.php @@ -468,7 +468,6 @@ class BankTransactionController extends BaseController $bank_transactions = BankTransaction::withTrashed()->whereIn('id', $this->transformKeys($ids))->company()->get(); if ($action == 'convert_matched') { //catch this action - $this->bank_transaction_repo->convert_matched($bank_transactions); } else { $bank_transactions->each(function ($bank_transaction, $key) use ($action) { diff --git a/app/Jobs/Entity/CreateEntityPdf.php b/app/Jobs/Entity/CreateEntityPdf.php index 9217bdce5967..9bdb48f53767 100644 --- a/app/Jobs/Entity/CreateEntityPdf.php +++ b/app/Jobs/Entity/CreateEntityPdf.php @@ -13,7 +13,6 @@ namespace App\Jobs\Entity; use App\Exceptions\FilePermissionsFailure; use App\Libraries\MultiDB; -use App\Models\Account; use App\Models\Credit; use App\Models\CreditInvitation; use App\Models\Design; diff --git a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php index 8dc45cf74f8d..d3293116a6c1 100644 --- a/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php +++ b/app/Jobs/Ledger/ClientLedgerBalanceUpdate.php @@ -28,7 +28,8 @@ class ClientLedgerBalanceUpdate implements ShouldQueue public $tries = 1; public $deleteWhenMissingModels = true; public function __construct(public Company $company, public Client $client) - {} + { + } /** * Execute the job. @@ -68,5 +69,4 @@ class ClientLedgerBalanceUpdate implements ShouldQueue { return [(new WithoutOverlapping($this->client->id))->dontRelease()]; } - } diff --git a/app/Jobs/Util/WebhookSingle.php b/app/Jobs/Util/WebhookSingle.php index 23749f84c64e..dc4f8314c39c 100644 --- a/app/Jobs/Util/WebhookSingle.php +++ b/app/Jobs/Util/WebhookSingle.php @@ -158,8 +158,8 @@ class WebhookSingle implements ShouldQueue $this->company ))->handle(); - /* Some 400's should never be repeated */ - if(in_array($e->getResponse()->getStatusCode(), [404, 410])){ + /* Some 400's should never be repeated */ + if (in_array($e->getResponse()->getStatusCode(), [404, 410])) { $this->fail(); return; } @@ -227,7 +227,6 @@ class WebhookSingle implements ShouldQueue private function resolveClient() { - //make sure it isn't an instance of the Client Model if (!$this->entity instanceof \App\Models\Client && !$this->entity instanceof \App\Models\Vendor && @@ -238,7 +237,6 @@ class WebhookSingle implements ShouldQueue } return null; - } public function failed($exception = null) diff --git a/app/Listeners/Credit/CreditCreatedNotification.php b/app/Listeners/Credit/CreditCreatedNotification.php index 19aca5a7c708..5c7b0350412b 100644 --- a/app/Listeners/Credit/CreditCreatedNotification.php +++ b/app/Listeners/Credit/CreditCreatedNotification.php @@ -67,7 +67,6 @@ class CreditCreatedNotification implements ShouldQueue $nmo->to_user = $user; (new NinjaMailerJob($nmo))->handle(); - } /* Override the methods in the Notification Class */ diff --git a/app/Listeners/Credit/CreditEmailedNotification.php b/app/Listeners/Credit/CreditEmailedNotification.php index db09b5a6ae70..1d04798b81c6 100644 --- a/app/Listeners/Credit/CreditEmailedNotification.php +++ b/app/Listeners/Credit/CreditEmailedNotification.php @@ -63,9 +63,7 @@ class CreditEmailedNotification implements ShouldQueue $nmo->to_user = $user; (new NinjaMailerJob($nmo))->handle(); - } - } } } diff --git a/app/Listeners/Invoice/InvoicePaidActivity.php b/app/Listeners/Invoice/InvoicePaidActivity.php index f2d64a0c8103..13cb70222beb 100644 --- a/app/Listeners/Invoice/InvoicePaidActivity.php +++ b/app/Listeners/Invoice/InvoicePaidActivity.php @@ -56,6 +56,5 @@ class InvoicePaidActivity implements ShouldQueue if ($event->invoice->subscription()->exists()) { $event->invoice->subscription->service()->planPaid($event->invoice); } - } } diff --git a/app/Listeners/Quote/QuoteEmailedNotification.php b/app/Listeners/Quote/QuoteEmailedNotification.php index 296e7df119d0..828941ced506 100644 --- a/app/Listeners/Quote/QuoteEmailedNotification.php +++ b/app/Listeners/Quote/QuoteEmailedNotification.php @@ -16,7 +16,6 @@ use App\Jobs\Mail\NinjaMailerJob; use App\Jobs\Mail\NinjaMailerObject; use App\Libraries\MultiDB; use App\Mail\Admin\EntitySentObject; -use App\Notifications\Admin\EntitySentNotification; use App\Utils\Traits\Notifications\UserNotifies; use Illuminate\Contracts\Queue\ShouldQueue; @@ -62,9 +61,7 @@ class QuoteEmailedNotification implements ShouldQueue $nmo->to_user = $user; (new NinjaMailerJob($nmo))->handle(); - } - } } } diff --git a/app/Listeners/Subscription/AppStoreRenewSubscription.php b/app/Listeners/Subscription/AppStoreRenewSubscription.php index 8b6ee587dae0..07e5c493f9b3 100644 --- a/app/Listeners/Subscription/AppStoreRenewSubscription.php +++ b/app/Listeners/Subscription/AppStoreRenewSubscription.php @@ -58,6 +58,5 @@ class AppStoreRenewSubscription implements ShouldQueue } $account->save(); - } } diff --git a/app/Listeners/Subscription/PlayStoreRenewSubscription.php b/app/Listeners/Subscription/PlayStoreRenewSubscription.php index 75a1561c9151..49ec9805d6fc 100644 --- a/app/Listeners/Subscription/PlayStoreRenewSubscription.php +++ b/app/Listeners/Subscription/PlayStoreRenewSubscription.php @@ -11,12 +11,12 @@ namespace App\Listeners\Subscription; -use Carbon\Carbon; +use App\Libraries\MultiDB; use App\Models\Account; use App\Models\Company; -use App\Libraries\MultiDB; -use Illuminate\Contracts\Queue\ShouldQueue; use App\Notifications\Ninja\RenewalFailureNotification; +use Carbon\Carbon; +use Illuminate\Contracts\Queue\ShouldQueue; use Imdhemy\Purchases\Events\GooglePlay\SubscriptionRenewed; class PlayStoreRenewSubscription implements ShouldQueue @@ -44,6 +44,4 @@ class PlayStoreRenewSubscription implements ShouldQueue return; } } - - } diff --git a/app/Mail/Admin/EntityPaidObject.php b/app/Mail/Admin/EntityPaidObject.php index aa806d66e4a6..ef7edd284e33 100644 --- a/app/Mail/Admin/EntityPaidObject.php +++ b/app/Mail/Admin/EntityPaidObject.php @@ -12,11 +12,11 @@ namespace App\Mail\Admin; use App\Mail\Engine\PaymentEmailEngine; +use App\Models\Payment; use App\Utils\Ninja; use App\Utils\Number; use Illuminate\Support\Facades\App; use stdClass; -use App\Models\Payment; class EntityPaidObject { diff --git a/app/Mail/Engine/PaymentEmailEngine.php b/app/Mail/Engine/PaymentEmailEngine.php index a8f7d44f46d7..eb2f10735d4d 100644 --- a/app/Mail/Engine/PaymentEmailEngine.php +++ b/app/Mail/Engine/PaymentEmailEngine.php @@ -388,7 +388,6 @@ class PaymentEmailEngine extends BaseEmailEngine */ private function buildViewButton(string $link, string $text): string { - return '
- + {{ $view_text }}
- + @if($logo) alt_text - + @endif