From 82888cccff9c1408555409219efae0c88ee75ba1 Mon Sep 17 00:00:00 2001 From: David Bomba Date: Mon, 29 Jan 2024 14:03:54 +1100 Subject: [PATCH] Adjustments for logic for sending payment emails --- app/Jobs/Payment/EmailPayment.php | 2 +- app/Services/Payment/SendEmail.php | 26 +++++++++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/app/Jobs/Payment/EmailPayment.php b/app/Jobs/Payment/EmailPayment.php index e79cf8c73cb4..0c15d43d17cd 100644 --- a/app/Jobs/Payment/EmailPayment.php +++ b/app/Jobs/Payment/EmailPayment.php @@ -68,7 +68,7 @@ class EmailPayment implements ShouldQueue $this->payment->load('invoices'); if (!$this->contact) { - $this->contact = $this->payment->client->contacts()->first(); + $this->contact = $this->payment->client->contacts()->orderBy('is_primary', 'desc')->first(); } $this->contact->load('client'); diff --git a/app/Services/Payment/SendEmail.php b/app/Services/Payment/SendEmail.php index eda37583ef0e..bb0872706dfc 100644 --- a/app/Services/Payment/SendEmail.php +++ b/app/Services/Payment/SendEmail.php @@ -14,22 +14,38 @@ namespace App\Services\Payment; use App\Jobs\Payment\EmailPayment; use App\Models\ClientContact; use App\Models\Payment; +use Illuminate\Database\QueryException; class SendEmail { - public function __construct(public Payment $payment, public ?ClientContact $contact) - { - } + public function __construct(public Payment $payment, public ?ClientContact $contact) {} /** * Builds the correct template to send. */ public function run() { - $this->payment->load('company', 'client.contacts', 'invoices'); + $this->payment->load('company', 'invoices'); if (!$this->contact) { - $this->contact = $this->payment->client->contacts()->first(); + + if($invoice = $this->payment->invoices->first() ?? false) { + + $invitation = + $invoice + ->invitations() + ->whereHas("contact", function ($q) { + $q->where('send_email', true)->orderBy("is_primary", 'ASC'); + }) + ->first(); + + if($invitation) { + $this->contact = $invitation->contact; + } else { + $this->contact = $this->payment->client->contacts()->orderBy('send_email', 'desc')->orderBy('is_primary', 'desc')->first(); + } + } + } EmailPayment::dispatch($this->payment, $this->payment->company, $this->contact);