first commit

This commit is contained in:
amikhaylov
2026-05-27 10:57:53 +03:00
commit 4ebf4ec35f
66 changed files with 11269 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
*.sqlite*
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Database\Factories;
use App\Models\ORM\Gig;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Gig>
*/
class GigFactory extends Factory
{
protected $model = Gig::class;
/**
* Базовое состояние: генерирует случайное будущее событие
*/
public function definition(): array
{
return [
'title' => $this->faker->randomElement([
'Большой рок-концерт', 'Выставка цифрового искусства', 'Квест в темноте',
'Лекция о космосе', 'Мастер-класс по живописи', 'Ночной кинопоказ',
'Футбольный матч', 'Театральный спектакль', 'Прогулка по крышам',
'Экскурсия в подземку', 'Детский интерактивный праздник'
]) . ' ' . $this->faker->numberBetween(1, 100),
'description' => $this->faker->paragraph(3),
'event_date' => $this->faker->dateTimeBetween('+1 days', '+3 months'), // Будущее время
];
}
/**
* Состояние для генерации прошедших событий (архивных)
*/
public function past(): static
{
return $this->state(fn (array $attributes) => [
'event_date' => $this->faker->dateTimeBetween('-6 months', '-1 days'), // Прошедшее время
]);
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
@@ -0,0 +1,49 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};
@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->integer('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->integer('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};
@@ -0,0 +1,57 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedTinyInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('gigs', function (Blueprint $blueprint) {
$blueprint->id(); // Автоинкрементный ID (BIGINT)
$blueprint->string('title'); // Название афиши (VARCHAR 255)
$blueprint->text('description'); // Текст афиши
$blueprint->dateTime('event_date'); // Дата и время мероприятия
$blueprint->boolean('archived')->default(false);
$blueprint->timestamps(); // Создает поля created_at и updated_at
$blueprint->softDeletes(); // Создает поле deleted_at для мягкого удаления
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('gigs');
}
};
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name')->unique(); // Уникальное название категории
$table->string('slug')->unique(); // URL-friendly идентификатор
$table->timestamps();
$table->softDeletes();
});
Schema::create('gig_category', function (Blueprint $table) {
$table->id();
// Внешний ключ на афишу. При удалении афиши связь удалится автоматически
$table->foreignId('gig_id')
->constrained()
->cascadeOnDelete();
// Внешний ключ на категорию. При удалении категории связь удалится автоматически
$table->foreignId('category_id')
->constrained()
->cascadeOnDelete();
// Защита от дублирования одинаковых связей
$table->unique(['gig_id', 'category_id']);
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('categories');
}
};
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Database\Seeders;
use App\Models\ORM\Category;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
class CategorySeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
// Список ваших категорий
$categories = [
'Выставки',
'Детям',
'Квесты',
'Концерты и шоу',
'Лекции',
'Кинопоказы',
'Спорт',
'Мастер-классы',
'Спектакли',
'Прогулки',
'Экскурсии',
];
foreach ($categories as $name) {
// updateOrCreate предотвратит дублирование при повторном запуске
Category::updateOrCreate(
['slug' => Str::slug($name)], // Уникальный идентификатор (например, "koncerty-i-sou")
['name' => $name]
);
}
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
// 1. Создаем фиксированного пользователя для тестирования API
$user = User::updateOrCreate(
['email' => 'test@example.com'],
[
'name' => 'Test API User',
'password' => Hash::make('password'), // Пароль для входа, если понадобится
]
);
// 2. Генерируем для него постоянный токен
// Сначала удаляем старые токены этого пользователя, чтобы не плодить дубликаты при повторном сидинге
$user->tokens()->delete();
// Создаем новый токен
$token = $user->createToken('postman-api-token');
// 3. Выводим токен прямо в консоль при запуске сидера, чтобы его можно было скопировать
$this->command->newLine();
$this->command->info('==================================================');
$this->command->info(' TEST USER BEARER TOKEN FOR POSTMAN / CURL: ');
$this->command->comment(' ' . $token->plainTextToken);
$this->command->info('==================================================');
$this->command->newLine();
$this->call([
CategorySeeder::class,
GigSeeder::class,
]);
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Database\Seeders;
use App\Models\ORM\Category;
use App\Models\ORM\Gig;
use Illuminate\Database\Seeder;
class GigSeeder extends Seeder
{
public function run(): void
{
// 1. Получаем все существующие категории из базы
$categories = Category::all();
if ($categories->isEmpty()) {
$this->command->error('Категории не найдены. Сначала запустите CategorySeeder!');
return;
}
// 2. Генерируем 10 ПРОШЕДШИХ событий
$pastGigs = Gig::factory()
->count(10)
->past() // Используем состояние из фабрики
->create();
// 3. Генерируем 30 БУДУЩИХ событий
$futureGigs = Gig::factory()
->count(30)
->create();
// Объединяем коллекции для привязки категорий
$allGigs = $pastGigs->concat($futureGigs);
// 4. Привязываем категории, выполняя условия ТЗ
foreach ($allGigs as $index => $gig) {
// Чтобы ГАРАНТИРОВАННО задействовать ВСЕ категории:
// Первые 11 событий получат строго по одной уникальной категории из списка
if ($index < $categories->count()) {
$gig->categories()->attach($categories[$index]->id);
continue;
}
// Для всех остальных событий выбираем случайное количество случайных категорий (от 1 до 3)
$randomCategories = $categories->random(rand(1, 3))->pluck('id')->toArray();
$gig->categories()->attach($randomCategories);
}
}
}