From f03b73dc75ba0a8c3775f3333368afa61353ffb2 Mon Sep 17 00:00:00 2001 From: Antoine Le Gonidec Date: Fri, 5 Jul 2024 18:03:05 +0200 Subject: [PATCH] Restrict the Customers shown during auto-completion of the "To:" field --- src/Http/Controllers/CustomersController.php | 41 ++++++++++++-------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/src/Http/Controllers/CustomersController.php b/src/Http/Controllers/CustomersController.php index 53f994d..41d7e0d 100644 --- a/src/Http/Controllers/CustomersController.php +++ b/src/Http/Controllers/CustomersController.php @@ -246,23 +246,32 @@ class CustomersController extends BaseCustomersController { } } - if ($request->search_by == 'all' || $request->search_by == 'email') { - $customers_query->where('emails.email', 'like', '%'.$q.'%'); - } - if ($request->exclude_email) { - $customers_query->where('emails.email', '<>', $request->exclude_email); - } - if ($request->search_by == 'all' || $request->search_by == 'name') { - $customers_query->orWhere('first_name', 'like', '%'.$q.'%') - ->orWhere('last_name', 'like', '%'.$q.'%'); - } - if ($request->search_by == 'phone') { - $phone_numeric = \Helper::phoneToNumeric($q); - if (!$phone_numeric) { - $phone_numeric = $q; + // Group the search terms query to avoid them from messing up the restriction by Mailbox. + $customers_query->where(function($customers_query) use($request, $q) { + if ($request->search_by == 'all' || $request->search_by == 'email') { + $customers_query->where('emails.email', 'like', '%'.$q.'%'); + if ($request->exclude_email) { + $customers_query->where('emails.email', '<>', $request->exclude_email); } - $customers_query->where('customers.phones', 'like', '%'.$phone_numeric.'%'); - } + if ($request->search_by == 'all' || $request->search_by == 'name') { + $customers_query->orWhere('first_name', 'like', '%'.$q.'%') + ->orWhere('last_name', 'like', '%'.$q.'%'); + } + if ($request->search_by == 'phone') { + $phone_numeric = \Helper::phoneToNumeric($q); + if (!$phone_numeric) { + $phone_numeric = $q; + } + $customers_query->where('customers.phones', 'like', '%'.$phone_numeric.'%'); + } + }); + + // Get the list of Mailboxes the current User has access to. + $user = auth()->user(); + $mailboxes = $user->mailboxesIdsCanView(); + + // Restrict the query to the Customers the current User is allowed to access. + $customers_query->whereIn('customers.mailbox_id', $mailboxes); $customers = $customers_query->paginate(20);