101 lines
3.0 KiB
PHP
101 lines
3.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Repositories;
|
|
|
|
use App\Models\Client;
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
|
|
use App\Repositories\ClientActivityTimelineRepositoryInterface;
|
|
use Illuminate\Support\Facades\Log as LaravelLog;
|
|
|
|
class ClientRepository extends BaseRepository implements ClientRepositoryInterface
|
|
{
|
|
public function __construct(
|
|
Client $model,
|
|
protected readonly ClientActivityTimelineRepositoryInterface $timelineRepository
|
|
) {
|
|
parent::__construct($model);
|
|
}
|
|
|
|
/**
|
|
* Create a new client and log activity
|
|
*/
|
|
public function create(array $attributes): Client
|
|
{
|
|
$client = parent::create($attributes);
|
|
|
|
try {
|
|
$this->timelineRepository->logActivity([
|
|
'client_id' => $client->id,
|
|
'actor_type' => 'user',
|
|
'actor_user_id' => auth()->id(),
|
|
'event_type' => 'client_created',
|
|
'entity_type' => 'client',
|
|
'entity_id' => $client->id,
|
|
'title' => 'Nouveau client créé',
|
|
'description' => "Le client {$client->name} a été ajouté au système.",
|
|
'created_at' => now(),
|
|
]);
|
|
} catch (\Exception $e) {
|
|
LaravelLog::error("Failed to log client creation activity: " . $e->getMessage());
|
|
}
|
|
|
|
return $client;
|
|
}
|
|
|
|
|
|
/**
|
|
* Get paginated clients
|
|
*/
|
|
public function paginate(int $perPage = 15, array $filters = []): LengthAwarePaginator
|
|
{
|
|
$query = $this->model->newQuery();
|
|
|
|
// Apply filters
|
|
if (!empty($filters['search'])) {
|
|
$query->where(function ($q) use ($filters) {
|
|
$q->where('name', 'like', '%' . $filters['search'] . '%')
|
|
->orWhere('email', 'like', '%' . $filters['search'] . '%')
|
|
->orWhere('vat_number', 'like', '%' . $filters['search'] . '%')
|
|
->orWhere('siret', 'like', '%' . $filters['search'] . '%');
|
|
});
|
|
}
|
|
|
|
if (isset($filters['is_active'])) {
|
|
$query->where('is_active', $filters['is_active']);
|
|
}
|
|
|
|
if (!empty($filters['group_id'])) {
|
|
$query->where('group_id', $filters['group_id']);
|
|
}
|
|
|
|
if (!empty($filters['client_category_id'])) {
|
|
$query->where('client_category_id', $filters['client_category_id']);
|
|
}
|
|
|
|
// Apply sorting
|
|
$sortField = $filters['sort_by'] ?? 'created_at';
|
|
$sortDirection = $filters['sort_direction'] ?? 'desc';
|
|
$query->orderBy($sortField, $sortDirection);
|
|
|
|
return $query->paginate($perPage);
|
|
}
|
|
|
|
|
|
public function searchByName(string $name, int $perPage = 15, bool $exactMatch = false)
|
|
{
|
|
$query = $this->model->newQuery();
|
|
|
|
if ($exactMatch) {
|
|
$query->where('name', $name);
|
|
} else {
|
|
$query->where('name', 'like', '%' . $name . '%');
|
|
}
|
|
|
|
return $query->get();
|
|
}
|
|
}
|