Начальный коммит: рабочая версия с исправленной авторизацией

This commit is contained in:
root
2026-01-11 19:15:02 +00:00
commit 2d98209ce1
206 changed files with 20957 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
<?php
namespace App\Http\Controllers;
use App\Services\AiSuggestorService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class AiController extends Controller
{
protected $aiService;
// ✅ Используем DI — Laravel сам передаст сервис
public function __construct(AiSuggestorService $aiService)
{
$this->aiService = $aiService;
}
public function suggest(Request $request)
{
$validated = $request->validate([
'task_id' => 'nullable|string',
'custom_prompt' => 'nullable|string',
'budget' => 'nullable|numeric|min:0',
]);
try {
// ✅ Вызываем через DI
$result = $this->aiService->suggest(
$request->input('task_id'),
$request->input('custom_prompt'),
$request->input('budget')
);
// ✅ Возвращаем ТОЛЬКО ID — быстро и безопасно
return response()->json([
'message' => 'Сборка успешно сгенерирована ИИ.',
'build_id' => $result['build']->id,
], 201);
} catch (\Exception $e) {
Log::error('Ошибка в AI-сервисе', [
'user_id' => auth()->id(),
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return response()->json([
'message' => 'Не удалось сгенерировать сборку.',
'error' => $e->getMessage()
], 500);
}
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
/**
* Регистрация пользователя.
*/
public function register(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8|confirmed',
<<<<<<< HEAD
=======
'custom_field' => 'required|string|min:2'
>>>>>>> origin/main
]);
$user = User::create([
'name' => $validated['name'],
'email' => $validated['email'],
'password' => Hash::make($validated['password']),
<<<<<<< HEAD
'custom_field' => $request->custom_field ?? 'user', // ← ключевая строка
=======
'custom_field' => $validated['custom_field'],
>>>>>>> origin/main
]);
return response()->json([
'message' => 'Пользователь зарегистрирован.',
'user' => $user,
'token' => $user->createToken('auth_token')->plainTextToken
], 201);
}
/**
* Вход пользователя.
*/
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$user = User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['Неверные учётные данные.'],
]);
}
return response()->json([
'message' => 'Успешный вход.',
'user' => $user,
'token' => $user->createToken('auth_token')->plainTextToken
]);
}
/**
* Выход (инвалидация токена).
*/
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();
return response()->json([
'message' => 'Вы успешно вышли из системы.'
]);
}
}

View File

@@ -0,0 +1,213 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Models\Component;
use Illuminate\Http\Response;
class ComponentsController extends Controller
{
<<<<<<< HEAD
public function index(Request $request)
{
// Начинаем с базового запроса
$query = Component::with('componentType'); // ← важно! Загружаем связь
// Фильтр по пользователю и статусу
$query->where(function ($q) {
$q->where('is_official', true)
->orWhere('created_by_user_id', auth()->id());
});
// Если передан параметр type — фильтруем по code
if ($request->has('type')) {
$typeCode = $request->input('type');
// Убедимся, что такой тип существует
$type = \App\Models\ComponentType::where('code', $typeCode)->first();
if (!$type) {
return response()->json([], 200); // пустой массив, если тип не найден
}
// Фильтруем компоненты по component_type_id
$query->where('component_type_id', $type->id);
}
$components = $query->get();
// Добавляем поле "type" для удобства фронта
$components = $components->map(function ($comp) {
$comp->type = $comp->componentType?->code ?? 'unknown';
return $comp;
});
return response()->json($components);
}
=======
public function index()
{
$components = Component::with('user', 'componentType')
->where('is_official', true)
->orWhere('created_by_user_id', auth()->id())
->get();
return response()->json($components);
}
>>>>>>> origin/main
public function show($id)
{
$component = Component::find($id);
if (!$component) {
return response()->json(['message' => 'Component not found'], 404);
}
return response()->json($component);
}
<<<<<<< HEAD
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
'component_type_id' => 'required|exists:component_types,id',
'specifications' => 'nullable|array',
]);
$component = Component::create([
'name' => $validated['name'],
'price' => $validated['price'],
'component_type_id' => $validated['component_type_id'],
'specifications' => $validated['specifications'] ?? null,
'is_official' => false,
'created_by_user_id' => auth()->id(),
]);
return response()->json([
'message' => 'Компонент успешно создан.',
'component' => $component
], 201);
}
public function update(Request $request, $id)
{
$component = Component::findOrFail($id);
if ($component->created_by_user_id !== auth()->id() || $component->is_official) {
return response()->json([
'message' => 'Вы не можете редактировать этот компонент.'
], 403);
}
$validated = $request->validate([
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
'component_type_id' => 'required|exists:component_types,id',
'specifications' => 'nullable|array',
]);
$component->update($validated);
return response()->json([
'message' => 'Компонент обновлён.',
'component' => $component
]);
}
public function destroy($id)
{
$component = Component::findOrFail($id);
if ($component->created_by_user_id !== auth()->id() || $component->is_official) {
return response()->json([
'message' => 'Вы не можете удалить этот компонент.'
], 403);
}
$component->delete();
return response()->json([
'message' => 'Компонент удалён.'
]);
}
}
=======
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
'component_type_id' => 'required|exists:component_types,id',
'specifications' => 'nullable|array',
]);
$component = Component::create([
'name' => $validated['name'],
'price' => $validated['price'],
'component_type_id' => $validated['component_type_id'],
'specifications' => $validated['specifications'] ?? null,
'is_official' => false, // всегда false для пользователя
'created_by_user_id' => auth()->id(), // автоматически привязываем к пользователю
]);
return response()->json([
'message' => 'Компонент успешно создан.',
'component' => $component
], 201);
}
public function update(Request $request, $id)
{
$component = Component::findOrFail($id);
// Проверяем, что компонент принадлежит пользователю и не официальный
if ($component->created_by_user_id !== auth()->id() || $component->is_official) {
return response()->json([
'message' => 'Вы не можете редактировать этот компонент.'
], 403);
}
$validated = $request->validate([
'name' => 'required|string|max:255',
'price' => 'required|numeric|min:0',
'component_type_id' => 'required|exists:component_types,id',
'specifications' => 'nullable|array',
]);
$component->update($validated);
return response()->json([
'message' => 'Компонент обновлён.',
'component' => $component
]);
}
public function destroy($id)
{
$component = Component::findOrFail($id);
// Проверяем, что компонент принадлежит пользователю и не официальный
if ($component->created_by_user_id !== auth()->id() || $component->is_official) {
return response()->json([
'message' => 'Вы не можете удалить этот компонент.'
], 403);
}
$component->delete();
return response()->json([
'message' => 'Компонент удалён.'
]);
}
}
>>>>>>> origin/main

View File

@@ -0,0 +1,8 @@
<?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}

View File

@@ -0,0 +1,246 @@
<?php
namespace App\Http\Controllers;
use App\Models\PCBuild;
use App\Models\Component;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\BuildValidator;
class PCBuildsController extends Controller
{
/**
* @OA\Get(
* path="/api/builds",
* summary="Получить список своих сборок",
* tags={"PC Builds"},
* @OA\Response(response=200, description="Список сборок"),
* @OA\Response(response=401, description="Неавторизован")
* )
*/
public function index()
{
$builds = PCBuild::where('user_id', auth()->id())
->with('components')
->get();
return response()->json($builds);
}
/**
* @OA\Post(
* path="/api/builds",
* summary="Создать новую сборку",
* tags={"PC Builds"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"name", "component_ids"},
* @OA\Property(property="name", type="string", example="Игровой ПК 2025"),
* @OA\Property(property="description", type="string", nullable=true, example="Для игр в 1440p"),
* @OA\Property(property="component_ids", type="array", @OA\Items(type="integer", example=1)),
* @OA\Property(property="is_ai_generated", type="boolean", default=false),
* @OA\Property(property="ai_prompt", type="string", nullable=true, example="Сборка до 1000$ для игр")
* )
* ),
* @OA\Response(response=201, description="Сборка создана"),
* @OA\Response(response=400, description="Ошибка валидации"),
* @OA\Response(response=403, description="Запрещено: чужие компоненты")
* )
*/
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'description' => 'nullable|string',
'component_ids' => 'required|array|min:1',
'component_ids.*' => 'exists:components,id',
'is_ai_generated' => 'nullable|boolean',
'ai_prompt' => 'nullable|string',
]);
// Проверяем: все компоненты — либо официальные, либо ваши
$invalidComponents = Component::whereIn('id', $validated['component_ids'])
->where(function ($query) {
$query->where('is_official', false)
->where('created_by_user_id', '!=', auth()->id());
})
->pluck('name', 'id')
->toArray();
if (!empty($invalidComponents)) {
return response()->json([
'message' => 'Запрещено использовать неофициальные компоненты, созданные другими пользователями.',
'invalid_components' => $invalidComponents
], 403);
}
// 👇 ВСТАВЛЯЕМ ПРОВЕРКУ СОВМЕСТИМОСТИ ЗДЕСЬ — ПЕРЕД СОЗДАНИЕМ СБОРКИ
$validator = new BuildValidator();
$compatibility = $validator->validateCompatibility($validated['component_ids']);
if (!$compatibility['valid']) {
return response()->json([
'message' => 'Сборка содержит несовместимые компоненты.',
'errors' => $compatibility['errors'],
'warnings' => $compatibility['warnings']
], 422); // 422 Unprocessable Entity
}
// ✅ Только если совместимость OK — создаём сборку
$build = PCBuild::create([
'user_id' => auth()->id(),
'name' => $validated['name'],
'description' => $validated['description'] ?? null,
'is_ai_generated' => $validated['is_ai_generated'] ?? false,
'ai_prompt' => $validated['ai_prompt'] ?? null,
]);
$build->components()->attach($validated['component_ids']);
return response()->json([
'message' => 'Сборка успешно создана.',
'build' => $build->load('components'),
'compatibility' => $compatibility // опционально — для отладки
], 201);
}
/**
* @OA\Get(
* path="/api/builds/{id}",
* summary="Получить одну сборку по ID",
* tags={"PC Builds"},
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
* @OA\Response(response=200, description="Сборка найдена"),
* @OA\Response(response=403, description="Запрещено: не ваша сборка"),
* @OA\Response(response=404, description="Не найдено")
* )
*/
public function show($id)
{
$build = PCBuild::with('components')->findOrFail($id);
if ($build->user_id !== auth()->id()) {
return response()->json([
'message' => 'Вы не можете просматривать эту сборку.'
], 403);
}
return response()->json($build);
}
/**
* @OA\Put(
* path="/api/builds/{id}",
* summary="Обновить сборку",
* tags={"PC Builds"},
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"name", "component_ids"},
* @OA\Property(property="name", type="string"),
* @OA\Property(property="description", type="string", nullable=true),
* @OA\Property(property="component_ids", type="array", @OA\Items(type="integer")),
* @OA\Property(property="is_ai_generated", type="boolean"),
* @OA\Property(property="ai_prompt", type="string", nullable=true)
* )
* ),
* @OA\Response(response=200, description="Сборка обновлена"),
* @OA\Response(response=403, description="Запрещено")
* )
*/
public function update(Request $request, $id)
{
$build = PCBuild::findOrFail($id);
if ($build->user_id !== auth()->id()) {
return response()->json([
'message' => 'Вы не можете редактировать эту сборку.'
], 403);
}
$validated = $request->validate([
'name' => 'required|string|max:255',
'description' => 'nullable|string',
'component_ids' => 'required|array|min:1',
'component_ids.*' => 'exists:components,id',
'is_ai_generated' => 'nullable|boolean',
'ai_prompt' => 'nullable|string',
]);
// Проверка: все компоненты — либо официальные, либо ваши
$invalidComponents = Component::whereIn('id', $validated['component_ids'])
->where(function ($query) {
$query->where('is_official', false)
->where('created_by_user_id', '!=', auth()->id());
})
->pluck('name', 'id')
->toArray();
if (!empty($invalidComponents)) {
return response()->json([
'message' => 'Запрещено использовать неофициальные компоненты, созданные другими пользователями.',
'invalid_components' => $invalidComponents
], 403);
}
// 👇 ВСТАВЛЯЕМ ПРОВЕРКУ СОВМЕСТИМОСТИ ЗДЕСЬ — ПЕРЕД ОБНОВЛЕНИЕМ
$validator = new BuildValidator();
$compatibility = $validator->validateCompatibility($validated['component_ids']);
if (!$compatibility['valid']) {
return response()->json([
'message' => 'Сборка содержит несовместимые компоненты.',
'errors' => $compatibility['errors'],
'warnings' => $compatibility['warnings']
], 422);
}
// ✅ Обновляем сборку
DB::transaction(function () use ($build, $validated) {
$build->update([
'name' => $validated['name'],
'description' => $validated['description'] ?? null,
'is_ai_generated' => $validated['is_ai_generated'] ?? $build->is_ai_generated,
'ai_prompt' => $validated['ai_prompt'] ?? $build->ai_prompt,
]);
$build->components()->sync($validated['component_ids']);
});
return response()->json([
'message' => 'Сборка обновлена.',
'build' => $build->load('components'),
'compatibility' => $compatibility // опционально
]);
}
/**
* @OA\Delete(
* path="/api/builds/{id}",
* summary="Удалить сборку",
* tags={"PC Builds"},
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
* @OA\Response(response=200, description="Сборка удалена"),
* @OA\Response(response=403, description="Запрещено")
* )
*/
public function destroy($id)
{
$build = PCBuild::findOrFail($id);
if ($build->user_id !== auth()->id()) {
return response()->json([
'message' => 'Вы не можете удалить эту сборку.'
], 403);
}
$build->delete();
return response()->json([
'message' => 'Сборка удалена.'
]);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Http\Controllers;
use App\Mail\RegisterUserMail;
use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use App\Models\User;
use Illuminate\Http\Request;
class UsersController extends Controller
{
public function create(Request $request){
$user = new User();
$name = $request->get('name');
$email = $request->get('email');
$password = Hash::make($request->get('password'));
$user->name = $name;
$user->email = $email;
$user->password = $password;
$user->save();
$adminEmail = 'dimon.cozlow2017@yandex.ru';
dispatch(function () use ($user, $adminEmail) {
Mail::to($adminEmail)->send(new RegisterUserMail($user->name));
});
return ['token' => $user->createToken('frontend')->plainTextToken];
}
}

67
app/Http/Kernel.php Normal file
View File

@@ -0,0 +1,67 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\Illuminate\Http\Middleware\HandleCors::class, // ← Встроенный CORS (Laravel 12+)
\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's middleware aliases.
*
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
*
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@@ -0,0 +1,59 @@
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class RegisterUserMail extends Mailable
{
use Queueable, SerializesModels;
public $name;
/**
* Create a new message instance.
*/
public function __construct(string $name)
{
$this->name = $name;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: 'Register User Mail',
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'emails.register',
);
}
/**
* Get the attachments for the message.
*
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
*/
public function attachments(): array
{
return [];
}
}

58
app/Models/AiTask.php Normal file
View File

@@ -0,0 +1,58 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class AiTask extends Model
{
use HasFactory;
protected $fillable = [
<<<<<<< HEAD
'title',
'description',
'ai_prompt_template',
'budget_min',
'budget_max',
'is_active'
];
protected $casts = [
'budget_min' => 'decimal:2',
'budget_max' => 'decimal:2',
'is_active' => 'boolean'
];
=======
'user_id',
'name',
'prompt_template',
'is_active',
];
protected $casts = [
'is_active' => 'boolean',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
// Связь с пользователем (если шаблон пользовательский)
public function user()
{
return $this->belongsTo(User::class);
}
// Общие (глобальные) шаблоны — где user_id IS NULL
public function scopeGlobal($query)
{
return $query->whereNull('user_id');
}
// Активные шаблоны
public function scopeActive($query)
{
return $query->where('is_active', true);
}
>>>>>>> origin/main
}

34
app/Models/Component.php Normal file
View File

@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Component extends Model
{
use HasFactory;
protected $fillable = [
'name',
'price',
'component_type_id',
'specifications',
'is_official',
'created_by_user_id',
];
protected $casts = [
'specifications' => 'array', // автоматически преобразует JSON в массив
];
public function user()
{
return $this->belongsTo(User::class, 'created_by_user_id');
}
public function componentType()
{
return $this->belongsTo(ComponentType::class, 'component_type_id');
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ComponentType extends Model
{
protected $fillable = ['name', 'code'];
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
}

55
app/Models/PCBuild.php Normal file
View File

@@ -0,0 +1,55 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class PcBuild extends Model
{
use HasFactory;
protected $fillable = [
'name',
'description',
'user_id',
];
<<<<<<< HEAD
// 👇 Связь "многие-ко-многим" с компонентами
public function components()
{
return $this->belongsToMany(Component::class, 'pc_build_components');
}
// Обратная связь
=======
protected $casts = [
'is_ai_generated' => 'boolean',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
// Связь с пользователем
>>>>>>> origin/main
public function user()
{
return $this->belongsTo(User::class);
}
<<<<<<< HEAD
// Опционально: защита от ошибок, если сборка без пользователя
protected static function booted()
{
static::addGlobalScope('user', function ($query) {
if (auth()->check()) {
$query->where('user_id', auth()->id());
}
});
}
=======
>>>>>>> origin/main
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class PcBuildComponent extends Model
{
use HasFactory;
protected $fillable = [
'pc_build_id',
'component_id',
'quantity',
];
protected $casts = [
'quantity' => 'integer',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
// Связь с сборкой
public function build()
{
return $this->belongsTo(PcBuild::class);
}
// Связь с компонентом
public function component()
{
return $this->belongsTo(Component::class);
}
}

52
app/Models/User.php Normal file
View File

@@ -0,0 +1,52 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
'custom_field'
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}

View File

@@ -0,0 +1,400 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\Component;
use App\Models\PCBuild;
use Exception;
class AiSuggestorService
{
protected $apiToken;
protected $baseUrl = 'https://gigachat.devices.sberbank.ru/api/v1/chat/completions';
public function __construct()
{
$this->apiToken = env('GIGACHAT_API_TOKEN');
if (!$this->apiToken) {
throw new Exception('GIGACHAT_API_TOKEN не установлен в .env');
}
}
public function suggest($task_id = null, $custom_prompt = null, $budget = null)
{
$prompt = $this->generatePrompt($task_id, $custom_prompt, $budget);
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $this->apiToken,
'Content-Type' => 'application/json',
])->withoutVerifying()
->post($this->baseUrl, [
'model' => 'GigaChat',
'messages' => [
[
'role' => 'user',
'content' => $prompt
]
],
'temperature' => 0.7,
'max_tokens' => 2500,
]);
if ($response->failed()) {
Log::error('Ошибка при запросе к ГигаЧату', [
'status' => $response->status(),
'body' => $response->body()
]);
throw new Exception('Не удалось получить ответ от ИИ.');
}
$responseData = $response->json();
$aiComponents = $this->parseResponse($responseData);
// ✅ Теперь можно безопасно логировать
// 🔹 ДЕБАГ: логируем полученные компоненты от ИИ
Log::info('Компоненты от ИИ:', [
'count' => count($aiComponents),
'types' => array_column($aiComponents, 'component_type_id'),
'components' => $aiComponents
]);
// 🔹 ШАГ 1: Удаляем дубликаты по name + component_type_id
$uniqueComponents = [];
$seen = [];
foreach ($aiComponents as $component) {
$key = $component['name'] . '|' . $component['component_type_id'];
if (!isset($seen[$key])) {
$seen[$key] = true;
$uniqueComponents[] = $component;
}
}
$aiComponents = $uniqueComponents;
// 🔹 ШАГ 2: Гарантируем наличие всех 7 типов компонентов
$requiredTypes = [1, 2, 3, 4, 5, 6, 7];
$existingTypes = array_column($aiComponents, 'component_type_id');
// ДЕБАГ: какие типы уже есть
Log::info('Проверка типов компонентов:', [
'required' => $requiredTypes,
'existing' => $existingTypes,
'missing' => array_diff($requiredTypes, $existingTypes)
]);
foreach ($requiredTypes as $typeId) {
if (!in_array($typeId, $existingTypes)) {
Log::warning('Добавляем недостающий тип компонента:', ['type_id' => $typeId]);
switch ($typeId) {
case 1:
$aiComponents[] = [
'name' => 'AMD Ryzen 5 5600',
'price' => 15000,
'component_type_id' => 1,
'specifications' => ['socket' => 'AM4', 'cores' => 6]
];
break;
case 2:
$aiComponents[] = [
'name' => 'NVIDIA RTX 4060',
'price' => 30000,
'component_type_id' => 2,
'specifications' => []
];
break;
case 3:
$aiComponents[] = [
'name' => 'ASUS TUF GAMING B660M-PLUS',
'price' => 8000,
'component_type_id' => 3,
'specifications' => ['chipset' => 'B660']
];
break;
case 4:
$aiComponents[] = [
'name' => 'Kingston FURY Beast DDR4 16GB',
'price' => 5000,
'component_type_id' => 4,
'specifications' => ['type' => 'DDR4', 'capacity' => '16GB']
];
break;
case 5:
$aiComponents[] = [
'name' => 'EVGA SuperNOVA 750 G2',
'price' => 8000,
'component_type_id' => 5,
'specifications' => ['power' => 750]
];
break;
case 6:
$aiComponents[] = [
'name' => 'Crucial P3 500GB NVMe',
'price' => 4000,
'component_type_id' => 6,
'specifications' => ['capacity' => 500, 'interface' => 'NVMe']
];
break;
case 7:
$aiComponents[] = [
'name' => 'Cooler Master H500P ATX Mid Tower Case',
'price' => 4000,
'component_type_id' => 7,
'specifications' => ['form_factor' => 'ATX']
];
break;
}
}
}
// ДЕБАГ: проверяем итоговый набор компонентов
Log::info('Итоговые компоненты перед созданием сборки:', [
'total_count' => count($aiComponents),
'types_present' => array_column($aiComponents, 'component_type_id'),
'unique_types_count' => count(array_unique(array_column($aiComponents, 'component_type_id')))
]);
// Проверка бюджета
if ($budget) {
$totalPrice = array_sum(array_column($aiComponents, 'price'));
if ($totalPrice > $budget) {
// Удаляем возможные дубликаты перед заменой
$uniqueComponents = [];
$seen = [];
foreach ($aiComponents as $component) {
$key = $component['name'] . '|' . $component['component_type_id'];
if (!isset($seen[$key])) {
$seen[$key] = true;
$uniqueComponents[] = $component;
}
}
$aiComponents = $uniqueComponents;
// Заменяем дорогие компоненты
foreach ($aiComponents as &$component) {
if ($component['component_type_id'] == 4) {
$component = [
'name' => 'Kingston FURY Beast DDR4 16GB',
'price' => 5000,
'component_type_id' => 4,
'specifications' => ['type' => 'DDR4', 'capacity' => '16GB']
];
}
if ($component['component_type_id'] == 6) {
$component = [
'name' => 'Crucial P3 500GB NVMe',
'price' => 4000,
'component_type_id' => 6,
'specifications' => ['capacity' => 500, 'interface' => 'NVMe']
];
}
if ($component['component_type_id'] == 1 && $totalPrice > $budget) {
$component = [
'name' => 'AMD Ryzen 5 5600',
'price' => 15000,
'component_type_id' => 1,
'specifications' => ['socket' => 'AM4', 'cores' => 6]
];
}
}
$totalPrice = array_sum(array_column($aiComponents, 'price'));
if ($totalPrice > $budget) {
throw new Exception("ИИ не смог уложиться в бюджет {$budget}₽ (итого: {$totalPrice}₽).");
}
}
}
// Создаём сборку
$build = PCBuild::create([
'user_id' => auth()->id(),
'name' => 'Сборка от ИИ',
'description' => "Сгенерировано ИИ на основе: " . ($custom_prompt ?: "задача #{$task_id}"),
'is_ai_generated' => true,
'ai_prompt' => $prompt,
]);
// Привязываем компоненты с защитой от дубликатов
$createdComponents = [];
$seenComponentIds = [];
foreach ($aiComponents as $componentData) {
$component = $this->findOrCreateComponent($componentData);
// Проверяем, что компонент ещё не добавлен в эту сборку
if (!in_array($component->id, $seenComponentIds)) {
$createdComponents[] = $component;
$seenComponentIds[] = $component->id;
}
}
// Используем sync без детачей, чтобы избежать дубликатов
$build->components()->sync($seenComponentIds, false);
// 🔹 ПРОВЕРКА: убеждаемся, что есть все 7 типов компонентов
$finalComponents = $build->components()->get();
$finalTypes = $finalComponents->pluck('component_type_id')->unique()->toArray();
Log::info('Проверка финальной сборки:', [
'build_id' => $build->id,
'total_components' => $finalComponents->count(),
'component_types' => $finalTypes,
'missing_types' => array_diff($requiredTypes, $finalTypes)
]);
if (!in_array(7, $finalTypes)) {
// Находим или создаем корпус по умолчанию
$defaultCase = Component::firstOrCreate(
[
'name' => 'Cooler Master H500P ATX Mid Tower Case',
'component_type_id' => 7,
],
[
'price' => 4000,
'specifications' => ['form_factor' => 'ATX'],
'is_official' => true,
'created_by_user_id' => null,
]
);
$build->components()->attach($defaultCase->id);
Log::warning('Был добавлен корпус по умолчанию для сборки', [
'build_id' => $build->id,
'case_id' => $defaultCase->id
]);
// Обновляем массив созданных компонентов
$createdComponents[] = $defaultCase;
}
// 🔹 ФИНАЛЬНАЯ ПРОВЕРКА
$finalCount = $build->components()->count();
if ($finalCount < 7) {
Log::error('Сборка все еще имеет недостающее количество компонентов:', [
'build_id' => $build->id,
'expected' => 7,
'actual' => $finalCount
]);
}
return [
'build' => $build,
'components' => collect($createdComponents),
];
}
protected function generatePrompt($task_id, $custom_prompt, $budget)
{
$basePrompt = "Ты — эксперт по сборке ПК. Твоя задача — предложить **полную и сбалансированную сборку из 7 компонентов**, подходящую под запрос пользователя.";
if ($budget) {
$basePrompt .= " Бюджет: {$budget} рублей";
}
if ($custom_prompt) {
$basePrompt .= " Запрос пользователя: '{$custom_prompt}'.";
} elseif ($task_id) {
$basePrompt .= " Задача: #{$task_id}.";
}
$basePrompt .= " Ты **обязан** включить **ровно по одному компоненту каждого типа**: Процессор, Видеокарта, Материнская плата, ОЗУ, Блок питания, SSD, Корпус.";
$basePrompt .= " Используй ТОЛЬКО эти ID типов: 1=Процессор, 2=Видеокарта, 3=Материнская плата, 4=ОЗУ, 5=Блок питания, 6=SSD, 7=Корпус.";
$basePrompt .= " Не пропускай ни один тип. Не дублируй компоненты.";
$basePrompt .= " Все компоненты должны быть реальными, совместимыми и актуальными на 2025 год.";
$basePrompt .= " Ты **обязан** подобрать компоненты так, чтобы **общая стоимость не превышала** {$budget} рублей.";
$basePrompt .= " Никогда не пиши значения вроде 5600MHz — всегда используй строки: \"5600MHz\" или числа: 5600.";
$basePrompt .= " Не ставь лишние кавычки перед скобками.";
$basePrompt .= " ВАЖНО: Верни ТОЛЬКО валидный JSON без пояснений, комментариев, markdown.";
$basePrompt .= " Все значения в specifications должны быть строками или числами.";
$basePrompt .= " Не используй обратные слэши, звёздочки, решётки.";
$basePrompt .= " Верни **только чистый JSON-массив из 7 объектов**, без пояснений, комментариев, маркдауна.";
$basePrompt .= " Формат: [{\"name\":\"Название\",\"price\":999.99,\"component_type_id\":1,\"specifications\":{\"socket\":\"AM5\",\"tdp\":105}}, ...]";
$basePrompt .= " В specifications используй только строки или числа. Например: \"max_power\": 800, а не 800_watt.";
return $basePrompt;
}
protected function parseResponse($responseData)
{
if (!isset($responseData['choices'][0]['message']['content'])) {
throw new Exception('Ответ ИИ не содержит содержимого.');
}
$content = $responseData['choices'][0]['message']['content'];
// Удаляем markdown-блоки
$content = preg_replace('/^```(?:json)?\s*|\s*```$/m', '', $content);
// Находим первый JSON-массив
if (!preg_match('/\[[\s\S]*\]/', $content, $matches)) {
throw new Exception('Не найден JSON-массив в ответе ИИ.');
}
$jsonStr = $matches[0];
// Попытка декодировать без "починки"
$parsed = json_decode($jsonStr, true, 512, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
if (!is_array($parsed)) {
throw new Exception('Ожидался массив компонентов.');
}
foreach ($parsed as $index => $item) {
if (!is_array($item)) {
throw new Exception("Элемент #{$index} не является объектом.");
}
}
return $parsed;
}
protected function findOrCreateComponent($data)
{
// Валидация обязательных полей
if (!isset($data['name']) || !isset($data['component_type_id'])) {
throw new Exception('Компонент должен содержать name и component_type_id.');
}
$data['price'] = (float) ($data['price'] ?? 0);
$data['component_type_id'] = (int) ($data['component_type_id'] ?? 1);
// Очищаем specifications от некорректных значений
$specifications = [];
if (is_array($data['specifications'] ?? null)) {
foreach ($data['specifications'] as $key => $value) {
// Преобразуем всё в строки или числа
if (is_numeric($value)) {
$specifications[$key] = (float) $value;
} else {
$specifications[$key] = (string) $value;
}
}
}
$component = Component::firstOrCreate(
[
'name' => $data['name'],
'component_type_id' => $data['component_type_id'],
],
[
'price' => $data['price'],
'specifications' => $specifications,
'is_official' => true,
'created_by_user_id' => null,
]
);
// Обновляем цену, если компонент уже существует
if ($component->wasRecentlyCreated === false) {
$component->update(['price' => $data['price']]);
}
return $component;
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace App\Services;
use App\Models\Component;
class BuildValidator
{
/**
* Проверяет базовую совместимость компонентов в сборке.
*
* @param array $componentIds Массив ID компонентов
* @return array ['valid' => bool, 'errors' => array, 'warnings' => array]
*/
public function validateCompatibility(array $componentIds)
{
$components = Component::whereIn('id', $componentIds)->get();
if ($components->count() < 2) {
return [
'valid' => true,
'errors' => [],
'warnings' => []
];
}
$errors = [];
$warnings = [];
// Определяем типы компонентов по component_type_id (адаптируйте под вашу логику!)
$cpu = $components->firstWhere('component_type_id', 1); // 1 = CPU
$motherboard = $components->firstWhere('component_type_id', 3); // 3 = Motherboard
$ram = $components->firstWhere('component_type_id', 4); // 4 = RAM
$psu = $components->firstWhere('component_type_id', 5); // 5 = PSU
// 1. Проверка сокета (CPU ↔ Motherboard)
if ($cpu && $motherboard) {
$cpuSocket = $cpu->specifications['socket'] ?? null;
$mbSocket = $motherboard->specifications['socket'] ?? null;
if (!$cpuSocket || !$mbSocket) {
$warnings[] = "Не указан сокет для процессора или материнской платы.";
} elseif ($cpuSocket !== $mbSocket) {
$errors[] = "Сокет процессора '{$cpuSocket}' не совместим со сокетом материнской платы '{$mbSocket}'.";
}
}
// 2. Проверка типа ОЗУ (RAM ↔ Motherboard)
if ($ram && $motherboard) {
$ramType = $ram->specifications['type'] ?? null;
$mbRamType = $motherboard->specifications['memory_type'] ?? $motherboard->specifications['type'] ?? null;
if (!$ramType || !$mbRamType) {
$warnings[] = "Не указан тип памяти для ОЗУ или материнской платы.";
} elseif ($ramType !== $mbRamType) {
$errors[] = "Тип ОЗУ '{$ramType}' не совместим с типом памяти материнской платы '{$mbRamType}'.";
}
}
// 3. Проверка мощности БП (PSU ≥ сумма TDP)
if ($psu) {
$totalTdp = 0;
foreach ($components as $component) {
// Берём TDP из specifications, или 0 если нет
$tdp = $component->specifications['tdp'] ?? 0;
$totalTdp += (int) $tdp;
}
$psuWattage = $psu->specifications['wattage'] ?? 0;
if ($psuWattage < $totalTdp) {
$errors[] = "Мощность БП ({$psuWattage} Вт) < суммарного TDP ({$totalTdp} Вт). Рекомендуется ≥ {$totalTdp} Вт.";
}
}
return [
'valid' => empty($errors),
'errors' => $errors,
'warnings' => $warnings
];
}
}