Files

175 lines
8.7 KiB
PHP

<?php
namespace Database\Seeders;
use App\Models\ActivityLog;
use App\Models\Equipment;
use App\Models\Priority;
use App\Models\RequestComment;
use App\Models\RequestType;
use App\Models\ServiceRequest;
use App\Models\Status;
use App\Models\User;
use Illuminate\Database\Seeder;
class ServiceRequestSeeder extends Seeder
{
public function run(): void
{
$types = RequestType::query()->get();
$priorities = Priority::query()->orderBy('level')->get();
$statuses = Status::query()->get()->keyBy('slug');
$clients = User::query()->where('role', 'client')->get();
$techs = User::query()->where('role', 'technician')->get();
$equipment = Equipment::query()->get();
$titles = [
'Не включается рабочая станция',
'Проблема с печатью документов',
'Нет доступа к корпоративной сети',
'Требуется установка ПО',
'Сильный шум вентилятора',
'Зависает операционная система',
'Не работает монитор',
'Проблема с принтером',
];
$descriptions = [
'Пользователь сообщил о проблеме при выполнении рабочих задач. Требуется диагностика оборудования и проверка состояния системы.',
'Зафиксировано некорректное поведение устройства. Необходимо провести первичную проверку и определить способ устранения неисправности.',
'Возникла техническая проблема, влияющая на выполнение служебных операций. Требуется обработка заявки специалистом.',
'Пользователь просит провести настройку и проверить корректность работы оборудования после выполнения работ.',
];
$resolutionNotesList = [
'Проблема устранена, работоспособность оборудования восстановлена.',
'Выполнена диагностика и произведена настройка системы.',
'Заявка обработана, пользователь уведомлен о результате.',
'Неисправность устранена в рамках регламентных работ.',
];
$clientComments = [
'Проблема решена, оборудование работает корректно.',
'Заявка выполнена в приемлемые сроки.',
'Работы проведены качественно.',
'Сервис оказан в полном объеме.',
];
$locations = ['Офис 101', 'Офис 204', 'Склад', 'Переговорная 2'];
$commentBodies = [
'Проведена первичная диагностика, заявка принята в работу.',
'Пользователь уточнил детали неисправности и подтвердил актуальность обращения.',
'Специалист выполнил проверку оборудования и зафиксировал результат.',
'Требуется дополнительная проверка после выполнения основных работ.',
'Работы завершены, результат передан пользователю.',
];
// Распределение: активные, ожидающие, решенные, закрытые и отмененные заявки.
$buckets = [
// [slug, count, deadline_offset_hours from now]
['new', 4, [+48, +168]],
['in_progress', 6, [+4, +48]],
['waiting', 4, [+24, +96]],
['resolved', 5, [-72, -1]],
['closed', 4, [-168, -24]],
['cancelled', 2, [-240, -48]],
];
$counter = 1;
foreach ($buckets as [$slug, $count, [$dlMin, $dlMax]]) {
$status = $statuses[$slug] ?? $statuses->first();
for ($i = 0; $i < $count; $i++) {
$type = $types->random();
$priority = $priorities->random();
$client = $clients->random();
$assignee = $techs->random();
$deadlineAt = now()->addHours(rand($dlMin, $dlMax));
$createdAt = (clone $deadlineAt)->subHours($type->sla_hours + rand(0, 12));
if ($createdAt->isFuture()) {
$createdAt = now()->subMinutes(rand(10, 120));
}
$startedAt = null;
$completedAt = null;
$resolutionNotes = null;
$clientRating = null;
$clientComment = null;
if (in_array($slug, ['in_progress', 'resolved', 'closed'], true)) {
$startedAt = (clone $createdAt)->addHours(rand(1, 4));
}
if (in_array($slug, ['resolved', 'closed'], true)) {
$completedAt = (clone $deadlineAt)->subHours(rand(0, 6));
$resolutionNotes = $resolutionNotesList[array_rand($resolutionNotesList)];
}
if ($slug === 'closed') {
$clientRating = rand(3, 5);
$clientComment = $clientComments[array_rand($clientComments)];
}
$request = ServiceRequest::query()->updateOrCreate(
['ticket_number' => sprintf('SRV-%04d', $counter)],
[
'title' => $titles[array_rand($titles)],
'description' => $descriptions[array_rand($descriptions)],
'type_id' => $type->id,
'priority_id' => $priority->id,
'status_id' => $status->id,
'client_id' => $client->id,
'assigned_to' => $assignee->id,
'equipment_id' => rand(0, 100) > 20 ? $equipment->random()?->id : null,
'location' => $locations[array_rand($locations)],
'planned_at' => rand(0, 100) > 50 ? (clone $createdAt)->addHours(rand(2, 24)) : null,
'deadline_at' => $deadlineAt,
'started_at' => $startedAt,
'completed_at' => $completedAt,
'resolution_notes' => $resolutionNotes,
'client_rating' => $clientRating,
'client_comment' => $clientComment,
'created_at' => $createdAt,
'updated_at' => now(),
]
);
RequestComment::query()->where('request_id', $request->id)->delete();
ActivityLog::query()
->where('model_type', ServiceRequest::class)
->where('model_id', $request->id)
->delete();
for ($c = 1; $c <= rand(1, 3); $c++) {
$author = rand(0, 1) ? $client : $assignee;
RequestComment::query()->create([
'request_id' => $request->id,
'user_id' => $author->id,
'body' => $commentBodies[array_rand($commentBodies)],
'is_internal' => $author->role !== 'client' && rand(0, 100) > 60,
'created_at' => (clone $createdAt)->addHours($c),
'updated_at' => (clone $createdAt)->addHours($c),
]);
}
ActivityLog::query()->create([
'user_id' => $assignee->id,
'model_type' => ServiceRequest::class,
'model_id' => $request->id,
'action' => 'created',
'description' => "Создана заявка {$request->ticket_number}",
'ip_address' => '127.0.0.1',
'created_at' => $createdAt,
]);
$counter++;
}
}
}
}