Add fix for vendor contacts in check data script

This commit is contained in:
David Bomba 2022-02-22 22:58:04 +11:00
parent 25a6b7b4f6
commit abf6aa0a0b

View File

@ -13,6 +13,7 @@ namespace App\Console\Commands;
use App;
use App\Factory\ClientContactFactory;
use App\Factory\VendorContactFactory;
use App\Models\Account;
use App\Models\Client;
use App\Models\ClientContact;
@ -72,7 +73,7 @@ class CheckData extends Command
/**
* @var string
*/
protected $signature = 'ninja:check-data {--database=} {--fix=} {--client_id=} {--paid_to_date=} {--client_balance=}';
protected $signature = 'ninja:check-data {--database=} {--fix=} {--client_id=} {--vendor_id=} {--paid_to_date=} {--client_balance=}';
/**
* @var string
@ -112,6 +113,7 @@ class CheckData extends Command
$this->checkClientBalances();
$this->checkContacts();
$this->checkVendorContacts();
$this->checkEntityInvitations();
$this->checkCompanyData();
@ -248,6 +250,65 @@ class CheckData extends Command
}
private function checkVendorContacts()
{
// check for contacts with the contact_key value set
$contacts = DB::table('vendor_contacts')
->whereNull('contact_key')
->orderBy('id')
->get(['id']);
$this->logMessage($contacts->count().' contacts without a contact_key');
if ($contacts->count() > 0) {
$this->isValid = false;
}
if ($this->option('fix') == 'true') {
foreach ($contacts as $contact) {
DB::table('vendor_contacts')
->where('id', '=', $contact->id)
->whereNull('contact_key')
->update([
'contact_key' => Str::random(config('ninja.key_length')),
]);
}
}
// check for missing contacts
$vendors = DB::table('vendors')
->leftJoin('vendor_contacts', function ($join) {
$join->on('vendor_contacts.vendor_id', '=', 'vendors.id')
->whereNull('vendor_contacts.deleted_at');
})
->groupBy('vendors.id', 'vendors.user_id', 'vendors.company_id')
->havingRaw('count(vendor_contacts.id) = 0');
if ($this->option('vendor_id')) {
$vendors->where('vendors.id', '=', $this->option('vendor_id'));
}
$vendors = $vendors->get(['vendors.id', 'vendors.user_id', 'vendors.company_id']);
$this->logMessage($vendors->count().' vendors without any contacts');
if ($vendors->count() > 0) {
$this->isValid = false;
}
if ($this->option('fix') == 'true') {
foreach ($vendors as $vendor) {
$this->logMessage("Fixing missing vendor contacts #{$vendor->id}");
$new_contact = VendorContactFactory::create($vendor->company_id, $vendor->user_id);
$new_contact->vendor_id = $vendor->id;
$new_contact->contact_key = Str::random(40);
$new_contact->is_primary = true;
$new_contact->save();
}
}
}
private function checkFailedJobs()
{
if (config('ninja.testvars.travis')) {