107 lines
3.0 KiB
PHP
107 lines
3.0 KiB
PHP
<?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
|
|
{
|
|
public function index()
|
|
{
|
|
$components = Component::with('user', 'componentType')
|
|
->where('is_official', true)
|
|
->orWhere('created_by_user_id', auth()->id())
|
|
->get();
|
|
|
|
return response()->json($components);
|
|
}
|
|
|
|
|
|
|
|
public function show($id)
|
|
{
|
|
$component = Component::find($id);
|
|
|
|
if (!$component) {
|
|
return response()->json(['message' => 'Component not found'], 404);
|
|
}
|
|
|
|
return response()->json($component);
|
|
}
|
|
|
|
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' => 'Компонент удалён.'
|
|
]);
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|