84 خطوط
3.0 KiB
PHP
84 خطوط
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\FollowUp;
|
|
use App\Models\Lead;
|
|
use App\Models\User;
|
|
use App\Support\WorkingHours;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class FollowUpService
|
|
{
|
|
public function schedule(Lead $lead, int $assigneeId, string $scheduledAt, User $actor, ?string $notes = null, ?int $callId = null, string $source = 'manual'): FollowUp
|
|
{
|
|
if (! WorkingHours::followUpAllowed($scheduledAt)) {
|
|
throw ValidationException::withMessages([
|
|
'scheduled_at' => ['زمان پیگیری خارج از روز یا ساعت کاری مجاز است.'],
|
|
]);
|
|
}
|
|
|
|
$followUp = DB::transaction(function () use ($lead, $assigneeId, $scheduledAt, $actor, $notes, $callId, $source): FollowUp {
|
|
$followUp = FollowUp::create([
|
|
'lead_id' => $lead->id,
|
|
'user_id' => $assigneeId,
|
|
'created_by' => $actor->id,
|
|
'call_id' => $callId,
|
|
'source' => $source,
|
|
'scheduled_at' => $scheduledAt,
|
|
'notes' => $notes,
|
|
'status' => 'pending',
|
|
]);
|
|
|
|
$lead->update(['next_follow_up_at' => $scheduledAt]);
|
|
ActivityLogger::log('follow_up_created', "Follow-up {$followUp->id} scheduled from {$source}", $followUp);
|
|
|
|
return $followUp;
|
|
});
|
|
|
|
NotificationService::notifyFollowUpAssigned(
|
|
$followUp,
|
|
$lead->full_name ?: ($lead->company ?? "لید {$lead->id}"),
|
|
$actor,
|
|
);
|
|
|
|
return $followUp->load($this->relations());
|
|
}
|
|
|
|
public function update(FollowUp $followUp, array $data): FollowUp
|
|
{
|
|
if (isset($data['scheduled_at']) && ! WorkingHours::followUpAllowed($data['scheduled_at'])) {
|
|
throw ValidationException::withMessages([
|
|
'scheduled_at' => ['زمان پیگیری خارج از روز یا ساعت کاری مجاز است.'],
|
|
]);
|
|
}
|
|
|
|
if (($data['status'] ?? null) === 'completed') {
|
|
$data['completed_at'] = now();
|
|
$data['is_overdue'] = false;
|
|
} elseif (($data['status'] ?? null) === 'pending') {
|
|
$data['completed_at'] = null;
|
|
}
|
|
|
|
$beforeAssignee = $followUp->user_id;
|
|
$followUp->update($data);
|
|
ActivityLogger::log('follow_up_updated', "Follow-up {$followUp->id} updated", $followUp);
|
|
|
|
if (isset($data['user_id']) && (int) $data['user_id'] !== $beforeAssignee) {
|
|
NotificationService::notifyFollowUpAssigned(
|
|
$followUp->fresh(),
|
|
$followUp->lead?->full_name ?: ($followUp->lead?->company ?? "لید {$followUp->lead_id}"),
|
|
auth()->user(),
|
|
);
|
|
}
|
|
|
|
return $followUp->fresh($this->relations());
|
|
}
|
|
|
|
private function relations(): array
|
|
{
|
|
return ['lead:id,first_name,last_name,company,phone', 'user:id,name', 'creator:id,name'];
|
|
}
|
|
}
|