124 lines
4.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Repositories;
use App\Models\Avoir;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class AvoirRepository extends BaseRepository implements AvoirRepositoryInterface
{
public function __construct(
Avoir $model,
protected AvoirLineRepositoryInterface $avoirLineRepository,
protected readonly ClientActivityTimelineRepositoryInterface $timelineRepository
) {
parent::__construct($model);
}
public function all(array $columns = ['*']): \Illuminate\Support\Collection
{
return $this->model->with(['client', 'lines.product'])->get($columns);
}
public function create(array $data): Avoir
{
return DB::transaction(function () use ($data) {
try {
// Create the avoir
$avoir = parent::create($data);
// Create the avoir lines
if (isset($data['lines']) && is_array($data['lines'])) {
foreach ($data['lines'] as $lineData) {
$lineData['avoir_id'] = $avoir->id;
$this->avoirLineRepository->create($lineData);
}
}
// Record initial status history
$this->recordHistory((int)$avoir->id, null, $avoir->status, 'Avoir created');
try {
$this->timelineRepository->logActivity([
'client_id' => $avoir->client_id,
'actor_type' => 'user',
'actor_user_id' => auth()->id(),
'event_type' => 'avoir_created',
'entity_type' => 'avoir',
'entity_id' => $avoir->id,
'title' => 'Nouvel avoir créé',
'description' => "L'avoir #{$avoir->avoir_number} a été créé.",
'created_at' => now(),
]);
} catch (\Exception $e) {
Log::error("Failed to log avoir creation activity: " . $e->getMessage());
}
return $avoir;
} catch (\Exception $e) {
Log::error('Error creating avoir with lines: ' . $e->getMessage(), [
'exception' => $e,
'data' => $data,
]);
throw $e;
}
});
}
public function update(int|string $id, array $attributes): bool
{
return DB::transaction(function () use ($id, $attributes) {
try {
$avoir = $this->find($id);
if (!$avoir) {
return false;
}
$oldStatus = $avoir->status;
// Update the avoir
$updated = parent::update($id, $attributes);
if ($updated) {
$newStatus = $attributes['status'] ?? $oldStatus;
// If status changed, record history
if ($oldStatus !== $newStatus) {
$this->recordHistory((int) $id, $oldStatus, $newStatus, 'Avoir status updated');
}
}
return $updated;
} catch (\Exception $e) {
Log::error('Error updating avoir: ' . $e->getMessage(), [
'id' => $id,
'attributes' => $attributes,
'exception' => $e,
]);
throw $e;
}
});
}
public function find(int|string $id, array $columns = ['*']): ?Avoir
{
return $this->model->with(['client', 'lines.product', 'history.user'])->find($id, $columns);
}
private function recordHistory(int $avoirId, ?string $oldStatus, string $newStatus, ?string $comment = null): void
{
\App\Models\DocumentStatusHistory::create([
'document_type' => 'avoir',
'document_id' => $avoirId,
'old_status' => $oldStatus,
'new_status' => $newStatus,
'changed_by' => auth()->id(),
'comment' => $comment,
'changed_at' => now(),
]);
}
}