From aa9c1624a1fc423a284a7959e24f3286ea6e210a Mon Sep 17 00:00:00 2001 From: Antoine Le Gonidec Date: Mon, 8 Jul 2024 12:44:40 +0200 Subject: [PATCH] On initial install, link existing Customers to Mailboxes The link is set only for Customers that are linked to exactly one Mailbox, through the Conversations they are linked to. --- ...d_mailbox_id_column_to_customers_table.php | 5 +++++ src/Customer.php | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/database/migrations/2024_07_03_135202_add_mailbox_id_column_to_customers_table.php b/database/migrations/2024_07_03_135202_add_mailbox_id_column_to_customers_table.php index 692a22a..9411efb 100644 --- a/database/migrations/2024_07_03_135202_add_mailbox_id_column_to_customers_table.php +++ b/database/migrations/2024_07_03_135202_add_mailbox_id_column_to_customers_table.php @@ -30,6 +30,11 @@ class AddMailboxIdColumnToCustomersTable extends Migration { // On mailbox deletion, delete all customer entries that are linked to it. ->onDelete('cascade'); }); + // Link Customers to Mailboxes, through their Conversation information. + $customers = Customer::all(); + $customers->each(function ($customer) { + $customer->linkToMailboxThroughConversations(); + }); } /** diff --git a/src/Customer.php b/src/Customer.php index 6ee213d..064d21d 100644 --- a/src/Customer.php +++ b/src/Customer.php @@ -82,4 +82,26 @@ class Customer extends BaseCustomer { ->whereIn('mailbox_id', $mailboxes) ->first($columns); } + + /** + * Get the Mailboxes this Customer is linked to through Conversations. + * + * @return array + */ + public function mailboxesThroughConversations() { + return $this + ->conversations + ->pluck('mailbox'); + } + + /** + * If this Customer is linked to a single Mailbox through Conversations, link it to it. + */ + public function linkToMailboxThroughConversations() { + $mailboxes = $this->mailboxesThroughConversations(); + if ( $mailboxes->count() == 1 ) { + $this->mailbox_id = $mailboxes->first()->id; + $this->save(); + } + } }