Files
componentsPC/app/Http/Controllers/ComponentsController.php

214 lines
6.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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