diff --git a/app/Models/Account.php b/app/Models/Account.php index 6bceb23d8f..d3c2f24260 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -470,6 +470,13 @@ class Account extends Eloquent return Document::getDirectFileUrl($this->logo, $this->getLogoDisk()); } + public function getPrimaryUser() + { + return $this->users() + ->orderBy('id') + ->first(); + } + public function getToken($userId, $name) { foreach ($this->account_tokens as $token) { diff --git a/app/Models/Client.php b/app/Models/Client.php index 4b26f40df0..6d2b44fbac 100644 --- a/app/Models/Client.php +++ b/app/Models/Client.php @@ -199,6 +199,13 @@ class Client extends EntityModel return $this->name; } + public function getPrimaryContact() + { + return $this->contacts() + ->whereIsPrimary(true) + ->first(); + } + public function getDisplayName() { if ($this->name) { diff --git a/app/Ninja/Repositories/AccountRepository.php b/app/Ninja/Repositories/AccountRepository.php index f5d401619e..b57efffdcd 100644 --- a/app/Ninja/Repositories/AccountRepository.php +++ b/app/Ninja/Repositories/AccountRepository.php @@ -333,28 +333,42 @@ class AccountRepository { $account->load('users'); $ninjaAccount = $this->getNinjaAccount(); - $client = Client::whereAccountId($ninjaAccount->id)->wherePublicId($account->id)->first(); + $ninjaUser = $ninjaAccount->getPrimaryUser(); + $client = Client::whereAccountId($ninjaAccount->id) + ->wherePublicId($account->id) + ->first(); + $clientExists = $client ? true : false; if (!$client) { $client = new Client(); $client->public_id = $account->id; - $client->user_id = $ninjaAccount->users()->first()->id; + $client->account_id = $ninjaAccount->id; + $client->user_id = $ninjaUser->id; $client->currency_id = 1; - foreach (['name', 'address1', 'address2', 'city', 'state', 'postal_code', 'country_id', 'work_phone', 'language_id', 'vat_number'] as $field) { - $client->$field = $account->$field; - } - $ninjaAccount->clients()->save($client); + } + + foreach (['name', 'address1', 'address2', 'city', 'state', 'postal_code', 'country_id', 'work_phone', 'language_id', 'vat_number'] as $field) { + $client->$field = $account->$field; + } + + $client->save(); + if ($clientExists) { + $contact = $client->getPrimaryContact(); + } else { $contact = new Contact(); - $contact->user_id = $ninjaAccount->users()->first()->id; + $contact->user_id = $ninjaUser->id; $contact->account_id = $ninjaAccount->id; $contact->public_id = $account->id; $contact->is_primary = true; - foreach (['first_name', 'last_name', 'email', 'phone'] as $field) { - $contact->$field = $account->users()->first()->$field; - } - $client->contacts()->save($contact); } + + $user = $account->getPrimaryUser(); + foreach (['first_name', 'last_name', 'email', 'phone'] as $field) { + $contact->$field = $user->$field; + } + + $client->contacts()->save($contact); return $client; }