diff --git a/src/Customer.php b/src/Customer.php index bafe77d..1216db5 100644 --- a/src/Customer.php +++ b/src/Customer.php @@ -6,7 +6,6 @@ namespace MillionsMissingFrance\FreescoutRestrictedCustomers; -use App\Email; use App\CustomerChannel; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Hash; @@ -105,4 +104,80 @@ class Customer extends BaseCustomer { $this->save(); } } + + /** + * Set customer emails. + * + * @param array $emails + */ + public function syncEmails($emails) { + if (is_array($emails)) { + $deleted_emails = []; + foreach ($this->emails as $email) { + foreach ($emails as $email_address) { + if (Email::sanitizeEmail($email->email) == Email::sanitizeEmail($email_address)) { + continue 2; + } + } + $deleted_emails[] = $email; + } + $mailbox = $this->mailbox; + foreach ($emails as $email_address) { + $email_address = Email::sanitizeEmail($email_address); + if (!$email_address) { + continue; + } + $email = Email + ::whereInMailbox($mailbox) + ->where('email', $email_address) + ->first(); + $new_emails = []; + if ($email) { + // Assign email to current customer + if ($email->customer_id != $this->id) { + $email->customer()->associate($this); + $email->save(); + } + } else { + $new_emails[] = new Email(['email' => $email_address]); + } + if ($new_emails) { + $this->emails()->saveMany($new_emails); + } + } + + foreach ($deleted_emails as $email) { + if (Conversation::where('customer_email', $email->email)->exists()) { + // Create customers for deleted emails + // if there is a conversation with 'customer_email'. + $customer = new self(); + $customer->save(); + $email->customer()->associate($customer); + $email->save(); + } else { + // Simply delete an email. + $email->delete(); + } + } + } + } + + /** + * Add new email to customer. + */ + public function addEmail($email_address, $check_if_exists = false) { + // Check if email already exists and belongs to another customer. + if ($check_if_exists) { + $mailbox = $this->mailbox; + $email = Email + ::whereInMailbox($mailbox) + ->where('email', $email_address) + ->first(); + if ($email && !empty($email->customer_id)) { + return false; + } + } + $new_email = new Email(['email' => $email_address]); + $this->emails()->save($new_email); + } } diff --git a/src/Email.php b/src/Email.php index 1b53955..fd8deb5 100644 --- a/src/Email.php +++ b/src/Email.php @@ -28,4 +28,19 @@ class Email extends BaseEmail { ->count(); return ( $emails_count != 0 ); } + + /** + * Return a query limited to a specific Mailbox + * + * @param Mailbox $mailbox + * + * @return QueryBuilder + */ + public static function whereInMailbox($mailbox) { + $query = self + ::whereHas('customer', function($query) use($mailbox) { + $query->where('mailbox_id', '=', $mailbox->id); + }); + return $query; + } }