tsett
This commit is contained in:
122
app/Http/Controllers/Admin/BrandsController.php
Normal file
122
app/Http/Controllers/Admin/BrandsController.php
Normal file
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Brand;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
use function Avifinfo\read;
|
||||
|
||||
class BrandsController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$brands = Brand::orderBy('name')->paginate(5);
|
||||
return view('admin.brands.brands', compact('brands'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255|unique:brands',
|
||||
'description' => 'nullable|string',
|
||||
'logo' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'website' => 'nullable|url|max:255',
|
||||
'country' => 'nullable|string|max:100',
|
||||
'is_active' => 'nullable|boolean',
|
||||
], [
|
||||
'name.required' => 'Название бренда обязательно',
|
||||
'name.unique' => 'Бренд с таким названием уже существует',
|
||||
'name.max' => 'Название не может быть длиннее 255 символов',
|
||||
'logo.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'logo.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'website.url' => 'Введите корректный URL сайта',
|
||||
'website.max' => 'URL сайта не может быть длиннее 255 символов',
|
||||
'country.max' => 'Название страны не может быть длиннее 100 символов',
|
||||
]);
|
||||
|
||||
if ($request->hasFile('logo')) {
|
||||
$logo = $request->file('logo');
|
||||
$logoName = Str::slug($request->name) . '.' . $logo->getClientOriginalExtension();
|
||||
$logo->move(public_path('assets/images/brands'), $logoName);
|
||||
$validated['logo'] = $logoName;
|
||||
}
|
||||
|
||||
$validated['slug'] = Str::slug($request->name);
|
||||
|
||||
$validated['is_active'] = $request->has('is_active');
|
||||
|
||||
Brand::create($validated);
|
||||
|
||||
return redirect()->route('admin.brands')
|
||||
->with('success', 'Бренд "' . $request->name . '" успешно создан');
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$brand = Brand::findOrFail($id);
|
||||
return view('admin.brands.edit', compact('brand'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$brand = Brand::findOrFail($id);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'logo' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'website' => 'nullable|url|max:255',
|
||||
'country' => 'nullable|string|max:100',
|
||||
'is_active' => 'nullable|boolean',
|
||||
], [
|
||||
'name.required' => 'Название бренда обязательно',
|
||||
'name.max' => 'Название не может быть длиннее 255 символов',
|
||||
'logo.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'logo.mimes' => 'Изображение должно быть в форматах: jpg, jpeg, png, svg',
|
||||
'logo.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'website.url' => 'Введите корректный URL сайта',
|
||||
'website.max' => 'URL сайта не может быть длиннее 255 символов',
|
||||
'country.max' => 'Название страны не может быть длиннее 100 символов',
|
||||
]);
|
||||
|
||||
$brand->name = $validated['name'];
|
||||
$brand->description = $validated['description'];
|
||||
$brand->website = $validated['website'];
|
||||
$brand->country = $validated['country'];
|
||||
$brand->is_active = $request->has('is_active');
|
||||
|
||||
if ($request->hasFile('logo')) {
|
||||
if ($brand->logo && file_exists(public_path('assets/images/brands/' . $brand->logo))) {
|
||||
unlink(public_path('assets/images/brands/' . $brand->logo));
|
||||
}
|
||||
|
||||
$logo = $request->file('logo');
|
||||
$logoName = Str::slug($request->name) . '.' . $logo->getClientOriginalExtension();
|
||||
$logo->move(public_path('assets/images/brands'), $logoName);
|
||||
$brand->logo = $logoName;
|
||||
}
|
||||
|
||||
$brand->save();
|
||||
|
||||
return redirect()->route('admin.brands')
|
||||
->with('success', 'Бренд "' . $brand->name . '" успешно обновлен');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$brand = Brand::findOrFail($id);
|
||||
|
||||
$brandName = $brand->name;
|
||||
|
||||
if ($brand->logo && file_exists(public_path('assets/images/brands/' . $brand->logo))) {
|
||||
unlink(public_path('assets/images/brands/' . $brand->logo));
|
||||
}
|
||||
|
||||
$brand->delete();
|
||||
|
||||
return redirect()->route('admin.brands')->with('success', 'Бренд "' . $brandName . '" успешно удален');
|
||||
}
|
||||
}
|
||||
217
app/Http/Controllers/Admin/CategoriesController.php
Normal file
217
app/Http/Controllers/Admin/CategoriesController.php
Normal file
@@ -0,0 +1,217 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Category;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class CategoriesController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$categories = Category::getFlatTree();
|
||||
|
||||
$allCategories = Category::getSelectTree(2);
|
||||
|
||||
return view('admin.categories.categories', compact('categories', 'allCategories'));
|
||||
}
|
||||
|
||||
public function moveUp($id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
|
||||
$previous = Category::where('parent_id', $category->parent_id)
|
||||
->where('sort_order', '<', $category->sort_order)
|
||||
->orderBy('sort_order', 'desc')
|
||||
->first();
|
||||
|
||||
if ($previous) {
|
||||
$temp = $category->sort_order;
|
||||
$category->sort_order = $previous->sort_order;
|
||||
$previous->sort_order = $temp;
|
||||
|
||||
$category->save();
|
||||
$previous->save();
|
||||
}
|
||||
|
||||
return redirect()->route('admin.categories')->with('success', 'Порядок категорий обновлен');
|
||||
}
|
||||
|
||||
public function moveDown($id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
|
||||
$next = Category::where('parent_id', $category->parent_id)
|
||||
->where('sort_order', '>', $category->sort_order)
|
||||
->orderBy('sort_order', 'asc')
|
||||
->first();
|
||||
|
||||
if ($next) {
|
||||
$temp = $category->sort_order;
|
||||
$category->sort_order = $next->sort_order;
|
||||
$next->sort_order = $temp;
|
||||
|
||||
$category->save();
|
||||
$next->save();
|
||||
}
|
||||
|
||||
return redirect()->route('admin.categories')->with('success', 'Порядок категорий обновлен');
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'parent_id' => 'nullable|exists:categories,id',
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'icon' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'image' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'is_active' => 'nullable|boolean',
|
||||
], [
|
||||
'name.required' => 'Название категории обязательно',
|
||||
'name.max' => 'Название не может быть длиннее 255 символов',
|
||||
'icon.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'icon.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'image.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'image.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'parent_id.exists' => 'Выбранная родительская категория не существует',
|
||||
]);
|
||||
|
||||
if ($request->hasFile('icon')) {
|
||||
$icon = $request->file('icon');
|
||||
$iconName = Str::slug($request->name) . '_icon.' . $icon->getClientOriginalExtension();
|
||||
$icon->move(public_path('assets/images/categories/icons'), $iconName);
|
||||
$validated['icon'] = $iconName;
|
||||
}
|
||||
|
||||
if ($request->hasFile('image')) {
|
||||
$image = $request->file('image');
|
||||
$imageName = Str::slug($request->name) . '_image.' . $image->getClientOriginalExtension();
|
||||
$image->move(public_path('assets/images/categories/images'), $imageName);
|
||||
$validated['image'] = $imageName;
|
||||
}
|
||||
|
||||
$validated['slug'] = Str::slug($request->name);
|
||||
|
||||
if (Category::where('slug', $validated['slug'])->exists()) {
|
||||
$validated['slug'] = $validated['slug'] . '-' . uniqid();
|
||||
}
|
||||
|
||||
$validated['is_active'] = $request->has('is_active');
|
||||
$validated['sort_order'] = Category::where('parent_id', $request->parent_id)->max('sort_order') + 10;
|
||||
|
||||
Category::create($validated);
|
||||
|
||||
return redirect()->route('admin.categories')
|
||||
->with('success', 'Категория "' . $request->name . '" успешно создана');
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
|
||||
$allCategories = Category::with('parent')
|
||||
->get()
|
||||
->map(function ($cat) use ($category) {
|
||||
$cat->level = $cat->calculateLevel();
|
||||
$cat->disabled = $cat->id == $category->id || $cat->isDescendantOf($category->id);
|
||||
return $cat;
|
||||
})
|
||||
->filter(function ($cat) {
|
||||
return $cat->level < 2;
|
||||
});
|
||||
|
||||
return view('admin.categories.edit', compact('category', 'allCategories'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
|
||||
$validated = $request->validate([
|
||||
'parent_id' => 'nullable|exists:categories,id',
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string',
|
||||
'icon' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'image' => 'nullable|image|mimes:jpg,jpeg,png,svg|max:2048',
|
||||
'is_active' => 'nullable|boolean',
|
||||
'remove_icon' => 'nullable|boolean',
|
||||
'remove_image' => 'nullable|boolean',
|
||||
], [
|
||||
'name.required' => 'Название категории обязательно',
|
||||
'name.max' => 'Название не может быть длиннее 255 символов',
|
||||
'icon.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'icon.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'image.image' => 'Загрузите изображение (jpg, png, svg)',
|
||||
'image.max' => 'Изображение не должно превышать 2 МБ',
|
||||
'parent_id.exists' => 'Выбранная родительская категория не существует',
|
||||
]);
|
||||
|
||||
$category->name = $validated['name'];
|
||||
$category->description = $validated['description'];
|
||||
$category->parent_id = $validated['parent_id'];
|
||||
$category->is_active = $request->has('is_active');
|
||||
|
||||
if ($request->hasFile('icon')) {
|
||||
if ($category->icon && file_exists(public_path('assets/images/categories/icons/' . $category->icon))) {
|
||||
unlink(public_path('assets/images/categories/icons/' . $category->icon));
|
||||
}
|
||||
|
||||
$icon = $request->file('icon');
|
||||
$iconName = Str::slug($request->name) . '_icon.' . $icon->getClientOriginalExtension();
|
||||
$icon->move(public_path('assets/images/categories/icons'), $iconName);
|
||||
$category->icon = $iconName;
|
||||
}
|
||||
|
||||
if ($request->has('remove_icon') && $request->remove_icon == 1) {
|
||||
if ($category->icon && file_exists(public_path('assets/images/categories/icons/' . $category->icon))) {
|
||||
unlink(public_path('assets/images/categories/icons/' . $category->icon));
|
||||
}
|
||||
$category->icon = null;
|
||||
}
|
||||
|
||||
if ($request->hasFile('image')) {
|
||||
if ($category->image && file_exists(public_path('assets/images/categories/images/' . $category->image))) {
|
||||
unlink(public_path('assets/images/categories/images/' . $category->image));
|
||||
}
|
||||
|
||||
$image = $request->file('image');
|
||||
$imageName = Str::slug($request->name) . '_image.' . $image->getClientOriginalExtension();
|
||||
$image->move(public_path('assets/images/categories/images'), $imageName);
|
||||
$category->image = $imageName;
|
||||
}
|
||||
|
||||
if ($request->has('remove_image') && $request->remove_image == 1) {
|
||||
if ($category->image && file_exists(public_path('assets/images/categories/images/' . $category->image))) {
|
||||
unlink(public_path('assets/images/categories/images/' . $category->image));
|
||||
}
|
||||
$category->image = null;
|
||||
}
|
||||
|
||||
$category->save();
|
||||
|
||||
return redirect()->route('admin.categories')
|
||||
->with('success', 'Категория "' . $category->name . '" успешно обновлена');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$category = Category::findOrFail($id);
|
||||
$categoryName = $category->name;
|
||||
|
||||
if ($category->icon && file_exists(public_path('assets/images/categories/icons/' . $category->icon))) {
|
||||
unlink(public_path('assets/images/categories/icons/' . $category->icon));
|
||||
}
|
||||
|
||||
if ($category->image && file_exists(public_path('assets/images/categories/images/' . $category->image))) {
|
||||
unlink(public_path('assets/images/categories/images/' . $category->image));
|
||||
}
|
||||
|
||||
$category->delete();
|
||||
|
||||
return redirect()->route('admin.categories')
|
||||
->with('success', 'Категория "' . $categoryName . '" успешно удалена');
|
||||
}
|
||||
}
|
||||
90
app/Http/Controllers/Admin/ContactController.php
Normal file
90
app/Http/Controllers/Admin/ContactController.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Contact;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class ContactController extends Controller
|
||||
{
|
||||
public function edit()
|
||||
{
|
||||
$contact = Contact::first();
|
||||
|
||||
if (!$contact) {
|
||||
$contact = Contact::create([
|
||||
'name' => 'Хвостики и лапки'
|
||||
]);
|
||||
}
|
||||
|
||||
return view('admin.contacts.edit', compact('contact'));
|
||||
}
|
||||
|
||||
public function update(Request $request)
|
||||
{
|
||||
$contact = Contact::first();
|
||||
|
||||
if (!$contact) {
|
||||
$contact = Contact::create();
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'description' => 'nullable|string|max:255',
|
||||
'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
|
||||
'favicon' => 'nullable|image|mimes:ico,png,svg|max:1024',
|
||||
'phone' => 'nullable|string|max:255',
|
||||
'email' => 'nullable|email|max:255',
|
||||
'address' => 'nullable|string|max:255',
|
||||
'work_hours' => 'nullable|string|max:255',
|
||||
'telegram' => 'nullable|string|max:255',
|
||||
'whatsapp' => 'nullable|string|max:255',
|
||||
'vkontakte' => 'nullable|string|max:255',
|
||||
'meta_title' => 'nullable|string|max:255',
|
||||
'meta_description' => 'nullable|string',
|
||||
'meta_keywords' => 'nullable|string'
|
||||
]);
|
||||
|
||||
if ($request->hasFile('logo')) {
|
||||
if ($contact->logo && file_exists(public_path('assets/images/logo/' . $contact->logo))) {
|
||||
unlink(public_path('assets/images/logo/' . $contact->logo));
|
||||
}
|
||||
|
||||
$logoFile = $request->file('logo');
|
||||
$logoName = time() . '_logo.' . $logoFile->getClientOriginalExtension();
|
||||
$logoFile->move(public_path('assets/images/logo'), $logoName);
|
||||
$contact->logo = $logoName;
|
||||
}
|
||||
|
||||
if ($request->hasFile('favicon')) {
|
||||
if ($contact->favicon && file_exists(public_path('assets/images/logo/' . $contact->favicon))) {
|
||||
unlink(public_path('assets/images/logo/' . $contact->favicon));
|
||||
}
|
||||
|
||||
$faviconFile = $request->file('favicon');
|
||||
$faviconName = time() . '_favicon.' . $faviconFile->getClientOriginalExtension();
|
||||
$faviconFile->move(public_path('assets/images/logo'), $faviconName);
|
||||
$contact->favicon = $faviconName;
|
||||
}
|
||||
|
||||
$contact->update([
|
||||
'name' => $request->name,
|
||||
'description' => $request->description,
|
||||
'phone' => $request->phone,
|
||||
'email' => $request->email,
|
||||
'address' => $request->address,
|
||||
'work_hours' => $request->work_hours,
|
||||
'telegram' => $request->telegram,
|
||||
'whatsapp' => $request->whatsapp,
|
||||
'vkontakte' => $request->vkontakte,
|
||||
'meta_title' => $request->meta_title,
|
||||
'meta_description' => $request->meta_description,
|
||||
'meta_keywords' => $request->meta_keywords
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.contacts.edit')
|
||||
->with('success', 'Данные сайта успешно обновлены');
|
||||
}
|
||||
}
|
||||
31
app/Http/Controllers/Admin/DashboardController.php
Normal file
31
app/Http/Controllers/Admin/DashboardController.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Product;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\ProductVariation;
|
||||
use App\Models\User;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$data = [
|
||||
'totalUsers' => User::count(),
|
||||
'totalProducts' => ProductVariation::count(),
|
||||
'totalOrders' => Order::count(),
|
||||
'recentOrders' => Order::with('user')
|
||||
->orderBy('created_at', 'desc')
|
||||
->limit(5)
|
||||
->get(),
|
||||
'popularProducts' => OrderItem::popular(10)->get(),
|
||||
'monthlyRevenue' => Order::getMonthlyRevenue(),
|
||||
|
||||
];
|
||||
return view('admin.dashboard', $data);
|
||||
}
|
||||
}
|
||||
61
app/Http/Controllers/Admin/OrdersController.php
Normal file
61
app/Http/Controllers/Admin/OrdersController.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class OrdersController extends Controller
|
||||
{
|
||||
/**
|
||||
* Список заказов
|
||||
*/
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = Order::with('user');
|
||||
|
||||
// Поиск по номеру заказа
|
||||
if ($request->filled('search')) {
|
||||
$query->where('order_number', 'like', "%{$request->search}%");
|
||||
}
|
||||
|
||||
// Фильтр по статусу
|
||||
if ($request->filled('status')) {
|
||||
$query->where('delivery_status', $request->status);
|
||||
}
|
||||
|
||||
$orders = $query->orderBy('created_at', 'desc')->paginate(20);
|
||||
|
||||
return view('admin.orders.orders', compact('orders'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Детали заказа
|
||||
*/
|
||||
public function show($id)
|
||||
{
|
||||
$order = Order::with(['user', 'items.variation.product'])->findOrFail($id);
|
||||
return view('admin.orders.show', compact('order'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновление статуса заказа
|
||||
*/
|
||||
public function updateStatus(Request $request, $id)
|
||||
{
|
||||
$request->validate([
|
||||
'delivery_status' => 'required|in:pending,processing,shipped,delivered,cancelled',
|
||||
'payment_status' => 'required|in:pending,paid,failed'
|
||||
]);
|
||||
|
||||
$order = Order::findOrFail($id);
|
||||
$order->update([
|
||||
'delivery_status' => $request->delivery_status,
|
||||
'payment_status' => $request->payment_status
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.orders.show', $order->id)
|
||||
->with('success', 'Статус заказа обновлен');
|
||||
}
|
||||
}
|
||||
107
app/Http/Controllers/Admin/PermissionsController.php
Normal file
107
app/Http/Controllers/Admin/PermissionsController.php
Normal file
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class PermissionsController extends Controller
|
||||
{
|
||||
/**
|
||||
* Список прав
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$permissions = Permission::orderBy('group')->orderBy('name')->paginate(10);
|
||||
return view('admin.permissions.permissions', compact('permissions'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохранить новое право
|
||||
*/
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255|unique:permissions',
|
||||
'slug' => 'required|string|max:255|unique:permissions',
|
||||
'group' => 'nullable|string|max:255',
|
||||
'description' => 'nullable|string'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.unique' => 'Право с таким названием уже существует',
|
||||
'slug.required' => 'Обязательно для заполнения',
|
||||
'slug.unique' => 'Право с таким slug уже существует'
|
||||
]);
|
||||
|
||||
Permission::create([
|
||||
'name' => $request->name,
|
||||
'slug' => $request->slug,
|
||||
'group' => $request->group,
|
||||
'description' => $request->description
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.permissions')
|
||||
->with('success', 'Право "' . $request->name . '" успешно создано');
|
||||
}
|
||||
|
||||
/**
|
||||
* Форма редактирования
|
||||
*/
|
||||
public function edit($id)
|
||||
{
|
||||
$permission = Permission::findOrFail($id);
|
||||
return view('admin.permissions.edit', compact('permission'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновить право
|
||||
*/
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$permission = Permission::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255|unique:permissions,name,' . $id,
|
||||
'slug' => 'required|string|max:255|unique:permissions,slug,' . $id,
|
||||
'group' => 'nullable|string|max:255',
|
||||
'description' => 'nullable|string'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.unique' => 'Право с таким названием уже существует',
|
||||
'slug.required' => 'Обязательно для заполнения',
|
||||
'slug.unique' => 'Право с таким slug уже существует'
|
||||
]);
|
||||
|
||||
$permission->update([
|
||||
'name' => $request->name,
|
||||
'slug' => $request->slug,
|
||||
'group' => $request->group,
|
||||
'description' => $request->description
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.permissions')
|
||||
->with('success', 'Право "' . $permission->name . '" успешно обновлено');
|
||||
}
|
||||
|
||||
/**
|
||||
* Удалить право
|
||||
*/
|
||||
public function destroy($id)
|
||||
{
|
||||
$permission = Permission::findOrFail($id);
|
||||
|
||||
$rolesCount = $permission->roles()->count();
|
||||
|
||||
$permissionName = $permission->name;
|
||||
$permission->delete();
|
||||
|
||||
$message = 'Право "' . $permissionName . '" успешно удалено';
|
||||
if ($rolesCount > 0) {
|
||||
$message .= ' Право было удалено у ' . $rolesCount . ' ролей.';
|
||||
}
|
||||
|
||||
return redirect()->route('admin.permissions')
|
||||
->with('success', $message);
|
||||
}
|
||||
}
|
||||
722
app/Http/Controllers/Admin/ProductController.php
Normal file
722
app/Http/Controllers/Admin/ProductController.php
Normal file
@@ -0,0 +1,722 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductVariation;
|
||||
use App\Models\ProductAttribute;
|
||||
use App\Models\VariationAttribute;
|
||||
use App\Models\VariationImage;
|
||||
use App\Models\Category;
|
||||
use App\Models\Brand;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ProductController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$products = Product::with(['category', 'brand', 'variations.images'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(15);
|
||||
|
||||
return view('admin.products.products', compact('products'));
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$categories = Category::getFlatTree();
|
||||
$brands = Brand::active()->orderBy('name')->get();
|
||||
|
||||
return view('admin.products.create', compact('categories', 'brands'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'category_id' => 'required|exists:categories,id',
|
||||
'brand_id' => 'nullable|exists:brands,id',
|
||||
'description' => 'nullable|string',
|
||||
'is_active' => 'nullable|boolean',
|
||||
|
||||
'meta_title' => 'nullable|string|max:255',
|
||||
'meta_description' => 'nullable|string',
|
||||
'meta_keywords' => 'nullable|string',
|
||||
|
||||
'attributes' => 'nullable|array',
|
||||
'attributes.*.key' => 'nullable|string',
|
||||
'attributes.*.value' => 'nullable|string',
|
||||
|
||||
'variations' => 'required|array|min:1',
|
||||
'variations.*.name' => 'required|string|max:255',
|
||||
'variations.*.sku' => 'required|string|max:100|unique:product_variations,sku',
|
||||
'variations.*.price' => 'required|numeric|min:0',
|
||||
'variations.*.old_price' => 'nullable|numeric|min:0',
|
||||
'variations.*.stock' => 'required|integer|min:0',
|
||||
'variations.*.is_default' => 'nullable|boolean',
|
||||
'variations.*.attributes' => 'nullable|array',
|
||||
'variations.*.attributes.flavor' => 'nullable|string|max:100',
|
||||
'variations.*.attributes.color' => 'nullable|string|max:100',
|
||||
'variations.*.attributes.size' => 'nullable|string|max:50',
|
||||
'variations.*.attributes.weight' => 'nullable|numeric|min:0',
|
||||
|
||||
'variations.*.images' => 'nullable|array',
|
||||
'variations.*.images.*' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
|
||||
], [
|
||||
'name.required' => 'Название товара обязательно',
|
||||
'category_id.required' => 'Выберите категорию',
|
||||
'variations.required' => 'Добавьте хотя бы одну вариацию',
|
||||
'variations.*.name.required' => 'Название вариации обязательно',
|
||||
'variations.*.sku.required' => 'Артикул обязателен',
|
||||
'variations.*.sku.unique' => 'Артикул "{value}" уже существует',
|
||||
'variations.*.price.required' => 'Цена обязательна',
|
||||
'variations.*.stock.required' => 'Количество обязательно',
|
||||
'variations.*.images.*.image' => 'Файл должен быть изображением',
|
||||
'variations.*.images.*.mimes' => 'Допустимые форматы: jpg, jpeg, png, webp',
|
||||
'variations.*.images.*.max' => 'Размер изображения не должен превышать 2 МБ',
|
||||
]);
|
||||
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
$slug = Str::slug($request->name);
|
||||
$baseSlug = $slug;
|
||||
$counter = 1;
|
||||
while (Product::where('slug', $slug)->exists()) {
|
||||
$slug = $baseSlug . '-' . $counter;
|
||||
$counter++;
|
||||
}
|
||||
|
||||
$product = Product::create([
|
||||
'name' => $validated['name'],
|
||||
'slug' => $slug,
|
||||
'category_id' => $validated['category_id'],
|
||||
'brand_id' => $validated['brand_id'] ?? null,
|
||||
'description' => $validated['description'] ?? null,
|
||||
'is_active' => $request->boolean('is_active'),
|
||||
'meta_title' => $validated['meta_title'] ?? null,
|
||||
'meta_description' => $validated['meta_description'] ?? null,
|
||||
'meta_keywords' => $validated['meta_keywords'] ?? null,
|
||||
]);
|
||||
|
||||
// Сохраняем атрибуты товара
|
||||
if (!empty($validated['attributes'])) {
|
||||
foreach ($validated['attributes'] as $attr) {
|
||||
if (!empty($attr['key']) && !empty($attr['value'])) {
|
||||
ProductAttribute::create([
|
||||
'product_id' => $product->id,
|
||||
'key' => $attr['key'],
|
||||
'value' => $attr['value'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Создаем вариации
|
||||
foreach ($validated['variations'] as $index => $variationData) {
|
||||
$variation = ProductVariation::create([
|
||||
'product_id' => $product->id,
|
||||
'name' => $variationData['name'],
|
||||
'sku' => $variationData['sku'],
|
||||
'price' => $variationData['price'],
|
||||
'old_price' => $variationData['old_price'] ?? null,
|
||||
'stock' => $variationData['stock'],
|
||||
'is_default' => $variationData['is_default'] ?? ($index == 0),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Сохраняем атрибуты вариации
|
||||
if (!empty($variationData['attributes'])) {
|
||||
foreach ($variationData['attributes'] as $key => $value) {
|
||||
if (!empty($value) || $value === 0 || $value === '0') {
|
||||
VariationAttribute::create([
|
||||
'variation_id' => $variation->id,
|
||||
'key' => $key,
|
||||
'value' => $value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Сохраняем изображения
|
||||
if ($request->hasFile("variations.{$index}.images")) {
|
||||
$files = $request->file("variations.{$index}.images");
|
||||
$validFiles = array_filter($files, function ($file) {
|
||||
return $file !== null && $file->isValid();
|
||||
});
|
||||
|
||||
if (!empty($validFiles)) {
|
||||
$this->saveVariationImages($validFiles, $product->slug, $variation->id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('admin.products.create')
|
||||
->with('success', 'Товар "' . $product->name . '" успешно создан');
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
Log::error('Product create error: ' . $e->getMessage());
|
||||
return redirect()->back()
|
||||
->withInput()
|
||||
->with('error', 'Ошибка при создании товара: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$product = Product::with(['variations.attributes', 'variations.images', 'attributes', 'brand', 'category'])->findOrFail($id);
|
||||
|
||||
$categories = Category::getFlatTree();
|
||||
|
||||
$brands = Brand::active()->orderBy('name')->get();
|
||||
|
||||
return view('admin.products.edit', compact('product', 'categories', 'brands'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$product = Product::findOrFail($id);
|
||||
|
||||
$validated = $request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'category_id' => 'required|exists:categories,id',
|
||||
'brand_id' => 'nullable|exists:brands,id',
|
||||
'description' => 'nullable|string',
|
||||
'is_active' => 'nullable|boolean',
|
||||
|
||||
'meta_title' => 'nullable|string|max:255',
|
||||
'meta_description' => 'nullable|string',
|
||||
'meta_keywords' => 'nullable|string',
|
||||
|
||||
'attributes' => 'nullable|array',
|
||||
'attributes.*.key' => 'nullable|string',
|
||||
'attributes.*.value' => 'nullable|string',
|
||||
|
||||
'variations' => 'required|array|min:1',
|
||||
'variations.*.id' => 'nullable|exists:product_variations,id',
|
||||
'variations.*.name' => 'required|string|max:255',
|
||||
'variations.*.sku' => 'required|string|max:100',
|
||||
'variations.*.price' => 'required|numeric|min:0',
|
||||
'variations.*.old_price' => 'nullable|numeric|min:0',
|
||||
'variations.*.stock' => 'required|integer|min:0',
|
||||
'variations.*.is_default' => 'nullable|boolean',
|
||||
'variations.*.attributes' => 'nullable|array',
|
||||
'variations.*.attributes.flavor' => 'nullable|string|max:100',
|
||||
'variations.*.attributes.color' => 'nullable|string|max:100',
|
||||
'variations.*.attributes.size' => 'nullable|string|max:50',
|
||||
'variations.*.attributes.weight' => 'nullable|numeric|min:0',
|
||||
|
||||
'variations.*.images' => 'nullable|array',
|
||||
'variations.*.images.*' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
|
||||
'variations.*.removed_images' => 'nullable|array',
|
||||
'variations.*.removed_images.*' => 'nullable|string',
|
||||
'variations.*.existing_images' => 'nullable|array',
|
||||
'variations.*.existing_images.*' => 'nullable|string',
|
||||
], [
|
||||
// Основные поля
|
||||
'name.required' => 'Название товара обязательно',
|
||||
'name.string' => 'Название товара должно быть строкой',
|
||||
'name.max' => 'Название товара не может превышать 255 символов',
|
||||
|
||||
'category_id.required' => 'Выберите категорию',
|
||||
'category_id.exists' => 'Выбранная категория не существует',
|
||||
|
||||
'brand_id.exists' => 'Выбранный бренд не существует',
|
||||
|
||||
'meta_title.max' => 'Meta Title не может превышать 255 символов',
|
||||
|
||||
// Вариации
|
||||
'variations.required' => 'Добавьте хотя бы одну вариацию',
|
||||
'variations.array' => 'Некорректный формат вариаций',
|
||||
'variations.min' => 'Добавьте хотя бы одну вариацию',
|
||||
|
||||
'variations.*.id.exists' => 'Вариация с ID :input не найдена',
|
||||
|
||||
'variations.*.name.required' => 'Название вариации обязательно',
|
||||
'variations.*.name.string' => 'Название вариации должно быть строкой',
|
||||
'variations.*.name.max' => 'Название вариации не может превышать 255 символов',
|
||||
|
||||
'variations.*.sku.required' => 'Артикул (SKU) обязателен',
|
||||
'variations.*.sku.string' => 'Артикул должен быть строкой',
|
||||
'variations.*.sku.max' => 'Артикул не может превышать 100 символов',
|
||||
|
||||
'variations.*.price.required' => 'Цена обязательна',
|
||||
'variations.*.price.numeric' => 'Цена должна быть числом',
|
||||
'variations.*.price.min' => 'Цена не может быть отрицательной',
|
||||
|
||||
'variations.*.old_price.numeric' => 'Старая цена должна быть числом',
|
||||
'variations.*.old_price.min' => 'Старая цена не может быть отрицательной',
|
||||
|
||||
'variations.*.stock.required' => 'Количество обязательно',
|
||||
'variations.*.stock.integer' => 'Количество должно быть целым числом',
|
||||
'variations.*.stock.min' => 'Количество не может быть отрицательным',
|
||||
|
||||
'variations.*.is_default.boolean' => 'Поле "Основная вариация" должно быть true или false',
|
||||
|
||||
'variations.*.attributes.array' => 'Некорректный формат атрибутов вариации',
|
||||
|
||||
'variations.*.attributes.flavor.string' => 'Вкус должен быть строкой',
|
||||
'variations.*.attributes.flavor.max' => 'Вкус не может превышать 100 символов',
|
||||
|
||||
'variations.*.attributes.color.string' => 'Цвет должен быть строкой',
|
||||
'variations.*.attributes.color.max' => 'Цвет не может превышать 100 символов',
|
||||
|
||||
'variations.*.attributes.size.string' => 'Размер должен быть строкой',
|
||||
'variations.*.attributes.size.max' => 'Размер не может превышать 50 символов',
|
||||
|
||||
'variations.*.attributes.weight.numeric' => 'Вес должен быть числом',
|
||||
'variations.*.attributes.weight.min' => 'Вес не может быть отрицательным',
|
||||
|
||||
// Изображения
|
||||
'variations.*.images.array' => 'Некорректный формат изображений',
|
||||
|
||||
'variations.*.images.*.image' => 'Файл должен быть изображением',
|
||||
'variations.*.images.*.mimes' => 'Допустимые форматы изображений: jpg, jpeg, png, webp',
|
||||
'variations.*.images.*.max' => 'Размер изображения не должен превышать 2 МБ',
|
||||
|
||||
'variations.*.removed_images.array' => 'Некорректный формат списка удаляемых изображений',
|
||||
'variations.*.removed_images.*.string' => 'Путь к удаляемому изображению должен быть строкой',
|
||||
|
||||
'variations.*.existing_images.array' => 'Некорректный формат списка существующих изображений',
|
||||
'variations.*.existing_images.*.string' => 'Путь к существующему изображению должен быть строкой',
|
||||
|
||||
// Атрибуты товара
|
||||
'attributes.array' => 'Некорректный формат характеристик',
|
||||
'attributes.*.key.string' => 'Название характеристики должно быть строкой',
|
||||
'attributes.*.value.string' => 'Значение характеристики должно быть строкой',
|
||||
]);
|
||||
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
// Обновляем slug если изменилось название
|
||||
$newSlug = Str::slug($validated['name']);
|
||||
$oldSlug = $product->slug;
|
||||
|
||||
if ($oldSlug != $newSlug) {
|
||||
$slug = $newSlug;
|
||||
$counter = 1;
|
||||
while (Product::where('slug', $slug)->where('id', '!=', $id)->exists()) {
|
||||
$slug = $newSlug . '-' . $counter;
|
||||
$counter++;
|
||||
}
|
||||
$product->slug = $slug;
|
||||
$this->renameProductFolder($oldSlug, $slug, $product);
|
||||
}
|
||||
|
||||
// Обновляем товар
|
||||
$product->update([
|
||||
'name' => $validated['name'],
|
||||
'description' => $validated['description'],
|
||||
'brand_id' => $validated['brand_id'],
|
||||
'category_id' => $validated['category_id'],
|
||||
'is_active' => $request->boolean('is_active'),
|
||||
'meta_title' => $validated['meta_title'],
|
||||
'meta_description' => $validated['meta_description'],
|
||||
'meta_keywords' => $validated['meta_keywords'],
|
||||
]);
|
||||
|
||||
// Обновляем атрибуты товара
|
||||
ProductAttribute::where('product_id', $product->id)->delete();
|
||||
if (!empty($validated['attributes'])) {
|
||||
foreach ($validated['attributes'] as $attr) {
|
||||
if (!empty($attr['key']) && !empty($attr['value'])) {
|
||||
ProductAttribute::create([
|
||||
'product_id' => $product->id,
|
||||
'key' => $attr['key'],
|
||||
'value' => $attr['value'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$existingVariationIds = [];
|
||||
|
||||
foreach ($validated['variations'] as $index => $variationData) {
|
||||
if (isset($variationData['id']) && $variationData['id']) {
|
||||
$variation = ProductVariation::find($variationData['id']);
|
||||
|
||||
if ($variation && $variation->product_id == $product->id) {
|
||||
$variation->update([
|
||||
'name' => $variationData['name'],
|
||||
'sku' => $variationData['sku'],
|
||||
'price' => $variationData['price'],
|
||||
'old_price' => $variationData['old_price'] ?? null,
|
||||
'stock' => $variationData['stock'],
|
||||
'is_default' => $variationData['is_default'] ?? false,
|
||||
]);
|
||||
|
||||
// Обновляем атрибуты вариации
|
||||
VariationAttribute::where('variation_id', $variation->id)->delete();
|
||||
if (!empty($variationData['attributes'])) {
|
||||
foreach ($variationData['attributes'] as $key => $value) {
|
||||
if (!empty($value) || $value === 0 || $value === '0') {
|
||||
VariationAttribute::create([
|
||||
'variation_id' => $variation->id,
|
||||
'key' => $key,
|
||||
'value' => $value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== ОБРАБОТКА ИЗОБРАЖЕНИЙ ==========
|
||||
// 1. Удаляем отмеченные изображения
|
||||
if (!empty($variationData['removed_images']) && is_array($variationData['removed_images'])) {
|
||||
foreach ($variationData['removed_images'] as $imagePath) {
|
||||
$image = VariationImage::where('variation_id', $variation->id)
|
||||
->where('path', $imagePath)
|
||||
->first();
|
||||
if ($image) {
|
||||
$fullPath = public_path($imagePath);
|
||||
if (file_exists($fullPath) && is_file($fullPath)) {
|
||||
@unlink($fullPath);
|
||||
}
|
||||
$image->delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Обновляем порядок существующих изображений
|
||||
if (!empty($variationData['existing_images']) && is_array($variationData['existing_images'])) {
|
||||
foreach ($variationData['existing_images'] as $sortOrder => $imagePath) {
|
||||
$image = VariationImage::where('variation_id', $variation->id)
|
||||
->where('path', $imagePath)
|
||||
->first();
|
||||
if ($image) {
|
||||
$image->sort_order = $sortOrder;
|
||||
$image->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Сохраняем новые изображения
|
||||
if ($request->hasFile("variations.{$index}.images")) {
|
||||
$files = $request->file("variations.{$index}.images");
|
||||
$validFiles = array_filter($files, function ($file) {
|
||||
return $file !== null && $file->isValid();
|
||||
});
|
||||
|
||||
if (!empty($validFiles)) {
|
||||
$this->saveVariationImages($validFiles, $product->slug, $variation->id);
|
||||
}
|
||||
}
|
||||
|
||||
$existingVariationIds[] = $variation->id;
|
||||
}
|
||||
} else {
|
||||
// Создаем новую вариацию
|
||||
$variation = ProductVariation::create([
|
||||
'product_id' => $product->id,
|
||||
'name' => $variationData['name'],
|
||||
'sku' => $variationData['sku'],
|
||||
'price' => $variationData['price'],
|
||||
'old_price' => $variationData['old_price'] ?? null,
|
||||
'stock' => $variationData['stock'],
|
||||
'is_default' => $variationData['is_default'] ?? false,
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
// Сохраняем атрибуты
|
||||
if (!empty($variationData['attributes'])) {
|
||||
foreach ($variationData['attributes'] as $key => $value) {
|
||||
if (!empty($value) || $value === 0 || $value === '0') {
|
||||
VariationAttribute::create([
|
||||
'variation_id' => $variation->id,
|
||||
'key' => $key,
|
||||
'value' => $value,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Сохраняем изображения
|
||||
if ($request->hasFile("variations.{$index}.images")) {
|
||||
$files = $request->file("variations.{$index}.images");
|
||||
$validFiles = array_filter($files, function ($file) {
|
||||
return $file !== null && $file->isValid();
|
||||
});
|
||||
|
||||
if (!empty($validFiles)) {
|
||||
$this->saveVariationImages($validFiles, $product->slug, $variation->id);
|
||||
}
|
||||
}
|
||||
|
||||
$existingVariationIds[] = $variation->id;
|
||||
}
|
||||
}
|
||||
|
||||
// Удаляем вариации, которых нет в форме
|
||||
$variationsToDelete = ProductVariation::where('product_id', $product->id)
|
||||
->whereNotIn('id', $existingVariationIds)
|
||||
->get();
|
||||
|
||||
foreach ($variationsToDelete as $variation) {
|
||||
// Удаляем изображения из БД и файловой системы
|
||||
$images = VariationImage::where('variation_id', $variation->id)->get();
|
||||
foreach ($images as $image) {
|
||||
$fullPath = public_path($image->path);
|
||||
if (file_exists($fullPath) && is_file($fullPath)) {
|
||||
@unlink($fullPath);
|
||||
}
|
||||
$image->delete();
|
||||
}
|
||||
|
||||
// Удаляем атрибуты
|
||||
VariationAttribute::where('variation_id', $variation->id)->delete();
|
||||
|
||||
// Удаляем папку
|
||||
$folderPath = public_path('assets/images/products/' . $product->slug . '/variation_' . $variation->id);
|
||||
if (file_exists($folderPath) && is_dir($folderPath)) {
|
||||
$this->deleteDirectory($folderPath);
|
||||
}
|
||||
|
||||
$variation->delete();
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('admin.products')
|
||||
->with('success', 'Товар "' . $product->name . '" успешно обновлен');
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
Log::error('Product update error: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
|
||||
return redirect()->back()
|
||||
->withInput()
|
||||
->with('error', 'Ошибка при обновлении товара: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function saveVariationImages($images, $productSlug, $variationId)
|
||||
{
|
||||
$folder = public_path('assets/images/products/' . $productSlug . '/variation_' . $variationId);
|
||||
|
||||
if (!file_exists($folder)) {
|
||||
mkdir($folder, 0755, true);
|
||||
}
|
||||
|
||||
// Получаем текущий максимальный sort_order
|
||||
$maxSortOrder = VariationImage::where('variation_id', $variationId)->max('sort_order');
|
||||
$nextIndex = ($maxSortOrder !== null) ? $maxSortOrder + 1 : 0;
|
||||
|
||||
foreach ($images as $index => $image) {
|
||||
if ($image && $image->isValid()) {
|
||||
$extension = $image->getClientOriginalExtension();
|
||||
$filename = ($nextIndex + $index) . '.' . $extension;
|
||||
$destinationPath = $folder . '/' . $filename;
|
||||
|
||||
$image->move($folder, $filename);
|
||||
|
||||
if (file_exists($destinationPath)) {
|
||||
VariationImage::create([
|
||||
'variation_id' => $variationId,
|
||||
'path' => 'assets/images/products/' . $productSlug . '/variation_' . $variationId . '/' . $filename,
|
||||
'sort_order' => $nextIndex + $index,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function renameProductFolder($oldSlug, $newSlug, $product)
|
||||
{
|
||||
$oldFolder = public_path('assets/images/products/' . $oldSlug);
|
||||
$newFolder = public_path('assets/images/products/' . $newSlug);
|
||||
|
||||
if (file_exists($oldFolder) && is_dir($oldFolder)) {
|
||||
if (file_exists($newFolder)) {
|
||||
$this->mergeDirectories($oldFolder, $newFolder);
|
||||
$this->deleteDirectory($oldFolder);
|
||||
} else {
|
||||
rename($oldFolder, $newFolder);
|
||||
}
|
||||
|
||||
// Обновляем пути в БД
|
||||
$variations = ProductVariation::where('product_id', $product->id)->get();
|
||||
foreach ($variations as $variation) {
|
||||
$images = VariationImage::where('variation_id', $variation->id)->get();
|
||||
foreach ($images as $image) {
|
||||
$image->path = str_replace('assets/images/products/' . $oldSlug, 'assets/images/products/' . $newSlug, $image->path);
|
||||
$image->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function mergeDirectories($source, $destination)
|
||||
{
|
||||
if (!is_dir($destination)) {
|
||||
mkdir($destination, 0777, true);
|
||||
}
|
||||
|
||||
$files = scandir($source);
|
||||
foreach ($files as $file) {
|
||||
if ($file == '.' || $file == '..') continue;
|
||||
|
||||
$sourcePath = $source . '/' . $file;
|
||||
$destPath = $destination . '/' . $file;
|
||||
|
||||
if (is_dir($sourcePath)) {
|
||||
$this->mergeDirectories($sourcePath, $destPath);
|
||||
rmdir($sourcePath);
|
||||
} else {
|
||||
copy($sourcePath, $destPath);
|
||||
unlink($sourcePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function deleteDirectory($dir)
|
||||
{
|
||||
if (!file_exists($dir)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!is_dir($dir)) {
|
||||
return unlink($dir);
|
||||
}
|
||||
|
||||
foreach (scandir($dir) as $item) {
|
||||
if ($item == '.' || $item == '..') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!$this->deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return rmdir($dir);
|
||||
}
|
||||
|
||||
public function checkSku(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'sku' => 'required|string',
|
||||
'variation_id' => 'nullable|exists:product_variations,id',
|
||||
'product_id' => 'nullable|exists:products,id'
|
||||
]);
|
||||
|
||||
$sku = $request->sku;
|
||||
$variationId = $request->variation_id;
|
||||
$productId = $request->product_id;
|
||||
|
||||
$isUnique = ProductVariation::isSkuUnique($sku, $variationId, $productId);
|
||||
|
||||
return response()->json([
|
||||
'unique' => $isUnique,
|
||||
'message' => $isUnique ? null : 'Артикул "' . $sku . '" уже используется'
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$product = Product::findOrFail($id);
|
||||
$productName = $product->name;
|
||||
|
||||
foreach ($product->variations as $variation) {
|
||||
$images = VariationImage::where('variation_id', $variation->id)->get();
|
||||
foreach ($images as $image) {
|
||||
$fullPath = public_path($image->path);
|
||||
if (file_exists($fullPath) && is_file($fullPath)) {
|
||||
@unlink($fullPath);
|
||||
}
|
||||
}
|
||||
$folderPath = public_path('assets/images/products/' . $product->slug . '/variation_' . $variation->id);
|
||||
if (file_exists($folderPath) && is_dir($folderPath)) {
|
||||
$this->deleteDirectory($folderPath);
|
||||
}
|
||||
}
|
||||
|
||||
$productFolder = public_path('assets/images/products/' . $product->slug);
|
||||
if (file_exists($productFolder) && is_dir($productFolder)) {
|
||||
$this->deleteDirectory($productFolder);
|
||||
}
|
||||
|
||||
$product->delete();
|
||||
|
||||
return redirect()->route('admin.products')
|
||||
->with('success', 'Товар "' . $productName . '" успешно удален');
|
||||
}
|
||||
|
||||
public function duplicate($id)
|
||||
{
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
$original = Product::with(['variations.attributes', 'variations.images'])->findOrFail($id);
|
||||
|
||||
$newProduct = $original->replicate();
|
||||
$newProduct->name = $original->name . ' (копия)';
|
||||
$newProduct->slug = Str::slug($newProduct->name) . '-' . uniqid();
|
||||
$newProduct->created_at = now();
|
||||
$newProduct->updated_at = now();
|
||||
$newProduct->save();
|
||||
|
||||
// Копируем атрибуты товара
|
||||
foreach ($original->attributes as $attr) {
|
||||
ProductAttribute::create([
|
||||
'product_id' => $newProduct->id,
|
||||
'key' => $attr->key,
|
||||
'value' => $attr->value,
|
||||
]);
|
||||
}
|
||||
|
||||
// Копируем вариации
|
||||
foreach ($original->variations as $variation) {
|
||||
$newVariation = $variation->replicate();
|
||||
$newVariation->product_id = $newProduct->id;
|
||||
$newVariation->sku = $variation->sku . '-copy-' . uniqid();
|
||||
$newVariation->created_at = now();
|
||||
$newVariation->updated_at = now();
|
||||
$newVariation->save();
|
||||
|
||||
// Копируем атрибуты вариации
|
||||
foreach ($variation->attributes as $attr) {
|
||||
VariationAttribute::create([
|
||||
'variation_id' => $newVariation->id,
|
||||
'key' => $attr->key,
|
||||
'value' => $attr->value,
|
||||
]);
|
||||
}
|
||||
|
||||
// Копируем изображения
|
||||
$newFolder = public_path('assets/images/products/' . $newProduct->slug . '/variation_' . $newVariation->id);
|
||||
if (!file_exists($newFolder)) {
|
||||
mkdir($newFolder, 0755, true);
|
||||
}
|
||||
|
||||
foreach ($variation->images as $image) {
|
||||
$oldPath = public_path($image->path);
|
||||
$filename = basename($image->path);
|
||||
$newPath = $newFolder . '/' . $filename;
|
||||
|
||||
if (file_exists($oldPath)) {
|
||||
copy($oldPath, $newPath);
|
||||
VariationImage::create([
|
||||
'variation_id' => $newVariation->id,
|
||||
'path' => 'assets/images/products/' . $newProduct->slug . '/variation_' . $newVariation->id . '/' . $filename,
|
||||
'sort_order' => $image->sort_order,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('admin.products')
|
||||
->with('success', 'Товар "' . $original->name . '" успешно скопирован. Новая версия: "' . $newProduct->name . '"');
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
Log::error('Product duplicate error: ' . $e->getMessage());
|
||||
return redirect()->back()
|
||||
->with('error', 'Ошибка при копировании товара: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
109
app/Http/Controllers/Admin/RolesController.php
Normal file
109
app/Http/Controllers/Admin/RolesController.php
Normal file
@@ -0,0 +1,109 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use App\Models\Permission;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class RolesController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$roles = Role::with('permissions')->paginate(15);
|
||||
|
||||
return view('admin.roles.roles', compact('roles'));
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$permissions = Permission::all();
|
||||
|
||||
return view('admin.roles.create', compact('permissions'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'slug' => 'required|string|max:255|unique:roles',
|
||||
'description' => 'nullable|string',
|
||||
'permissions' => 'nullable|array',
|
||||
'permissions.*' => 'exists:permissions,id'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.max' => 'Не более 255 символов',
|
||||
'slug.required' => 'Обязательно для заполнения',
|
||||
'slug.max' => 'Не более 255 символов',
|
||||
'slug.unique' => 'Такой slug уже существует',
|
||||
'permissions.*.exists' => 'Право не найдено'
|
||||
]);
|
||||
|
||||
$role = Role::create([
|
||||
'name' => $request->name,
|
||||
'slug' => $request->slug,
|
||||
'description' => $request->description
|
||||
]);
|
||||
|
||||
if ($request->has('permissions')) {
|
||||
$role->permissions()->attach($request->permissions);
|
||||
}
|
||||
|
||||
return redirect()->route('admin.roles')
|
||||
->with('success', 'Роль "' . $role->name . '" успешно создана');
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$role = Role::with('permissions')->findOrFail($id);
|
||||
$permissions = Permission::all();
|
||||
|
||||
return view('admin.roles.edit', compact('role', 'permissions'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$role = Role::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'slug' => 'required|string|max:255|unique:roles,slug,' . $id,
|
||||
'description' => 'nullable|string',
|
||||
'permissions' => 'nullable|array',
|
||||
'permissions.*' => 'exists:permissions,id'
|
||||
]);
|
||||
|
||||
$role->update([
|
||||
'name' => $request->name,
|
||||
'slug' => $request->slug,
|
||||
'description' => $request->description
|
||||
]);
|
||||
|
||||
$role->permissions()->sync($request->permissions ?? []);
|
||||
|
||||
return redirect()->route('admin.roles')
|
||||
->with('success', 'Роль "' . $role->name . '" успешно обновлена');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$role = Role::findOrFail($id);
|
||||
|
||||
$usersCount = User::where('role_id', $role->id)->count();
|
||||
|
||||
if ($usersCount > 0) {
|
||||
return redirect()->route('admin.roles')
|
||||
->with('error', 'Нельзя удалить роль, у которой есть пользователи');
|
||||
}
|
||||
|
||||
$roleName = $role->name;
|
||||
$role->permissions()->detach();
|
||||
$role->delete();
|
||||
|
||||
return redirect()->route('admin.roles')
|
||||
->with('success', 'Роль "' . $roleName . '" успешно удалена');
|
||||
}
|
||||
}
|
||||
133
app/Http/Controllers/Admin/UsersController.php
Normal file
133
app/Http/Controllers/Admin/UsersController.php
Normal file
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Models\Role;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
class UsersController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
$query = User::with('role');
|
||||
|
||||
if ($request->filled('search')) {
|
||||
$search = $request->search;
|
||||
$query->where(function ($q) use ($search) {
|
||||
$q->where('name', 'like', "%{$search}%")
|
||||
->orWhere('email', 'like', "%{$search}%");
|
||||
});
|
||||
}
|
||||
|
||||
$users = $query->orderBy('created_at', 'desc')->paginate(15);
|
||||
$users->appends($request->all());
|
||||
|
||||
return view('admin.users.users', compact('users'));
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$roles = Role::all();
|
||||
return view('admin.users.create', compact('roles'));
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => 'required|email|max:255|unique:users',
|
||||
'phone' => 'nullable|string|max:20',
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
'role_id' => 'required|exists:roles,id'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.max' => 'Не более 255 символов',
|
||||
'email.required' => 'Обязательно для заполнения',
|
||||
'email.email' => 'Введите корректный email',
|
||||
'email.max' => 'Не более 255 символов',
|
||||
'email.unique' => 'Этот email уже занят',
|
||||
'phone.max' => 'Не более 20 символов',
|
||||
'password.required' => 'Обязательно для заполнения',
|
||||
'password.min' => 'Минимум 8 символов',
|
||||
'password.confirmed' => 'Пароли не совпадают',
|
||||
'role_id.required' => 'Обязательно для заполнения'
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'phone' => $request->phone,
|
||||
'password' => Hash::make($request->password),
|
||||
'role_id' => $request->role_id
|
||||
]);
|
||||
|
||||
return redirect()->route('admin.users')
|
||||
->with('success', 'Пользователь "' . $user->name . '" успешно создан');
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
$roles = Role::all();
|
||||
return view('admin.users.edit', compact('user', 'roles'));
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => 'required|email|max:255|unique:users,email,' . $id,
|
||||
'phone' => 'nullable|string|max:20',
|
||||
'password' => 'nullable|string|min:8|confirmed',
|
||||
'role_id' => 'required|exists:roles,id'
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'name.max' => 'Не более 255 символов',
|
||||
'email.required' => 'Обязательно для заполнения',
|
||||
'email.email' => 'Введите корректный email',
|
||||
'email.max' => 'Не более 255 символов',
|
||||
'email.unique' => 'Этот email уже занят',
|
||||
'phone.max' => 'Не более 20 символов',
|
||||
'password.min' => 'Минимум 8 символов',
|
||||
'password.confirmed' => 'Пароли не совпадают',
|
||||
'role_id.required' => 'Обязательно для заполнения'
|
||||
]);
|
||||
|
||||
$data = [
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'phone' => $request->phone,
|
||||
'role_id' => $request->role_id
|
||||
];
|
||||
|
||||
if ($request->filled('password')) {
|
||||
$data['password'] = Hash::make($request->password);
|
||||
}
|
||||
|
||||
$user->update($data);
|
||||
|
||||
return redirect()->route('admin.users')
|
||||
->with('success', 'Пользователь "' . $user->name . '" успешно обновлен');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$user = User::findOrFail($id);
|
||||
|
||||
if ($user->id === auth()->id()) {
|
||||
return redirect()->route('admin.users')
|
||||
->with('error', 'Нельзя удалить самого себя');
|
||||
}
|
||||
|
||||
$userName = $user->name;
|
||||
$user->delete();
|
||||
|
||||
return redirect()->route('admin.users')
|
||||
->with('success', 'Пользователь "' . $userName . '" успешно удален');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user