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