1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-13 14:42:42 +01:00
invoiceninja/app/Repositories/ClientContactRepository.php

72 lines
1.6 KiB
PHP
Raw Normal View History

<?php
2019-05-11 05:32:07 +02: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
*/
namespace App\Repositories;
use App\Models\Client;
use App\Models\ClientContact;
2019-10-02 11:40:32 +02:00
use Illuminate\Support\Str;
/**
2019-05-10 08:08:33 +02:00
* ClientContactRepository
*/
class ClientContactRepository extends BaseRepository
{
2019-03-27 09:38:01 +01:00
public function save($contacts, Client $client) : void
{
/* Convert array to collection */
$contacts = collect($contacts);
/* Get array of IDs which have been removed from the contacts array and soft delete each contact */
collect($client->contacts->pluck('id'))->diff($contacts->pluck('id'))->each(function($contact){
2019-05-10 08:08:33 +02:00
ClientContact::destroy($contact);
2019-05-10 08:08:33 +02:00
});
/* Set first record to primary - always*/
$contacts = $contacts->sortBy('is_primary');
$contacts->first(function($contact){
2019-05-10 08:08:33 +02:00
$contact['is_primary'] = true;
2019-10-02 09:40:10 +02:00
// $contact->save();
2019-05-10 08:08:33 +02:00
});
//loop and update/create contacts
$contacts->each(function ($contact) use ($client){
2019-10-02 09:52:38 +02:00
$update_contact = null;
2019-10-02 09:52:38 +02:00
if(isset($contact['id']))
$update_contact = ClientContact::find($this->decodePrimaryKey($contact['id']));
if(!$update_contact){
$update_contact = new ClientContact;
$update_contact->client_id = $client->id;
$update_contact->company_id = $client->company_id;
$update_contact->user_id = $client->user_id;
2019-10-02 11:40:32 +02:00
$update_contact->contact_key = Str::random(40);
2019-10-02 09:52:38 +02:00
}
$update_contact->fill($contact);
2019-05-10 08:08:33 +02:00
$update_contact->save();
});
}
}