From 764310eefd8cdda8d3cb4f3914d83924b411ca6d Mon Sep 17 00:00:00 2001 From: Hillel Coren Date: Mon, 24 Apr 2017 16:41:36 +0300 Subject: [PATCH] Add contact checks to check-data command --- app/Console/Commands/CheckData.php | 58 ++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/app/Console/Commands/CheckData.php b/app/Console/Commands/CheckData.php index f5d10a5bd901..f96e64b218b1 100644 --- a/app/Console/Commands/CheckData.php +++ b/app/Console/Commands/CheckData.php @@ -9,6 +9,7 @@ use Illuminate\Console\Command; use Mail; use Symfony\Component\Console\Input\InputOption; use Utils; +use App\Models\Contact; /* @@ -68,6 +69,7 @@ class CheckData extends Command } $this->checkBalances(); + $this->checkContacts(); if (! $this->option('client_id')) { $this->checkFailedJobs(); @@ -95,6 +97,62 @@ class CheckData extends Command $this->log .= $str . "\n"; } + private function checkContacts() + { + $clients = DB::table('clients') + ->leftJoin('contacts', function($join) { + $join->on('contacts.client_id', '=', 'clients.id') + ->whereNull('contacts.deleted_at'); + }) + ->groupBy('clients.id', 'clients.user_id', 'clients.account_id') + ->havingRaw('count(contacts.id) = 0'); + + if ($this->option('client_id')) { + $clients->where('clients.id', '=', $this->option('client_id')); + } + + $clients = $clients->get(['clients.id', 'clients.user_id', 'clients.account_id']); + $this->logMessage(count($clients) . ' clients without any contacts'); + + if (count($clients) > 0) { + $this->isValid = false; + } + + if ($this->option('fix') == 'true') { + foreach ($clients as $client) { + $contact = new Contact(); + $contact->account_id = $client->account_id; + $contact->user_id = $client->user_id; + $contact->client_id = $client->id; + $contact->is_primary = true; + $contact->send_invoice = true; + $contact->contact_key = strtolower(str_random(RANDOM_KEY_LENGTH)); + $contact->public_id = Contact::whereAccountId($client->account_id)->withTrashed()->max('public_id') + 1; + $contact->save(); + } + } + + $clients = DB::table('clients') + ->leftJoin('contacts', function($join) { + $join->on('contacts.client_id', '=', 'clients.id') + ->where('contacts.is_primary', '=', true) + ->whereNull('contacts.deleted_at'); + }) + ->groupBy('clients.id') + ->havingRaw('count(contacts.id) != 1'); + + if ($this->option('client_id')) { + $clients->where('clients.id', '=', $this->option('client_id')); + } + + $clients = $clients->get(['clients.id', DB::raw('count(contacts.id)')]); + $this->logMessage(count($clients) . ' clients without a single primary contact'); + + if (count($clients) > 0) { + $this->isValid = false; + } + } + private function checkFailedJobs() { $count = DB::table('failed_jobs')->count();