2018-11-22 22:12:41 +11:00
|
|
|
<?php
|
2019-05-11 13:32:07 +10:00
|
|
|
/**
|
|
|
|
|
* Invoice Ninja (https://invoiceninja.com)
|
|
|
|
|
*
|
|
|
|
|
* @link https://github.com/invoiceninja/invoiceninja source repository
|
|
|
|
|
*
|
|
|
|
|
* @copyright Copyright (c) 2019. Invoice Ninja LLC (https://invoiceninja.com)
|
|
|
|
|
*
|
|
|
|
|
* @license https://opensource.org/licenses/AAL
|
|
|
|
|
*/
|
2018-11-22 22:12:41 +11:00
|
|
|
|
|
|
|
|
namespace App\Repositories;
|
|
|
|
|
|
2018-11-27 17:59:16 +11:00
|
|
|
use App\Models\Client;
|
|
|
|
|
use App\Models\ClientContact;
|
|
|
|
|
|
2018-11-22 22:12:41 +11:00
|
|
|
/**
|
2019-05-10 16:08:33 +10:00
|
|
|
* ClientContactRepository
|
2018-11-22 22:12:41 +11:00
|
|
|
*/
|
|
|
|
|
class ClientContactRepository extends BaseRepository
|
|
|
|
|
{
|
|
|
|
|
|
2019-03-27 19:38:01 +11:00
|
|
|
public function save($contacts, Client $client) : void
|
2018-11-22 22:12:41 +11:00
|
|
|
{
|
|
|
|
|
|
2018-11-27 17:59:16 +11:00
|
|
|
/* Convert array to collection */
|
|
|
|
|
$contacts = collect($contacts);
|
|
|
|
|
|
|
|
|
|
/* Get array of IDs which have been removed from the contacts array and soft delete each contact */
|
2018-12-07 21:57:20 +11:00
|
|
|
collect($client->contacts->pluck('id'))->diff($contacts->pluck('id'))->each(function($contact){
|
2019-05-10 16:08:33 +10:00
|
|
|
|
2018-11-27 17:59:16 +11:00
|
|
|
ClientContact::destroy($contact);
|
2019-05-10 16:08:33 +10:00
|
|
|
|
2018-11-27 17:59:16 +11:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
/* Set first record to primary - always*/
|
|
|
|
|
$contacts = $contacts->sortBy('is_primary');
|
|
|
|
|
|
|
|
|
|
$contacts->first(function($contact){
|
2019-05-10 16:08:33 +10:00
|
|
|
|
2018-11-27 17:59:16 +11:00
|
|
|
$contact['is_primary'] = true;
|
2019-05-06 15:34:59 +10:00
|
|
|
$contact->save();
|
2019-05-10 16:08:33 +10:00
|
|
|
|
2018-11-27 17:59:16 +11:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
//loop and update/create contacts
|
|
|
|
|
$contacts->each(function ($contact) use ($client){
|
|
|
|
|
|
|
|
|
|
$update_contact = ClientContact::firstOrNew(
|
|
|
|
|
['id' => $contact['id']],
|
|
|
|
|
[
|
|
|
|
|
'client_id' => $client->id,
|
2019-01-25 21:47:23 +11:00
|
|
|
'company_id' => $client->company_id,
|
|
|
|
|
'user_id' => auth()->user()->id
|
2018-11-27 17:59:16 +11:00
|
|
|
]
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
$update_contact->fill($contact);
|
2019-05-10 16:08:33 +10:00
|
|
|
|
2018-11-27 17:59:16 +11:00
|
|
|
$update_contact->save();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
2018-11-22 22:12:41 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|