Prevent the setting of an e-mail from a Customer from "stealing" it from other Customers

This commit is contained in:
Antoine Le Gonidec 2024-07-09 14:38:11 +02:00
parent 3a6de55d19
commit a2ee787747
Signed by: vv221
GPG key ID: 636B78F91CEB80D8
2 changed files with 91 additions and 1 deletions

View file

@ -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);
}
}

View file

@ -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;
}
}