tsett
This commit is contained in:
27
app/Console/Kernel.php
Normal file
27
app/Console/Kernel.php
Normal file
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console;
|
||||
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
|
||||
|
||||
class Kernel extends ConsoleKernel
|
||||
{
|
||||
/**
|
||||
* Define the application's command schedule.
|
||||
*/
|
||||
protected function schedule(Schedule $schedule): void
|
||||
{
|
||||
// $schedule->command('inspire')->hourly();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the commands for the application.
|
||||
*/
|
||||
protected function commands(): void
|
||||
{
|
||||
$this->load(__DIR__.'/Commands');
|
||||
|
||||
require base_path('routes/console.php');
|
||||
}
|
||||
}
|
||||
30
app/Exceptions/Handler.php
Normal file
30
app/Exceptions/Handler.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Throwable;
|
||||
|
||||
class Handler extends ExceptionHandler
|
||||
{
|
||||
/**
|
||||
* The list of the inputs that are never flashed to the session on validation exceptions.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $dontFlash = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register the exception handling callbacks for the application.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
$this->reportable(function (Throwable $e) {
|
||||
//
|
||||
});
|
||||
}
|
||||
}
|
||||
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 . '" успешно удален');
|
||||
}
|
||||
}
|
||||
50
app/Http/Controllers/Auth/LoginController.php
Normal file
50
app/Http/Controllers/Auth/LoginController.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class LoginController extends Controller
|
||||
{
|
||||
public function showLoginForm()
|
||||
{
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
public function login(Request $request)
|
||||
{
|
||||
$credentials = $request->validate([
|
||||
'email' => 'required|email',
|
||||
'password' => 'required|string',
|
||||
], [
|
||||
'email.required' => 'Введите email',
|
||||
'email.email' => 'Введите корректный email',
|
||||
'password.required' => 'Введите пароль',
|
||||
]);
|
||||
|
||||
$remember = $request->has('save_checkbox');
|
||||
|
||||
if (Auth::attempt($credentials, $remember)) {
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->intended('/');
|
||||
}
|
||||
|
||||
return back()->withErrors([
|
||||
'email' => 'Неверный email или пароль',
|
||||
])->onlyInput('email');
|
||||
}
|
||||
|
||||
public function logout(Request $request)
|
||||
{
|
||||
Auth::logout();
|
||||
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect('/');
|
||||
}
|
||||
}
|
||||
63
app/Http/Controllers/Auth/RegisterController.php
Normal file
63
app/Http/Controllers/Auth/RegisterController.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\User;
|
||||
use App\Models\Role;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
|
||||
class RegisterController extends Controller
|
||||
{
|
||||
public function showRegisterForm()
|
||||
{
|
||||
return view('auth.register');
|
||||
}
|
||||
|
||||
public function register(Request $request)
|
||||
{
|
||||
$validator = Validator::make($request->all(), [
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => 'required|string|email|max:255|unique:users',
|
||||
'phone' => 'required|string|max:20',
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
'save_checkbox' => 'accepted'
|
||||
], [
|
||||
'name.required' => 'Обязательно введите Ваше имя',
|
||||
'email.required' => 'Обязательно введите адрес электронной почты',
|
||||
'phone.required' => 'Обязательно введите Ваш номер телефона',
|
||||
'email.email' => 'Введите корректный адрес электронной почты',
|
||||
'email.unique' => 'Пользователь с таким адресом электронной почты уже существует',
|
||||
'password.required' => 'Поле пароль обязательно для заполнения',
|
||||
'password.min' => 'Пароль должен содержать минимум 8 символов',
|
||||
'password.confirmed' => 'Пароли не совпадают',
|
||||
'save_checkbox.accepted' => 'Необходимо согласие на обработку персональных данных'
|
||||
]);
|
||||
|
||||
if ($validator->fails()) {
|
||||
return redirect()->back()
|
||||
->withErrors($validator)
|
||||
->withInput();
|
||||
}
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'phone' => $request->phone,
|
||||
'password' => Hash::make($request->password),
|
||||
]);
|
||||
|
||||
$defaultRole = Role::where('slug', 'registered_user')->first();
|
||||
if ($defaultRole) {
|
||||
$user->role()->attach($defaultRole->id);
|
||||
}
|
||||
|
||||
auth()->login($user);
|
||||
|
||||
return redirect()->intended('/')
|
||||
->with('success', 'Регистрация прошла успешно!');
|
||||
}
|
||||
}
|
||||
113
app/Http/Controllers/BrandController.php
Normal file
113
app/Http/Controllers/BrandController.php
Normal file
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Brand;
|
||||
use App\Models\Category;
|
||||
use App\Models\Product;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class BrandController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display all brands.
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$brands = Brand::active()
|
||||
->withCount('products')
|
||||
->orderBy('name')
|
||||
->paginate(20);
|
||||
|
||||
return view('brands.brands', compact('brands'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Display products by brand with filters.
|
||||
*/
|
||||
public function show(Request $request, $slug)
|
||||
{
|
||||
$brand = Brand::where('slug', $slug)
|
||||
->active()
|
||||
->firstOrFail();
|
||||
|
||||
// Получаем ID категорий, в которых есть товары этого бренда
|
||||
$categoryIds = $brand->products()
|
||||
->active()
|
||||
->pluck('category_id')
|
||||
->unique()
|
||||
->filter()
|
||||
->values()
|
||||
->toArray();
|
||||
|
||||
// Загружаем категории с родителями для построения полного пути
|
||||
$categories = Category::with(['parent', 'parent.parent'])
|
||||
->whereIn('id', $categoryIds)
|
||||
->active()
|
||||
->get();
|
||||
|
||||
// Формируем полный путь для каждой категории
|
||||
$categoriesWithPath = $categories->map(function ($category) {
|
||||
$path = [];
|
||||
$current = $category;
|
||||
|
||||
while ($current) {
|
||||
$path[] = $current->name;
|
||||
$current = $current->parent;
|
||||
}
|
||||
|
||||
$category->full_path = implode(' / ', array_reverse($path));
|
||||
return $category;
|
||||
})->sortBy('full_path');
|
||||
|
||||
// Диапазон цен
|
||||
$priceRange = DB::table('products')
|
||||
->join('product_variations', 'products.id', '=', 'product_variations.product_id')
|
||||
->where('products.brand_id', $brand->id)
|
||||
->where('products.is_active', true)
|
||||
->selectRaw('MIN(product_variations.price) as min_price, MAX(product_variations.price) as max_price')
|
||||
->first();
|
||||
|
||||
$minPrice = $priceRange->min_price ?? 0;
|
||||
$maxPrice = $priceRange->max_price ?? 10000;
|
||||
|
||||
// Запрос на продукты с фильтрацией
|
||||
$productsQuery = Product::with(['variations', 'category'])
|
||||
->where('brand_id', $brand->id)
|
||||
->active();
|
||||
|
||||
// Фильтрация по категориям
|
||||
if ($request->has('categories') && !empty($request->categories)) {
|
||||
$productsQuery->whereIn('category_id', $request->categories);
|
||||
}
|
||||
|
||||
// Фильтрация по цене
|
||||
if ($request->has('price-min') && $request->has('price-max')) {
|
||||
$min = (float) $request->get('price-min');
|
||||
$max = (float) $request->get('price-max');
|
||||
|
||||
$productsQuery->whereHas('variations', function ($q) use ($min, $max) {
|
||||
$q->whereBetween('price', [$min, $max]);
|
||||
});
|
||||
}
|
||||
|
||||
// Сортировка
|
||||
$sort = $request->get('sort', 'created_at');
|
||||
$order = $request->get('order', 'desc');
|
||||
|
||||
if ($sort === 'price') {
|
||||
$productsQuery->withMin('variations', 'price')
|
||||
->orderBy('variations_min_price', $order);
|
||||
} elseif ($sort === 'name') {
|
||||
$productsQuery->orderBy('name', $order);
|
||||
} else {
|
||||
$productsQuery->orderBy($sort, $order);
|
||||
}
|
||||
|
||||
$products = $productsQuery->paginate(20);
|
||||
$products->appends($request->all());
|
||||
|
||||
return view('brands.show', compact('brand', 'products', 'categoriesWithPath', 'minPrice', 'maxPrice'));
|
||||
}
|
||||
}
|
||||
179
app/Http/Controllers/CartController.php
Normal file
179
app/Http/Controllers/CartController.php
Normal file
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\CartItem;
|
||||
use App\Models\ProductVariation;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class CartController extends Controller
|
||||
{
|
||||
/**
|
||||
* Отобразить корзину
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$cartItems = CartItem::getCartQuery()->get();
|
||||
$total = $cartItems->sum('total');
|
||||
|
||||
return view('cart.show', compact('cartItems', 'total'));
|
||||
}
|
||||
|
||||
public function add(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'variation_id' => 'required|exists:product_variations,id',
|
||||
'quantity' => 'required|integer|min:1'
|
||||
]);
|
||||
|
||||
$variation = ProductVariation::with('product')->find($request->variation_id);
|
||||
|
||||
if (!$variation) {
|
||||
if ($request->ajax()) {
|
||||
return response()->json(['success' => false, 'message' => 'Товар не найден'], 404);
|
||||
}
|
||||
return back()->with('error', 'Товар не найден');
|
||||
}
|
||||
|
||||
if ($variation->stock < $request->quantity) {
|
||||
if ($request->ajax()) {
|
||||
return response()->json(['success' => false, 'message' => 'Недостаточно товара на складе'], 422);
|
||||
}
|
||||
return back()->with('error', 'Недостаточно товара на складе');
|
||||
}
|
||||
|
||||
$cartItem = CartItem::findByVariation($request->variation_id);
|
||||
|
||||
if ($cartItem) {
|
||||
$newQuantity = $cartItem->quantity + $request->quantity;
|
||||
if ($variation->stock < $newQuantity) {
|
||||
if ($request->ajax()) {
|
||||
return response()->json(['success' => false, 'message' => 'Недостаточно товара на складе'], 422);
|
||||
}
|
||||
return back()->with('error', 'Недостаточно товара на складе');
|
||||
}
|
||||
$cartItem->update(['quantity' => $newQuantity]);
|
||||
} else {
|
||||
CartItem::create([
|
||||
'user_id' => Auth::id(),
|
||||
'session_id' => session()->getId(),
|
||||
'variation_id' => $request->variation_id,
|
||||
'quantity' => $request->quantity,
|
||||
'price' => $variation->price
|
||||
]);
|
||||
}
|
||||
|
||||
$cartCount = CartItem::getCount();
|
||||
|
||||
if ($request->ajax()) {
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Товар добавлен в корзину',
|
||||
'cart_count' => $cartCount
|
||||
]);
|
||||
}
|
||||
|
||||
return back()->with('success', 'Товар добавлен в корзину');
|
||||
}
|
||||
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$request->validate(['quantity' => 'required|integer|min:1']);
|
||||
|
||||
$cartItem = CartItem::find($id);
|
||||
|
||||
if (!$cartItem) {
|
||||
return response()->json(['error' => 'Товар не найден'], 404);
|
||||
}
|
||||
|
||||
$variation = $cartItem->variation;
|
||||
|
||||
if ($variation->stock < $request->quantity) {
|
||||
return response()->json(['error' => 'Недостаточно товара на складе'], 422);
|
||||
}
|
||||
|
||||
$cartItem->update(['quantity' => $request->quantity]);
|
||||
|
||||
$cartItems = CartItem::getCartQuery()->get();
|
||||
$cartTotal = $cartItems->sum('total');
|
||||
$totalItems = $cartItems->sum('quantity');
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'total' => $cartItem->total,
|
||||
'cart_total' => $cartTotal,
|
||||
'total_items' => $totalItems,
|
||||
'max_stock' => $variation->stock
|
||||
]);
|
||||
}
|
||||
|
||||
public function remove($id)
|
||||
{
|
||||
$cartItem = CartItem::findCartItem($id);
|
||||
|
||||
if ($cartItem) {
|
||||
$cartItem->delete();
|
||||
return redirect()->route('cart.index')->with('success', 'Товар удален из корзины');
|
||||
}
|
||||
|
||||
return redirect()->route('cart.index')->with('error', 'Товар не найден');
|
||||
}
|
||||
|
||||
public function clear()
|
||||
{
|
||||
CartItem::clear();
|
||||
return redirect()->route('cart.index')->with('success', 'Корзина очищена');
|
||||
}
|
||||
|
||||
public function checkout()
|
||||
{
|
||||
$cartItems = CartItem::getCartQuery()->get();
|
||||
|
||||
if ($cartItems->isEmpty()) {
|
||||
return redirect()->route('cart.index')->with('error', 'Корзина пуста');
|
||||
}
|
||||
|
||||
$total = $cartItems->sum('total');
|
||||
|
||||
return view('cart.checkout', compact('cartItems', 'total'));
|
||||
}
|
||||
|
||||
public function processOrder(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'customer_name' => 'required|string|max:255',
|
||||
'customer_email' => 'required|email|max:255',
|
||||
'customer_phone' => 'required|string|max:20',
|
||||
'shipping_address' => 'required_if:delivery_method,courier,express|max:1000',
|
||||
'delivery_method' => 'required|in:courier,pickup,express',
|
||||
'payment_method' => 'required|in:cash,card,online'
|
||||
], [
|
||||
'customer_name.required' => 'Поле обязательно для заполнения',
|
||||
'customer_email.required' => 'Поле обязательно для заполнения',
|
||||
'customer_email.email' => 'Введите корректный адрес электронной почты',
|
||||
'customer_phone.required' => 'Поле обязательно для заполнения',
|
||||
'shipping_address.required_if' => 'Адрес доставки обязателен для выбранного способа доставки',
|
||||
'delivery_method.required' => 'Выберите способ доставки',
|
||||
'payment_method.required' => 'Выберите способ оплаты'
|
||||
]);
|
||||
|
||||
|
||||
$cartItems = CartItem::getCartQuery()->get();
|
||||
|
||||
if ($cartItems->isEmpty()) {
|
||||
return back()->with('error', 'Корзина пуста');
|
||||
}
|
||||
|
||||
$order = Order::createFromCart($request->all(), $cartItems);
|
||||
|
||||
if ($order['success']) {
|
||||
return redirect()->route('orders.show', $order['order'])
|
||||
->with('success', 'Заказ оформлен! Номер заказа: ' . $order['order']->order_number);
|
||||
}
|
||||
|
||||
return back()->with('error', $order['message']);
|
||||
}
|
||||
}
|
||||
67
app/Http/Controllers/CategoryController.php
Normal file
67
app/Http/Controllers/CategoryController.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Brand;
|
||||
use App\Models\Category;
|
||||
use App\Models\Product;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class CategoryController extends Controller
|
||||
{
|
||||
public function showByPath(Request $request, $path)
|
||||
{
|
||||
$category = Category::findByPath($path);
|
||||
|
||||
if (!$category) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$categoryIds = $category->getAllCategoryIds();
|
||||
|
||||
$brands = Brand::whereHas('products', function ($query) use ($categoryIds) {
|
||||
$query->whereIn('category_id', $categoryIds)
|
||||
->active();
|
||||
})
|
||||
->active()
|
||||
->orderBy('name')
|
||||
->get();
|
||||
|
||||
$priceRange = DB::table('products')
|
||||
->join('product_variations', 'products.id', '=', 'product_variations.product_id')
|
||||
->whereIn('products.category_id', $categoryIds)
|
||||
->where('products.is_active', true)
|
||||
->where('product_variations.is_active', true)
|
||||
->selectRaw('MIN(product_variations.price) as min_price, MAX(product_variations.price) as max_price')
|
||||
->first();
|
||||
|
||||
$minPrice = $priceRange->min_price ?? 0;
|
||||
$maxPrice = $priceRange->max_price ?? 10000;
|
||||
|
||||
$productsQuery = $category->productsWithChildren()
|
||||
->with(['variations', 'brand'])
|
||||
->active();
|
||||
|
||||
if ($request->has('brands') && !empty($request->brands)) {
|
||||
$productsQuery->whereIn('brand_id', $request->brands);
|
||||
}
|
||||
|
||||
if ($request->has('price-min') && $request->has('price-max')) {
|
||||
$min = (float) $request->get('price-min');
|
||||
$max = (float) $request->get('price-max');
|
||||
|
||||
$productsQuery->whereHas('variations', function ($q) use ($min, $max) {
|
||||
$q->whereBetween('price', [$min, $max]);
|
||||
});
|
||||
}
|
||||
|
||||
$products = $productsQuery->orderBy('created_at', 'desc')->paginate(20);
|
||||
|
||||
$products->appends($request->all());
|
||||
|
||||
$children = $category->children()->active()->get();
|
||||
|
||||
return view('categories.show', compact('category', 'products', 'children', 'brands', 'minPrice', 'maxPrice'));
|
||||
}
|
||||
}
|
||||
12
app/Http/Controllers/Controller.php
Normal file
12
app/Http/Controllers/Controller.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
use AuthorizesRequests, ValidatesRequests;
|
||||
}
|
||||
53
app/Http/Controllers/HomeController.php
Normal file
53
app/Http/Controllers/HomeController.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
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\Contact;
|
||||
use App\Models\Brand;
|
||||
|
||||
class HomeController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$discountedProducts = ProductVariation::with(['product', 'images'])
|
||||
->discounted()
|
||||
->inStock()
|
||||
->active()
|
||||
->orderByRaw('(old_price - price) / old_price * 100 DESC')
|
||||
->limit(8)
|
||||
->get();
|
||||
|
||||
$categories = Category::active()->root()->orderBy('sort_order')->get();
|
||||
|
||||
$dryCatFood = Product::getForCarousel(21, 12);
|
||||
|
||||
$dryDogFood = Product::getForCarousel(3, 12);
|
||||
|
||||
return view('index', compact('discountedProducts', 'categories', 'dryCatFood', 'dryDogFood'));
|
||||
}
|
||||
|
||||
public function about()
|
||||
{
|
||||
|
||||
$topBrands = Brand::active()->popular()->limit(5)->get();
|
||||
|
||||
return view('about', compact('topBrands'));
|
||||
}
|
||||
|
||||
public function contacts()
|
||||
{
|
||||
return view('contacts');
|
||||
}
|
||||
|
||||
public function privacyPolicy()
|
||||
{
|
||||
return view('privacy-policy');
|
||||
}
|
||||
}
|
||||
90
app/Http/Controllers/MenuController.php
Normal file
90
app/Http/Controllers/MenuController.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\Category;
|
||||
use App\Models\Contact;
|
||||
use App\Models\Brand;
|
||||
use App\Models\Product;
|
||||
|
||||
class MenuController extends Controller
|
||||
{
|
||||
public function getMenuData()
|
||||
{
|
||||
$categories = Category::getTreeMenu();
|
||||
|
||||
$footerCategories = Category::root()
|
||||
->active()
|
||||
->orderBy('sort_order')
|
||||
->get();
|
||||
|
||||
$contacts = Contact::getData();
|
||||
|
||||
$popularBrands = Brand::active()->popular()->limit(8)->get();
|
||||
|
||||
return [
|
||||
'categories' => $categories,
|
||||
'contacts' => $contacts,
|
||||
'popularBrands' => $popularBrands,
|
||||
'footerCategories' => $footerCategories,
|
||||
];
|
||||
}
|
||||
|
||||
public function search(Request $request)
|
||||
{
|
||||
$query = trim($request->get('q', ''));
|
||||
|
||||
// Проверка на минимальную длину
|
||||
if (mb_strlen($query) < 3) {
|
||||
return redirect()->back()->with('error', 'Для поиска введите минимум 3 символа');
|
||||
}
|
||||
|
||||
// Поиск товаров
|
||||
$products = Product::with(['variations', 'brand', 'category'])
|
||||
->where('name', 'like', "%{$query}%")
|
||||
->orWhere('description', 'like', "%{$query}%")
|
||||
->orWhere('meta_keywords', 'like', "%{$query}%")
|
||||
->active()
|
||||
->paginate(20);
|
||||
|
||||
// Поиск брендов
|
||||
$brands = Brand::where('name', 'like', "%{$query}%")
|
||||
->orWhere('description', 'like', "%{$query}%")
|
||||
->active()
|
||||
->limit(10)
|
||||
->get();
|
||||
|
||||
return view('search.results', compact('products', 'brands', 'query'));
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX поиск для подсказок
|
||||
*/
|
||||
public function searchAjax(Request $request)
|
||||
{
|
||||
$query = trim($request->get('q', ''));
|
||||
|
||||
if (mb_strlen($query) < 2) {
|
||||
return response()->json([]);
|
||||
}
|
||||
|
||||
// Поиск товаров
|
||||
$products = Product::with('variations')
|
||||
->where('name', 'like', "%{$query}%")
|
||||
->active()
|
||||
->limit(5)
|
||||
->get(['id', 'name', 'slug']);
|
||||
|
||||
// Поиск брендов
|
||||
$brands = Brand::where('name', 'like', "%{$query}%")
|
||||
->active()
|
||||
->limit(3)
|
||||
->get(['id', 'name', 'slug']);
|
||||
|
||||
return response()->json([
|
||||
'products' => $products,
|
||||
'brands' => $brands
|
||||
]);
|
||||
}
|
||||
}
|
||||
35
app/Http/Controllers/OrderController.php
Normal file
35
app/Http/Controllers/OrderController.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Order;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class OrderController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display user orders.
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$orders = Order::where('user_id', Auth::id())
|
||||
->orderBy('created_at', 'desc')
|
||||
->paginate(20);
|
||||
|
||||
return view('orders.orders', compact('orders'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Display order details.
|
||||
*/
|
||||
public function show(Order $order)
|
||||
{
|
||||
$user = Auth::user();
|
||||
if ($order->user_id !== Auth::id()) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
return view('profile.order-show', compact('order', 'user'));
|
||||
}
|
||||
}
|
||||
39
app/Http/Controllers/ProductsController.php
Normal file
39
app/Http/Controllers/ProductsController.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Product;
|
||||
use App\Models\ProductVariation;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class ProductsController extends Controller
|
||||
{
|
||||
public function show($slug)
|
||||
{
|
||||
$product = Product::with([
|
||||
'category',
|
||||
'category.parent',
|
||||
'brand',
|
||||
'variations',
|
||||
'variations.images',
|
||||
'attributes'
|
||||
])
|
||||
->where('slug', $slug)
|
||||
->where('is_active', true)
|
||||
->firstOrFail();
|
||||
|
||||
$defaultVariation = $product->default_variation;
|
||||
|
||||
return view('products.show', compact('product', 'defaultVariation'));
|
||||
}
|
||||
|
||||
public function getVariationImages($variationId)
|
||||
{
|
||||
$images = ProductVariation::getImagesDataById($variationId);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'images' => $images
|
||||
]);
|
||||
}
|
||||
}
|
||||
97
app/Http/Controllers/ProfileController.php
Normal file
97
app/Http/Controllers/ProfileController.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Order;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
/**
|
||||
* Личный кабинет - главная
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$user = Auth::user();
|
||||
$activeOrders = Order::where('user_id', $user->id)
|
||||
->whereNotIn('delivery_status', ['delivered', 'cancelled'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->get();
|
||||
|
||||
$archiveOrders = Order::where('user_id', $user->id)
|
||||
->whereIn('delivery_status', ['delivered', 'cancelled'])
|
||||
->orderBy('created_at', 'desc')
|
||||
->get();
|
||||
|
||||
return view('profile.profile', compact('user', 'activeOrders', 'archiveOrders'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Редактирование профиля
|
||||
*/
|
||||
public function edit()
|
||||
{
|
||||
$user = Auth::user();
|
||||
return view('profile.edit', compact('user'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновление профиля
|
||||
*/
|
||||
public function update(Request $request)
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
'email' => [
|
||||
'required',
|
||||
'email',
|
||||
'max:255',
|
||||
Rule::unique('users')->ignore($user->id),
|
||||
],
|
||||
'phone' => 'nullable|string|max:20',
|
||||
'current_password' => 'nullable|required_with:password|current_password',
|
||||
'password' => 'nullable|string|min:8|confirmed',
|
||||
], [
|
||||
'name.required' => 'Обязательно для заполнения',
|
||||
'email.required' => 'Обязательно для заполнения',
|
||||
'email.email' => 'Введите корректный email',
|
||||
'email.unique' => 'Этот email уже занят',
|
||||
'current_password.required_with' => 'Введите текущий пароль',
|
||||
'current_password.current_password' => 'Неверный текущий пароль',
|
||||
'password.min' => 'Пароль должен содержать минимум 8 символов',
|
||||
'password.confirmed' => 'Пароли не совпадают',
|
||||
]);
|
||||
|
||||
$user->name = $request->name;
|
||||
$user->email = $request->email;
|
||||
$user->phone = $request->phone;
|
||||
|
||||
if ($request->filled('password')) {
|
||||
$user->password = Hash::make($request->password);
|
||||
}
|
||||
|
||||
$user->save();
|
||||
|
||||
return redirect()->route('profile.index')
|
||||
->with('success', 'Профиль успешно обновлен');
|
||||
}
|
||||
|
||||
/**
|
||||
* Детали заказа
|
||||
*/
|
||||
public function orderShow($id)
|
||||
{
|
||||
$order = Order::where('user_id', Auth::id())
|
||||
->with('items.variation.product')
|
||||
->findOrFail($id);
|
||||
$user = Auth::user();
|
||||
|
||||
return view('profile.order-show', compact('order', 'user'));
|
||||
}
|
||||
}
|
||||
69
app/Http/Kernel.php
Normal file
69
app/Http/Kernel.php
Normal file
@@ -0,0 +1,69 @@
|
||||
<?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,
|
||||
\App\Http\Middleware\TrustProxies::class,
|
||||
\Illuminate\Http\Middleware\HandleCors::class,
|
||||
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
|
||||
\App\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' => \App\Http\Middleware\ValidateSignature::class,
|
||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||
'permission' => \App\Http\Middleware\CheckPermission::class,
|
||||
];
|
||||
}
|
||||
17
app/Http/Middleware/Authenticate.php
Normal file
17
app/Http/Middleware/Authenticate.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class Authenticate extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the path the user should be redirected to when they are not authenticated.
|
||||
*/
|
||||
protected function redirectTo(Request $request): ?string
|
||||
{
|
||||
return $request->expectsJson() ? null : route('login');
|
||||
}
|
||||
}
|
||||
32
app/Http/Middleware/CheckPermission.php
Normal file
32
app/Http/Middleware/CheckPermission.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class CheckPermission
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, string $permission): Response
|
||||
{
|
||||
if (!Auth::check()) {
|
||||
abort(403, 'Для доступа необходимо авторизоваться');
|
||||
}
|
||||
|
||||
/** @var \App\Models\User $user */
|
||||
$user = Auth::user();
|
||||
|
||||
if (!$user->hasPermission($permission)) {
|
||||
abort(403, 'У вас нет прав для доступа к этой странице');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
20
app/Http/Middleware/CheckRole.php
Normal file
20
app/Http/Middleware/CheckRole.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class CheckRole
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
17
app/Http/Middleware/EncryptCookies.php
Normal file
17
app/Http/Middleware/EncryptCookies.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
|
||||
|
||||
class EncryptCookies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the cookies that should not be encrypted.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
17
app/Http/Middleware/PreventRequestsDuringMaintenance.php
Normal file
17
app/Http/Middleware/PreventRequestsDuringMaintenance.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
|
||||
|
||||
class PreventRequestsDuringMaintenance extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be reachable while maintenance mode is enabled.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
30
app/Http/Middleware/RedirectIfAuthenticated.php
Normal file
30
app/Http/Middleware/RedirectIfAuthenticated.php
Normal file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class RedirectIfAuthenticated
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, string ...$guards): Response
|
||||
{
|
||||
$guards = empty($guards) ? [null] : $guards;
|
||||
|
||||
foreach ($guards as $guard) {
|
||||
if (Auth::guard($guard)->check()) {
|
||||
return redirect(RouteServiceProvider::HOME);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
19
app/Http/Middleware/TrimStrings.php
Normal file
19
app/Http/Middleware/TrimStrings.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
|
||||
|
||||
class TrimStrings extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the attributes that should not be trimmed.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
}
|
||||
20
app/Http/Middleware/TrustHosts.php
Normal file
20
app/Http/Middleware/TrustHosts.php
Normal file
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustHosts as Middleware;
|
||||
|
||||
class TrustHosts extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the host patterns that should be trusted.
|
||||
*
|
||||
* @return array<int, string|null>
|
||||
*/
|
||||
public function hosts(): array
|
||||
{
|
||||
return [
|
||||
$this->allSubdomainsOfApplicationUrl(),
|
||||
];
|
||||
}
|
||||
}
|
||||
28
app/Http/Middleware/TrustProxies.php
Normal file
28
app/Http/Middleware/TrustProxies.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustProxies as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TrustProxies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The trusted proxies for this application.
|
||||
*
|
||||
* @var array<int, string>|string|null
|
||||
*/
|
||||
protected $proxies;
|
||||
|
||||
/**
|
||||
* The headers that should be used to detect proxies.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $headers =
|
||||
Request::HEADER_X_FORWARDED_FOR |
|
||||
Request::HEADER_X_FORWARDED_HOST |
|
||||
Request::HEADER_X_FORWARDED_PORT |
|
||||
Request::HEADER_X_FORWARDED_PROTO |
|
||||
Request::HEADER_X_FORWARDED_AWS_ELB;
|
||||
}
|
||||
22
app/Http/Middleware/ValidateSignature.php
Normal file
22
app/Http/Middleware/ValidateSignature.php
Normal file
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
|
||||
|
||||
class ValidateSignature extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the query string parameters that should be ignored.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
// 'fbclid',
|
||||
// 'utm_campaign',
|
||||
// 'utm_content',
|
||||
// 'utm_medium',
|
||||
// 'utm_source',
|
||||
// 'utm_term',
|
||||
];
|
||||
}
|
||||
17
app/Http/Middleware/VerifyCsrfToken.php
Normal file
17
app/Http/Middleware/VerifyCsrfToken.php
Normal file
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
|
||||
|
||||
class VerifyCsrfToken extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be excluded from CSRF verification.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
62
app/Models/Brand.php
Normal file
62
app/Models/Brand.php
Normal file
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Brand extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'slug',
|
||||
'description',
|
||||
'logo',
|
||||
'website',
|
||||
'country',
|
||||
'is_active',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
|
||||
public function products(): HasMany
|
||||
{
|
||||
return $this->hasMany(Product::class);
|
||||
}
|
||||
|
||||
public function activeProducts(): HasMany
|
||||
{
|
||||
return $this->hasMany(Product::class)->where('is_active', true);
|
||||
}
|
||||
|
||||
public function getProductsCountAttribute(): int
|
||||
{
|
||||
return $this->activeProducts()->count();
|
||||
}
|
||||
|
||||
public function scopeActive($query)
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
}
|
||||
|
||||
public function scopePopular($query)
|
||||
{
|
||||
return $query->withCount('products')->orderBy('products_count', 'desc');
|
||||
}
|
||||
|
||||
public function getLogoUrlAttribute(): string
|
||||
{
|
||||
if ($this->logo) {
|
||||
$logoPath = 'assets/images/brands/' . $this->logo;
|
||||
if (file_exists(public_path($logoPath))) {
|
||||
return asset($logoPath);
|
||||
}
|
||||
}
|
||||
|
||||
return asset('assets/images/brands/default.svg');
|
||||
}
|
||||
}
|
||||
97
app/Models/CartItem.php
Normal file
97
app/Models/CartItem.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class CartItem extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'session_id',
|
||||
'variation_id',
|
||||
'quantity',
|
||||
'price'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'quantity' => 'integer',
|
||||
'price' => 'decimal:2'
|
||||
];
|
||||
|
||||
public function variation(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductVariation::class);
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function getTotalAttribute(): float
|
||||
{
|
||||
return $this->quantity * $this->price;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить корзину для текущего пользователя/сессии
|
||||
*/
|
||||
public static function getCartQuery()
|
||||
{
|
||||
return self::with('variation.product')
|
||||
->where(function ($query) {
|
||||
if (Auth::check()) {
|
||||
$query->where('user_id', Auth::id());
|
||||
} else {
|
||||
$query->where('session_id', session()->getId());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить количество товаров в корзине
|
||||
*/
|
||||
public static function getCount()
|
||||
{
|
||||
return self::getCartQuery()->sum('quantity');
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить общую сумму корзины
|
||||
*/
|
||||
public static function getTotal()
|
||||
{
|
||||
return self::getCartQuery()->get()->sum('total');
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить товар в корзине по вариации
|
||||
*/
|
||||
public static function findByVariation($variationId)
|
||||
{
|
||||
return self::getCartQuery()
|
||||
->where('variation_id', $variationId)
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить товар в корзине по ID
|
||||
*/
|
||||
public static function findCartItem($id)
|
||||
{
|
||||
return self::getCartQuery()
|
||||
->where('id', $id)
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Очистить корзину
|
||||
*/
|
||||
public static function clear()
|
||||
{
|
||||
return self::getCartQuery()->delete();
|
||||
}
|
||||
}
|
||||
243
app/Models/Category.php
Normal file
243
app/Models/Category.php
Normal file
@@ -0,0 +1,243 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class Category extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'slug',
|
||||
'description',
|
||||
'icon',
|
||||
'image',
|
||||
'parent_id',
|
||||
'sort_order',
|
||||
'is_active'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
|
||||
public function parent(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Category::class, 'parent_id');
|
||||
}
|
||||
|
||||
public function children(): HasMany
|
||||
{
|
||||
return $this->hasMany(Category::class, 'parent_id')->orderBy('sort_order');
|
||||
}
|
||||
|
||||
public function descendants()
|
||||
{
|
||||
return $this->children()->with('descendants');
|
||||
}
|
||||
|
||||
public function products(): HasMany
|
||||
{
|
||||
return $this->hasMany(Product::class, 'category_id');
|
||||
}
|
||||
|
||||
public function getFullSlugAttribute(): string
|
||||
{
|
||||
$slugs = [];
|
||||
$current = $this;
|
||||
|
||||
while ($current) {
|
||||
$slugs[] = $current->slug;
|
||||
$current = $current->parent;
|
||||
}
|
||||
|
||||
return implode('/', array_reverse($slugs));
|
||||
}
|
||||
|
||||
public function getUrlAttribute(): string
|
||||
{
|
||||
return route('category.show', $this->full_slug);
|
||||
}
|
||||
|
||||
public function getBreadcrumbsAttribute()
|
||||
{
|
||||
$breadcrumbs = [];
|
||||
$current = $this;
|
||||
|
||||
while ($current) {
|
||||
array_unshift($breadcrumbs, [
|
||||
'name' => $current->name,
|
||||
'slug' => $current->slug,
|
||||
'url' => $current->url
|
||||
]);
|
||||
$current = $current->parent;
|
||||
}
|
||||
|
||||
return $breadcrumbs;
|
||||
}
|
||||
|
||||
public function getPathAttribute()
|
||||
{
|
||||
$path = [];
|
||||
$current = $this;
|
||||
|
||||
while ($current) {
|
||||
array_unshift($path, $current->slug);
|
||||
$current = $current->parent;
|
||||
}
|
||||
|
||||
return implode('/', $path);
|
||||
}
|
||||
|
||||
public function scopeActive($query)
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
}
|
||||
|
||||
public function scopeRoot($query)
|
||||
{
|
||||
return $query->whereNull('parent_id');
|
||||
}
|
||||
|
||||
public static function getTreeMenu()
|
||||
{
|
||||
return self::with('descendants')->root()->active()->orderBy('sort_order')->get();
|
||||
}
|
||||
|
||||
public static function findByPath($path)
|
||||
{
|
||||
$slugs = explode('/', trim($path, '/'));
|
||||
$category = null;
|
||||
|
||||
foreach ($slugs as $slug) {
|
||||
if (!$category) {
|
||||
$category = self::where('slug', $slug)
|
||||
->whereNull('parent_id')
|
||||
->active()
|
||||
->first();
|
||||
} else {
|
||||
$category = $category->children()
|
||||
->where('slug', $slug)
|
||||
->active()
|
||||
->first();
|
||||
}
|
||||
|
||||
if (!$category) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return $category;
|
||||
}
|
||||
|
||||
public static function getSelectTree($maxLevel = 1)
|
||||
{
|
||||
$categories = self::with('parent')->get();
|
||||
|
||||
return $categories->map(function ($cat) {
|
||||
$cat->level = $cat->calculateLevel();
|
||||
return $cat;
|
||||
})->filter(function ($cat) use ($maxLevel) {
|
||||
return $cat->level < $maxLevel;
|
||||
});
|
||||
}
|
||||
|
||||
public static function getFlatTree()
|
||||
{
|
||||
$categories = self::with('parent')
|
||||
->orderBy('parent_id')
|
||||
->orderBy('sort_order')
|
||||
->get();
|
||||
|
||||
return self::buildFlatTree($categories);
|
||||
}
|
||||
|
||||
private static function buildFlatTree($categories, $parentId = null, $level = 0)
|
||||
{
|
||||
$result = collect();
|
||||
|
||||
foreach ($categories as $category) {
|
||||
if ($category->parent_id == $parentId) {
|
||||
$category->level = $level;
|
||||
$result->push($category);
|
||||
|
||||
$children = self::buildFlatTree($categories, $category->id, $level + 1);
|
||||
$result = $result->concat($children);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function getLevelAttribute()
|
||||
{
|
||||
return $this->calculateLevel();
|
||||
}
|
||||
|
||||
public function calculateLevel($level = 0)
|
||||
{
|
||||
if ($this->parent) {
|
||||
return $this->parent->calculateLevel($level + 1);
|
||||
}
|
||||
return $level;
|
||||
}
|
||||
|
||||
public function isDescendantOf($ancestorId): bool
|
||||
{
|
||||
$current = $this;
|
||||
while ($current) {
|
||||
if ($current->id == $ancestorId) {
|
||||
return true;
|
||||
}
|
||||
$current = $current->parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function getIconUrlAttribute(): string
|
||||
{
|
||||
if ($this->icon !== NULL) {
|
||||
$iconPath = 'assets/images/categories/icons/' . $this->icon;
|
||||
if (file_exists(public_path($iconPath))) {
|
||||
return asset($iconPath);
|
||||
}
|
||||
}
|
||||
|
||||
return asset('assets/images/categories/icons/default.svg');
|
||||
}
|
||||
|
||||
public function getImageUrlAttribute(): string
|
||||
{
|
||||
if ($this->image !== NULL) {
|
||||
$imagePath = 'assets/images/categories/images/' . $this->image;
|
||||
if (file_exists(public_path($imagePath))) {
|
||||
return asset($imagePath);
|
||||
}
|
||||
}
|
||||
|
||||
return asset('assets/images/categories/images/default.svg');
|
||||
}
|
||||
|
||||
public function getAllCategoryIds(): array
|
||||
{
|
||||
$ids = [$this->id];
|
||||
|
||||
foreach ($this->children as $child) {
|
||||
$ids = array_merge($ids, $child->getAllCategoryIds());
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
// В модели Category
|
||||
public function productsWithChildren()
|
||||
{
|
||||
$categoryIds = $this->getAllCategoryIds();
|
||||
|
||||
return Product::whereIn('category_id', $categoryIds);
|
||||
}
|
||||
}
|
||||
31
app/Models/Contact.php
Normal file
31
app/Models/Contact.php
Normal file
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Contact extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'description',
|
||||
'logo',
|
||||
'favicon',
|
||||
'phone',
|
||||
'email',
|
||||
'address',
|
||||
'work_hours',
|
||||
'telegram',
|
||||
'whatsapp',
|
||||
'vkontakte',
|
||||
'meta_title',
|
||||
'meta_description',
|
||||
'meta_keywords',
|
||||
];
|
||||
|
||||
public static function getData()
|
||||
{
|
||||
return self::first() ?? self::create();
|
||||
}
|
||||
}
|
||||
203
app/Models/Order.php
Normal file
203
app/Models/Order.php
Normal file
@@ -0,0 +1,203 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class Order extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'order_number',
|
||||
'user_id',
|
||||
'customer_name',
|
||||
'customer_email',
|
||||
'customer_phone',
|
||||
'shipping_address',
|
||||
'subtotal',
|
||||
'shipping_cost',
|
||||
'discount',
|
||||
'total',
|
||||
'payment_method',
|
||||
'payment_status',
|
||||
'delivery_method',
|
||||
'delivery_status',
|
||||
'comment'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'subtotal' => 'decimal:2',
|
||||
'shipping_cost' => 'decimal:2',
|
||||
'discount' => 'decimal:2',
|
||||
'total' => 'decimal:2'
|
||||
];
|
||||
|
||||
const DELIVERY_STATUSES = [
|
||||
'pending' => 'Ожидает обработки',
|
||||
'processing' => 'В обработке',
|
||||
'shipped' => 'Отправлен',
|
||||
'delivered' => 'Доставлен',
|
||||
'cancelled' => 'Отменён'
|
||||
];
|
||||
|
||||
const PAYMENT_STATUSES = [
|
||||
'pending' => 'Ожидает оплаты',
|
||||
'paid' => 'Оплачен',
|
||||
'failed' => 'Ошибка оплаты'
|
||||
];
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function items(): HasMany
|
||||
{
|
||||
return $this->hasMany(OrderItem::class);
|
||||
}
|
||||
|
||||
public static function generateOrderNumber(): string
|
||||
{
|
||||
return 'ORD-' . date('Ymd') . '-' . strtoupper(uniqid());
|
||||
}
|
||||
|
||||
/**
|
||||
* Создать заказ из корзины
|
||||
*/
|
||||
public static function createFromCart($data, $cartItems)
|
||||
{
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
$subtotal = $cartItems->sum('total');
|
||||
$shippingCost = self::calculateShipping($data['delivery_method']);
|
||||
$total = $subtotal + $shippingCost;
|
||||
|
||||
$shippingAddress = null;
|
||||
if (in_array($data['delivery_method'], ['courier', 'express'])) {
|
||||
$shippingAddress = $data['shipping_address'];
|
||||
}
|
||||
|
||||
$order = self::create([
|
||||
'order_number' => self::generateOrderNumber(),
|
||||
'user_id' => auth()->id(),
|
||||
'customer_name' => $data['customer_name'],
|
||||
'customer_email' => $data['customer_email'],
|
||||
'customer_phone' => $data['customer_phone'],
|
||||
'shipping_address' => $shippingAddress,
|
||||
'subtotal' => $subtotal,
|
||||
'shipping_cost' => $shippingCost,
|
||||
'total' => $total,
|
||||
'payment_method' => $data['payment_method'],
|
||||
'delivery_method' => $data['delivery_method'],
|
||||
'comment' => $data['comment'] ?? null
|
||||
]);
|
||||
|
||||
foreach ($cartItems as $item) {
|
||||
OrderItem::create([
|
||||
'order_id' => $order->id,
|
||||
'variation_id' => $item->variation_id,
|
||||
'product_name' => $item->variation->product->name,
|
||||
'variation_name' => $item->variation->name,
|
||||
'sku' => $item->variation->sku,
|
||||
'quantity' => $item->quantity,
|
||||
'price' => $item->price,
|
||||
'total' => $item->total
|
||||
]);
|
||||
|
||||
$item->variation->decrement('stock', $item->quantity);
|
||||
}
|
||||
|
||||
CartItem::clear();
|
||||
|
||||
DB::commit();
|
||||
|
||||
return ['success' => true, 'order' => $order];
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
return ['success' => false, 'message' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Рассчитать стоимость доставки
|
||||
*/
|
||||
private static function calculateShipping($method)
|
||||
{
|
||||
return match ($method) {
|
||||
'express' => 300,
|
||||
'courier' => 0,
|
||||
'pickup' => 0,
|
||||
default => 0,
|
||||
};
|
||||
}
|
||||
|
||||
public function getDeliveryStatusNameAttribute(): string
|
||||
{
|
||||
return self::DELIVERY_STATUSES[$this->delivery_status] ?? $this->delivery_status;
|
||||
}
|
||||
|
||||
public function getPaymentStatusNameAttribute(): string
|
||||
{
|
||||
return self::PAYMENT_STATUSES[$this->payment_status] ?? $this->payment_status;
|
||||
}
|
||||
|
||||
public function getDeliveryStatusColorAttribute(): string
|
||||
{
|
||||
return match ($this->delivery_status) {
|
||||
'pending' => 'warning',
|
||||
'processing' => 'info',
|
||||
'shipped' => 'primary',
|
||||
'delivered' => 'success',
|
||||
'cancelled' => 'danger',
|
||||
default => 'secondary'
|
||||
};
|
||||
}
|
||||
|
||||
public function getDeliveryStatusIconAttribute(): string
|
||||
{
|
||||
return match ($this->delivery_status) {
|
||||
'pending' => 'bi-clock',
|
||||
'processing' => 'bi-arrow-repeat',
|
||||
'shipped' => 'bi-truck',
|
||||
'delivered' => 'bi-check-circle',
|
||||
'cancelled' => 'bi-x-circle',
|
||||
default => 'bi-question-circle'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить все возможные статусы доставки для выпадающего списка
|
||||
*/
|
||||
public static function getDeliveryStatuses(): array
|
||||
{
|
||||
return self::DELIVERY_STATUSES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить все возможные статусы оплаты для выпадающего списка
|
||||
*/
|
||||
public static function getPaymentStatuses(): array
|
||||
{
|
||||
return self::PAYMENT_STATUSES;
|
||||
}
|
||||
|
||||
public static function getRevenue($startDate, $endDate, $paidOnly = true)
|
||||
{
|
||||
$query = self::query();
|
||||
|
||||
if ($paidOnly) {
|
||||
$query->where('payment_status', 'paid');
|
||||
}
|
||||
|
||||
return $query->whereBetween('created_at', [$startDate, $endDate])
|
||||
->sum('total');
|
||||
}
|
||||
|
||||
public static function getMonthlyRevenue()
|
||||
{
|
||||
return self::getRevenue(now()->startOfMonth(), now()->endOfMonth());
|
||||
}
|
||||
}
|
||||
65
app/Models/OrderItem.php
Normal file
65
app/Models/OrderItem.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class OrderItem extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'order_id',
|
||||
'variation_id',
|
||||
'product_name',
|
||||
'variation_name',
|
||||
'sku',
|
||||
'quantity',
|
||||
'price',
|
||||
'total'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'quantity' => 'integer',
|
||||
'price' => 'decimal:2',
|
||||
'total' => 'decimal:2'
|
||||
];
|
||||
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
|
||||
public function variation(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductVariation::class);
|
||||
}
|
||||
|
||||
public static function createFromCartItem($orderId, $cartItem)
|
||||
{
|
||||
return self::create([
|
||||
'order_id' => $orderId,
|
||||
'variation_id' => $cartItem->variation_id,
|
||||
'product_name' => $cartItem->variation->product->name,
|
||||
'variation_name' => $cartItem->variation->name,
|
||||
'sku' => $cartItem->variation->sku,
|
||||
'quantity' => $cartItem->quantity,
|
||||
'price' => $cartItem->price,
|
||||
'total' => $cartItem->total
|
||||
]);
|
||||
}
|
||||
|
||||
public function scopePopular($query, $limit = 5)
|
||||
{
|
||||
return $query->select(
|
||||
'product_name',
|
||||
'variation_name',
|
||||
'variation_id',
|
||||
DB::raw('SUM(quantity) as total_quantity'),
|
||||
DB::raw('SUM(total) as total_revenue')
|
||||
)
|
||||
->groupBy('product_name', 'variation_name', 'variation_id')
|
||||
->orderBy('total_quantity', 'desc')
|
||||
->limit($limit);
|
||||
}
|
||||
}
|
||||
28
app/Models/Permission.php
Normal file
28
app/Models/Permission.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class Permission extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'slug',
|
||||
'group',
|
||||
'description',
|
||||
];
|
||||
|
||||
public function roles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Role::class)->withTimestamps();
|
||||
}
|
||||
|
||||
public function scopeInGroup($query, string $group)
|
||||
{
|
||||
$query->where('group', $group);
|
||||
}
|
||||
}
|
||||
183
app/Models/Product.php
Normal file
183
app/Models/Product.php
Normal file
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class Product extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'slug',
|
||||
'description',
|
||||
'brand_id',
|
||||
'category_id',
|
||||
'is_active',
|
||||
'meta_title',
|
||||
'meta_description',
|
||||
'meta_keywords',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
|
||||
public function brand(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Brand::class);
|
||||
}
|
||||
|
||||
public function category(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Category::class);
|
||||
}
|
||||
|
||||
public function variations(): HasMany
|
||||
{
|
||||
return $this->hasMany(ProductVariation::class);
|
||||
}
|
||||
|
||||
public function attributes(): HasMany
|
||||
{
|
||||
return $this->hasMany(ProductAttribute::class);
|
||||
}
|
||||
|
||||
public function getDefaultVariationAttribute()
|
||||
{
|
||||
$defaultInStock = $this->variations->firstWhere(function ($variation) {
|
||||
return $variation->is_default && $variation->stock > 0;
|
||||
});
|
||||
|
||||
if ($defaultInStock) {
|
||||
return $defaultInStock;
|
||||
}
|
||||
|
||||
$anyInStock = $this->variations->firstWhere('stock', '>', 0);
|
||||
|
||||
if ($anyInStock) {
|
||||
return $anyInStock;
|
||||
}
|
||||
|
||||
return $this->variations->firstWhere('is_default', true) ?? $this->variations->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить URL главного изображения товара (из дефолтной вариации)
|
||||
*/
|
||||
public function getMainImageAttribute(): string
|
||||
{
|
||||
$defaultVariation = $this->default_variation;
|
||||
|
||||
if ($defaultVariation) {
|
||||
return $defaultVariation->main_image_url;
|
||||
}
|
||||
|
||||
return asset('assets/images/products/default.svg');
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить изображения дефолтной вариации
|
||||
*/
|
||||
public function getDefaultVariationImages()
|
||||
{
|
||||
$defaultVariation = $this->default_variation;
|
||||
|
||||
if ($defaultVariation) {
|
||||
return $defaultVariation->images;
|
||||
}
|
||||
|
||||
return collect();
|
||||
}
|
||||
|
||||
public static function getForCarousel($categoryId = null, $limit = 9, $itemsPerSlide = 3)
|
||||
{
|
||||
$query = self::with(['category', 'brand', 'variations'])
|
||||
->active();
|
||||
|
||||
if ($categoryId) {
|
||||
$query->byCategory($categoryId);
|
||||
}
|
||||
|
||||
$products = $query->limit($limit)->get();
|
||||
|
||||
$products = $products->filter(function ($product) {
|
||||
return $product->variations->isNotEmpty();
|
||||
});
|
||||
|
||||
$products = $products->sortByDesc(function ($product) {
|
||||
$defaultVariation = $product->default_variation;
|
||||
if ($defaultVariation && $defaultVariation->stock > 0) {
|
||||
return 3;
|
||||
} elseif ($defaultVariation) {
|
||||
return 2;
|
||||
} elseif ($product->variations->firstWhere('stock', '>', 0)) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
|
||||
return $products->chunk($itemsPerSlide);
|
||||
}
|
||||
|
||||
public function getRatingAttribute(): array
|
||||
{
|
||||
return [
|
||||
'score' => 4.9,
|
||||
'count' => 1000
|
||||
];
|
||||
}
|
||||
|
||||
public function getMinPriceAttribute(): float
|
||||
{
|
||||
return $this->variations->min('price') ?? 0;
|
||||
}
|
||||
|
||||
public function getMaxPriceAttribute(): float
|
||||
{
|
||||
return $this->variations->max('price') ?? 0;
|
||||
}
|
||||
|
||||
public function getPriceRangeAttribute(): string
|
||||
{
|
||||
$min = $this->min_price;
|
||||
$max = $this->max_price;
|
||||
|
||||
if ($min == $max) {
|
||||
return number_format($min, 0, '.', ' ') . ' ₽';
|
||||
}
|
||||
|
||||
return 'от ' . number_format($min, 0, '.', ' ') . ' ₽ до ' . number_format($max, 0, '.', ' ') . ' ₽';
|
||||
}
|
||||
|
||||
public function getTotalStockAttribute(): int
|
||||
{
|
||||
return $this->variations->sum('stock');
|
||||
}
|
||||
|
||||
public function getHasStockAttribute(): bool
|
||||
{
|
||||
return $this->total_stock > 0;
|
||||
}
|
||||
|
||||
public function getFullNameAttribute(): string
|
||||
{
|
||||
return $this->brand ? "[{$this->brand->name}] {$this->name}" : $this->name;
|
||||
}
|
||||
|
||||
public function scopeActive($query)
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
}
|
||||
|
||||
public function scopeByBrand($query, $brandId)
|
||||
{
|
||||
return $query->where('brand_id', $brandId);
|
||||
}
|
||||
|
||||
public function scopeByCategory($query, $categoryId)
|
||||
{
|
||||
return $query->where('category_id', $categoryId);
|
||||
}
|
||||
}
|
||||
16
app/Models/ProductAttribute.php
Normal file
16
app/Models/ProductAttribute.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class ProductAttribute extends Model
|
||||
{
|
||||
protected $fillable = ['product_id', 'key', 'value'];
|
||||
|
||||
public function product(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
}
|
||||
160
app/Models/ProductVariation.php
Normal file
160
app/Models/ProductVariation.php
Normal file
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class ProductVariation extends Model
|
||||
{
|
||||
protected $table = 'product_variations';
|
||||
|
||||
protected $fillable = [
|
||||
'product_id',
|
||||
'sku',
|
||||
'name',
|
||||
'price',
|
||||
'old_price',
|
||||
'stock',
|
||||
'is_default',
|
||||
'is_active',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_default' => 'boolean',
|
||||
'is_active' => 'boolean',
|
||||
'price' => 'float',
|
||||
'old_price' => 'float',
|
||||
];
|
||||
|
||||
public function product(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
|
||||
public function attributes(): HasMany
|
||||
{
|
||||
return $this->hasMany(VariationAttribute::class, 'variation_id');
|
||||
}
|
||||
|
||||
public function images(): HasMany
|
||||
{
|
||||
return $this->hasMany(VariationImage::class, 'variation_id')
|
||||
->ordered();
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить URL главного изображения вариации
|
||||
*/
|
||||
public function getMainImageUrlAttribute(): string
|
||||
{
|
||||
$image = $this->images()->first();
|
||||
|
||||
if ($image) {
|
||||
return $image->url;
|
||||
}
|
||||
|
||||
return asset('assets/images/products/default.svg');
|
||||
}
|
||||
|
||||
/**
|
||||
* Получить все изображения вариации
|
||||
*/
|
||||
public function getAllImages()
|
||||
{
|
||||
return $this->images;
|
||||
}
|
||||
|
||||
public function getHasDiscountAttribute(): bool
|
||||
{
|
||||
return $this->old_price && $this->old_price > $this->price;
|
||||
}
|
||||
|
||||
public function getDiscountPercentAttribute(): int
|
||||
{
|
||||
if (!$this->has_discount) return 0;
|
||||
return round(($this->old_price - $this->price) / $this->old_price * 100);
|
||||
}
|
||||
|
||||
public function getInStockAttribute(): bool
|
||||
{
|
||||
return $this->stock > 0;
|
||||
}
|
||||
|
||||
public function getFormattedPriceAttribute(): string
|
||||
{
|
||||
return number_format($this->price, 0, '.', ' ') . ' ₽';
|
||||
}
|
||||
|
||||
public function getFormattedOldPriceAttribute(): string
|
||||
{
|
||||
if (!$this->old_price) return '';
|
||||
return number_format($this->old_price, 0, '.', ' ') . ' ₽';
|
||||
}
|
||||
|
||||
public static function isSkuUnique($sku, $excludeId = null, $productId = null)
|
||||
{
|
||||
$query = self::where('sku', $sku);
|
||||
|
||||
if ($excludeId) {
|
||||
$query->where('id', '!=', $excludeId);
|
||||
}
|
||||
|
||||
if ($productId) {
|
||||
$query->where('product_id', $productId);
|
||||
}
|
||||
|
||||
return !$query->exists();
|
||||
}
|
||||
|
||||
public function scopeActive($query)
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
}
|
||||
|
||||
public function scopeInStock($query)
|
||||
{
|
||||
return $query->where('stock', '>', 0);
|
||||
}
|
||||
|
||||
public function scopeDiscounted($query)
|
||||
{
|
||||
return $query->whereNotNull('old_price')
|
||||
->whereColumn('old_price', '>', 'price');
|
||||
}
|
||||
|
||||
public function scopeDefault($query)
|
||||
{
|
||||
return $query->where('is_default', true);
|
||||
}
|
||||
|
||||
// ========== МЕТОДЫ ДЛЯ AJAX ==========
|
||||
|
||||
public static function getImagesByVariationId($variationId)
|
||||
{
|
||||
$variation = self::with(['images' => function ($query) {
|
||||
$query->active()->ordered();
|
||||
}])->find($variationId);
|
||||
|
||||
if (!$variation) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
return $variation->images;
|
||||
}
|
||||
|
||||
public static function getImagesDataById($variationId)
|
||||
{
|
||||
$images = self::getImagesByVariationId($variationId);
|
||||
|
||||
return $images->map(function ($image) {
|
||||
return [
|
||||
'id' => $image->id,
|
||||
'url' => $image->url,
|
||||
'sort_order' => $image->sort_order,
|
||||
'variation_id' => $image->variation_id
|
||||
];
|
||||
});
|
||||
}
|
||||
}
|
||||
74
app/Models/Review.php
Normal file
74
app/Models/Review.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class Review extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'product_id',
|
||||
'rating',
|
||||
'title',
|
||||
'comment',
|
||||
'advantages',
|
||||
'disadvantages',
|
||||
'helpful_count',
|
||||
'unhelpful_count',
|
||||
'is_approved'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_approved' => 'boolean',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function product(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Product::class);
|
||||
}
|
||||
|
||||
public function getDateAttribute(): string
|
||||
{
|
||||
return $this->created_at->format('d.m.Y');
|
||||
}
|
||||
|
||||
public function getIsFreshAttribute(): bool
|
||||
{
|
||||
return $this->created_at->gt(now()->subWeek());
|
||||
}
|
||||
|
||||
public function scopeApproved($query)
|
||||
{
|
||||
return $query->where('is_approved', true);
|
||||
}
|
||||
|
||||
public function scopeByRating($query, $rating)
|
||||
{
|
||||
return $query->where('rating', $rating);
|
||||
}
|
||||
|
||||
public function scopeHelpful($query)
|
||||
{
|
||||
return $query->orderBy('helpful_count', 'desc');
|
||||
}
|
||||
|
||||
public function scopeLatest($query)
|
||||
{
|
||||
return $query->orderBy('created_at', 'desc');
|
||||
}
|
||||
|
||||
public function scopeUserProduct($query, $userId, $productId)
|
||||
{
|
||||
return $query->where('user_id', $userId)
|
||||
->where('product_id', $productId);
|
||||
}
|
||||
}
|
||||
32
app/Models/Role.php
Normal file
32
app/Models/Role.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class Role extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'slug',
|
||||
'description',
|
||||
];
|
||||
|
||||
public function users(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(User::class)->withTimestamps();
|
||||
}
|
||||
|
||||
public function permissions(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Permission::class)->withTimestamps();
|
||||
}
|
||||
|
||||
public function hasPermission(string $permissionSlug): bool
|
||||
{
|
||||
return $this->permissions()->where('slug', $permissionSlug)->exists();
|
||||
}
|
||||
}
|
||||
110
app/Models/User.php
Normal file
110
app/Models/User.php
Normal file
@@ -0,0 +1,110 @@
|
||||
<?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;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
class User extends Authenticatable
|
||||
{
|
||||
use HasApiTokens, HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* The attributes that are mass assignable.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
'phone',
|
||||
'role_id',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be hidden for serialization.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $hidden = [
|
||||
'password',
|
||||
'remember_token',
|
||||
];
|
||||
|
||||
/**
|
||||
* The attributes that should be cast.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
protected $casts = [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
];
|
||||
|
||||
public function role(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Role::class);
|
||||
}
|
||||
|
||||
public function permissions(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Permission::class, 'role_user', 'user_id', 'role_id')
|
||||
->join('permission_role', 'role_user.role_id', '=', 'permission_role.role_id')
|
||||
->join('permissions', 'permission_role.permission_id', '=', 'permissions.id')
|
||||
->select('permissions.*')
|
||||
->distinct()
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
public function hasRole(string $roleSlug): bool
|
||||
{
|
||||
return $this->role()->where('slug', $roleSlug)->exists();
|
||||
}
|
||||
|
||||
public function hasPermission(string $permissionSlug): bool
|
||||
{
|
||||
if ($this->hasRole('super_admin')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$role = $this->role;
|
||||
|
||||
return $role && $role->hasPermission($permissionSlug);
|
||||
}
|
||||
|
||||
public function hasAnyPermission(array $permissionSlugs): bool
|
||||
{
|
||||
if ($this->is_super_admin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ($permissionSlugs as $permissionSlug) {
|
||||
if ($this->hasPermission($permissionSlug)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function hasAllPermissions(array $permissionSlugs): bool
|
||||
{
|
||||
if ($this->is_super_admin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ($permissionSlugs as $permissionSlug) {
|
||||
if (!$this->hasPermission($permissionSlug)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
16
app/Models/VariationAttribute.php
Normal file
16
app/Models/VariationAttribute.php
Normal file
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class VariationAttribute extends Model
|
||||
{
|
||||
protected $fillable = ['variation_id', 'key', 'value'];
|
||||
|
||||
public function variation(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductVariation::class, 'variation_id');
|
||||
}
|
||||
}
|
||||
47
app/Models/VariationImage.php
Normal file
47
app/Models/VariationImage.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class VariationImage extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = [
|
||||
'variation_id',
|
||||
'path',
|
||||
'sort_order',
|
||||
'is_active'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'sort_order' => 'integer',
|
||||
'is_active' => 'boolean'
|
||||
];
|
||||
|
||||
public function variation(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductVariation::class, 'variation_id');
|
||||
}
|
||||
|
||||
public function getUrlAttribute(): string
|
||||
{
|
||||
if ($this->path && file_exists(public_path($this->path))) {
|
||||
return asset($this->path);
|
||||
}
|
||||
|
||||
return asset('assets/images/products/default.svg');
|
||||
}
|
||||
|
||||
public function scopeOrdered($query)
|
||||
{
|
||||
return $query->orderBy('sort_order', 'asc');
|
||||
}
|
||||
|
||||
public function scopeActive($query)
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
}
|
||||
}
|
||||
25
app/Providers/AppServiceProvider.php
Normal file
25
app/Providers/AppServiceProvider.php
Normal file
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Pagination\Paginator;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register any application services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
Paginator::useBootstrapFive();
|
||||
}
|
||||
}
|
||||
29
app/Providers/AuthServiceProvider.php
Normal file
29
app/Providers/AuthServiceProvider.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
// use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
|
||||
class AuthServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The model to policy mappings for the application.
|
||||
*
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
protected $policies = [
|
||||
//
|
||||
];
|
||||
|
||||
/**
|
||||
* Register any authentication / authorization services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
Gate::before(function ($user, $ability) {
|
||||
return $user->hasPermission($ability);
|
||||
});
|
||||
}
|
||||
}
|
||||
19
app/Providers/BroadcastServiceProvider.php
Normal file
19
app/Providers/BroadcastServiceProvider.php
Normal file
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\Facades\Broadcast;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class BroadcastServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
Broadcast::routes();
|
||||
|
||||
require base_path('routes/channels.php');
|
||||
}
|
||||
}
|
||||
38
app/Providers/EventServiceProvider.php
Normal file
38
app/Providers/EventServiceProvider.php
Normal file
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
|
||||
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
|
||||
class EventServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The event to listener mappings for the application.
|
||||
*
|
||||
* @var array<class-string, array<int, class-string>>
|
||||
*/
|
||||
protected $listen = [
|
||||
Registered::class => [
|
||||
SendEmailVerificationNotification::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Register any events for your application.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if events and listeners should be automatically discovered.
|
||||
*/
|
||||
public function shouldDiscoverEvents(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
34
app/Providers/MenuServiceProvider.php
Normal file
34
app/Providers/MenuServiceProvider.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use App\Http\Controllers\MenuController;
|
||||
use Illuminate\Support\Facades\View;
|
||||
|
||||
class MenuServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
View::composer('*', function ($view) {
|
||||
$menuController = new MenuController();
|
||||
$menuData = $menuController->getMenuData();
|
||||
|
||||
$view->with('menuCategories', $menuData['categories']);
|
||||
$view->with('menuContacts', $menuData['contacts']);
|
||||
$view->with('menuBrands', $menuData['popularBrands']);
|
||||
$view->with('footerCategories', $menuData['footerCategories']);
|
||||
});
|
||||
}
|
||||
}
|
||||
40
app/Providers/RouteServiceProvider.php
Normal file
40
app/Providers/RouteServiceProvider.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
class RouteServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The path to your application's "home" route.
|
||||
*
|
||||
* Typically, users are redirected here after authentication.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const HOME = '/home';
|
||||
|
||||
/**
|
||||
* Define your route model bindings, pattern filters, and other route configuration.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
RateLimiter::for('api', function (Request $request) {
|
||||
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
|
||||
});
|
||||
|
||||
$this->routes(function () {
|
||||
Route::middleware('api')
|
||||
->prefix('api')
|
||||
->group(base_path('routes/api.php'));
|
||||
|
||||
Route::middleware('web')
|
||||
->group(base_path('routes/web.php'));
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user