Remove Faker usage from seeders

This commit is contained in:
2026-06-03 06:50:21 +05:00
parent 177c316b44
commit 932b37c7f6
4 changed files with 134 additions and 69 deletions
+17 -2
View File
@@ -14,13 +14,28 @@ class ActivityLogSeeder extends Seeder
$users = User::query()->get(); $users = User::query()->get();
$requests = ServiceRequest::query()->latest()->limit(10)->get(); $requests = ServiceRequest::query()->latest()->limit(10)->get();
$actions = ['updated', 'assigned', 'status_changed'];
$descriptions = [
'Изменены параметры заявки.',
'Заявка назначена ответственному специалисту.',
'Изменен статус обработки заявки.',
'Добавлено служебное действие по заявке.',
];
ActivityLog::query()
->where('model_type', ServiceRequest::class)
->whereIn('action', $actions)
->where('ip_address', '127.0.0.1')
->delete();
foreach ($requests as $request) { foreach ($requests as $request) {
ActivityLog::query()->create([ ActivityLog::query()->create([
'user_id' => $users->random()->id, 'user_id' => $users->random()->id,
'model_type' => ServiceRequest::class, 'model_type' => ServiceRequest::class,
'model_id' => $request->id, 'model_id' => $request->id,
'action' => fake()->randomElement(['updated', 'assigned', 'status_changed']), 'action' => $actions[array_rand($actions)],
'description' => fake()->sentence(), 'description' => $descriptions[array_rand($descriptions)],
'ip_address' => '127.0.0.1', 'ip_address' => '127.0.0.1',
'created_at' => now()->subHours(rand(1, 72)), 'created_at' => now()->subHours(rand(1, 72)),
]); ]);
+21 -9
View File
@@ -16,6 +16,24 @@ class EquipmentSeeder extends Seeder
$categories = EquipmentCategory::query()->get(); $categories = EquipmentCategory::query()->get();
$clients = User::query()->where('role', UserRole::CLIENT)->get(); $clients = User::query()->where('role', UserRole::CLIENT)->get();
$names = [
'Ноутбук Dell Latitude',
'HP ProDesk',
'Cisco Router',
'Brother MFC Printer',
'Lenovo ThinkPad',
];
$conditions = array_map(fn (EquipmentCondition $case) => $case->value, EquipmentCondition::cases());
$notes = [
'Оборудование используется в штатном режиме.',
'Требуется периодическая профилактика.',
'Закреплено за пользователем в рамках эксплуатации.',
'Используется для выполнения рабочих задач.',
'Находится в исправном состоянии.',
];
for ($i = 1; $i <= 10; $i++) { for ($i = 1; $i <= 10; $i++) {
$category = $categories->random(); $category = $categories->random();
$client = $clients->random(); $client = $clients->random();
@@ -23,20 +41,14 @@ class EquipmentSeeder extends Seeder
Equipment::query()->updateOrCreate( Equipment::query()->updateOrCreate(
['inventory_number' => sprintf('INV-%04d', $i)], ['inventory_number' => sprintf('INV-%04d', $i)],
[ [
'name' => fake()->randomElement([ 'name' => $names[($i - 1) % count($names)].' '.$i,
'Ноутбук Dell Latitude',
'HP ProDesk',
'Cisco Router',
'Brother MFC Printer',
'Lenovo ThinkPad',
]).' '.$i,
'serial_number' => sprintf('SN-%08d', 10000000 + $i), 'serial_number' => sprintf('SN-%08d', 10000000 + $i),
'category_id' => $category->id, 'category_id' => $category->id,
'client_id' => $client->id, 'client_id' => $client->id,
'purchase_date' => now()->subMonths(rand(6, 48))->toDateString(), 'purchase_date' => now()->subMonths(rand(6, 48))->toDateString(),
'warranty_until' => now()->addDays(rand(-90, 365))->toDateString(), 'warranty_until' => now()->addDays(rand(-90, 365))->toDateString(),
'condition' => fake()->randomElement(EquipmentCondition::cases())->value, 'condition' => $conditions[($i - 1) % count($conditions)],
'notes' => fake()->sentence(), 'notes' => $notes[($i - 1) % count($notes)],
] ]
); );
} }
+70 -32
View File
@@ -23,16 +23,57 @@ class ServiceRequestSeeder extends Seeder
$techs = User::query()->where('role', 'technician')->get(); $techs = User::query()->where('role', 'technician')->get();
$equipment = Equipment::query()->get(); $equipment = Equipment::query()->get();
// Распределение: 10 активных, 8 в ожидании/в работе с дедлайном сегодня-завтра, $titles = [
// 4 решённых, 3 закрытых. 'Не включается рабочая станция',
'Проблема с печатью документов',
'Нет доступа к корпоративной сети',
'Требуется установка ПО',
'Сильный шум вентилятора',
'Зависает операционная система',
'Не работает монитор',
'Проблема с принтером',
];
$descriptions = [
'Пользователь сообщил о проблеме при выполнении рабочих задач. Требуется диагностика оборудования и проверка состояния системы.',
'Зафиксировано некорректное поведение устройства. Необходимо провести первичную проверку и определить способ устранения неисправности.',
'Возникла техническая проблема, влияющая на выполнение служебных операций. Требуется обработка заявки специалистом.',
'Пользователь просит провести настройку и проверить корректность работы оборудования после выполнения работ.',
];
$resolutionNotesList = [
'Проблема устранена, работоспособность оборудования восстановлена.',
'Выполнена диагностика и произведена настройка системы.',
'Заявка обработана, пользователь уведомлен о результате.',
'Неисправность устранена в рамках регламентных работ.',
];
$clientComments = [
'Проблема решена, оборудование работает корректно.',
'Заявка выполнена в приемлемые сроки.',
'Работы проведены качественно.',
'Сервис оказан в полном объеме.',
];
$locations = ['Офис 101', 'Офис 204', 'Склад', 'Переговорная 2'];
$commentBodies = [
'Проведена первичная диагностика, заявка принята в работу.',
'Пользователь уточнил детали неисправности и подтвердил актуальность обращения.',
'Специалист выполнил проверку оборудования и зафиксировал результат.',
'Требуется дополнительная проверка после выполнения основных работ.',
'Работы завершены, результат передан пользователю.',
];
// Распределение: активные, ожидающие, решенные, закрытые и отмененные заявки.
$buckets = [ $buckets = [
// [slug, count, deadline_offset_hours от now] // [slug, count, deadline_offset_hours from now]
['new', 4, [+48, +168]], // новые — дедлайн через 2-7 дней ['new', 4, [+48, +168]],
['in_progress', 6, [+4, +48]], // в работе — дедлайн через 4-48 ч ['in_progress', 6, [+4, +48]],
['waiting', 4, [+24, +96]], // ожидание — дедлайн через 1-4 дня ['waiting', 4, [+24, +96]],
['resolved', 5, [-72, -1]], // решены — дедлайн в прошлом ['resolved', 5, [-72, -1]],
['closed', 4, [-168, -24]], // закрыты — дедлайн в прошлом ['closed', 4, [-168, -24]],
['cancelled', 2, [-240, -48]], // отменены ['cancelled', 2, [-240, -48]],
]; ];
$counter = 1; $counter = 1;
@@ -47,11 +88,8 @@ class ServiceRequestSeeder extends Seeder
$assignee = $techs->random(); $assignee = $techs->random();
$deadlineAt = now()->addHours(rand($dlMin, $dlMax)); $deadlineAt = now()->addHours(rand($dlMin, $dlMax));
// created_at: задолго до дедлайна, но реалистично
$createdAt = (clone $deadlineAt)->subHours($type->sla_hours + rand(0, 12)); $createdAt = (clone $deadlineAt)->subHours($type->sla_hours + rand(0, 12));
// Не даём created_at быть в будущем
if ($createdAt->isFuture()) { if ($createdAt->isFuture()) {
$createdAt = now()->subMinutes(rand(10, 120)); $createdAt = now()->subMinutes(rand(10, 120));
} }
@@ -62,40 +100,32 @@ class ServiceRequestSeeder extends Seeder
$clientRating = null; $clientRating = null;
$clientComment = null; $clientComment = null;
if (in_array($slug, ['in_progress', 'resolved', 'closed'])) { if (in_array($slug, ['in_progress', 'resolved', 'closed'], true)) {
$startedAt = (clone $createdAt)->addHours(rand(1, 4)); $startedAt = (clone $createdAt)->addHours(rand(1, 4));
} }
if (in_array($slug, ['resolved', 'closed'])) { if (in_array($slug, ['resolved', 'closed'], true)) {
$completedAt = (clone $deadlineAt)->subHours(rand(0, 6)); $completedAt = (clone $deadlineAt)->subHours(rand(0, 6));
$resolutionNotes = fake()->sentence(12); $resolutionNotes = $resolutionNotesList[array_rand($resolutionNotesList)];
} }
if ($slug === 'closed') { if ($slug === 'closed') {
$clientRating = rand(3, 5); $clientRating = rand(3, 5);
$clientComment = fake()->sentence(); $clientComment = $clientComments[array_rand($clientComments)];
} }
$request = ServiceRequest::query()->create([ $request = ServiceRequest::query()->updateOrCreate(
'ticket_number' => sprintf('SRV-%04d', $counter), ['ticket_number' => sprintf('SRV-%04d', $counter)],
'title' => fake()->randomElement([ [
'Не включается рабочая станция', 'title' => $titles[array_rand($titles)],
'Проблема с печатью документов', 'description' => $descriptions[array_rand($descriptions)],
'Нет доступа к корпоративной сети',
'Требуется установка ПО',
'Сильный шум вентилятора',
'Зависает операционная система',
'Не работает монитор',
'Проблема с принтером',
]),
'description' => fake()->paragraph(3),
'type_id' => $type->id, 'type_id' => $type->id,
'priority_id' => $priority->id, 'priority_id' => $priority->id,
'status_id' => $status->id, 'status_id' => $status->id,
'client_id' => $client->id, 'client_id' => $client->id,
'assigned_to' => $assignee->id, 'assigned_to' => $assignee->id,
'equipment_id' => rand(0, 100) > 20 ? $equipment->random()?->id : null, 'equipment_id' => rand(0, 100) > 20 ? $equipment->random()?->id : null,
'location' => fake()->randomElement(['Офис 101', 'Офис 204', 'Склад', 'Переговорная 2']), 'location' => $locations[array_rand($locations)],
'planned_at' => rand(0, 100) > 50 ? (clone $createdAt)->addHours(rand(2, 24)) : null, 'planned_at' => rand(0, 100) > 50 ? (clone $createdAt)->addHours(rand(2, 24)) : null,
'deadline_at' => $deadlineAt, 'deadline_at' => $deadlineAt,
'started_at' => $startedAt, 'started_at' => $startedAt,
@@ -105,14 +135,22 @@ class ServiceRequestSeeder extends Seeder
'client_comment' => $clientComment, 'client_comment' => $clientComment,
'created_at' => $createdAt, 'created_at' => $createdAt,
'updated_at' => now(), '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++) { for ($c = 1; $c <= rand(1, 3); $c++) {
$author = rand(0, 1) ? $client : $assignee; $author = rand(0, 1) ? $client : $assignee;
RequestComment::query()->create([ RequestComment::query()->create([
'request_id' => $request->id, 'request_id' => $request->id,
'user_id' => $author->id, 'user_id' => $author->id,
'body' => fake()->sentence(rand(10, 20)), 'body' => $commentBodies[array_rand($commentBodies)],
'is_internal' => $author->role !== 'client' && rand(0, 100) > 60, 'is_internal' => $author->role !== 'client' && rand(0, 100) > 60,
'created_at' => (clone $createdAt)->addHours($c), 'created_at' => (clone $createdAt)->addHours($c),
'updated_at' => (clone $createdAt)->addHours($c), 'updated_at' => (clone $createdAt)->addHours($c),
+4 -4
View File
@@ -42,9 +42,9 @@ class UserSeeder extends Seeder
); );
$technicians = [ $technicians = [
['name' => 'Иван Петров', 'email' => 'tech1@service.local'], ['name' => 'Иван Петров', 'email' => 'tech1@service.local', 'phone' => '+79990000101'],
['name' => 'Алексей Сидоров', 'email' => 'tech2@service.local'], ['name' => 'Алексей Сидоров', 'email' => 'tech2@service.local', 'phone' => '+79990000102'],
['name' => 'Ольга Смирнова', 'email' => 'tech3@service.local'], ['name' => 'Ольга Смирнова', 'email' => 'tech3@service.local', 'phone' => '+79990000103'],
]; ];
foreach ($technicians as $technician) { foreach ($technicians as $technician) {
@@ -54,7 +54,7 @@ class UserSeeder extends Seeder
'name' => $technician['name'], 'name' => $technician['name'],
'password' => Hash::make('password'), 'password' => Hash::make('password'),
'role' => UserRole::TECHNICIAN, 'role' => UserRole::TECHNICIAN,
'phone' => '+7999'.fake()->numerify('######'), 'phone' => $technician['phone'],
'department_id' => $serviceDepartment?->id, 'department_id' => $serviceDepartment?->id,
'is_active' => true, 'is_active' => true,
'email_verified_at' => now(), 'email_verified_at' => now(),