add order on products table - issue #21

This commit is contained in:
Alexis Gousseau 2023-07-26 09:56:16 +02:00
parent a07d87b3d1
commit 591079f264
9 changed files with 325 additions and 170 deletions

View file

@ -14,6 +14,7 @@ use App\Models\Range;
use App\Models\Tag;
use App\Models\TaxRate;
use App\Models\XmlInco;
use App\Traits\Controllers\ChangesModelOrder;
use App\Traits\Controllers\UpdateModelStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
@ -22,6 +23,7 @@ use Illuminate\Support\Facades\File;
class ProductsController extends Controller
{
use UpdateModelStatus;
use ChangesModelOrder;
/**
* Display a listing of the resource.
@ -48,7 +50,7 @@ class ProductsController extends Controller
if (!empty($filter_brand)) {
$products = $products->where('brand', $filter_brand);
}
$products = $products->paginate(10);
$products = $products->orderBy('order', 'ASC')->paginate(10);
// Ici récupération des infos additionnelles pour affichage dans la liste.
foreach ($products as &$product) {

View file

@ -111,7 +111,7 @@ class ProductsController extends Controller
$productsQuery = $this->buildFilterQuery($sessionFilter);
/** @var \Illuminate\Database\Eloquent\Collection<\App\Models\Product> */
$products = $productsQuery->paginate(6);
$products = $productsQuery->orderBy('order', 'ASC')->paginate(6);
if ($request->ajax()) {
return \response()->json([ProductResource::collection($products), $products->total()]);

View file

@ -0,0 +1,42 @@
<?php
namespace App\Http\Requests\Bo;
use Illuminate\Foundation\Http\FormRequest;
class UpdateChangeOrderRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
return auth()->check();
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation(): void
{
$this->merge([
'direction' => $this->direction === 'up' ? true : false
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return [
'direction' => 'required|boolean',
];
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace App\Traits\Controllers;
use App\Http\Requests\Bo\UpdateChangeOrderRequest;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
trait ChangesModelOrder
{
/**
* Change order.
*
* @param \App\Http\Requests\Bo\UpdateChangeOrderRequest $request
* @param \Illuminate\Database\Eloquent\Model $model
* @return \Illuminate\Http\RedirectResponse
* @throws \RuntimeException Si le nom du parametre de la route ne correspond pas au model utilisé.
*/
public function changeOrder(UpdateChangeOrderRequest $request, Model $model): \Illuminate\Http\RedirectResponse
{
$params = collect(request()->route()->parameterNames);
$className = Str::ucfirst(Str::lower($params->get($params->count() - 2)));
$className = "\\App\\Models\\$className";
if (!class_exists($className)) {
throw new \RuntimeException("The $className class doesn't exist.");
}
/** @var \Illuminate\Database\Eloquent\Model|null */
$model = $className::where('id', $model->id)->first();
if (!$model) {
return redirect()->back()->with('error', trans('crud.messages.order_not_changed'));
}
return DB::transaction(function () use ($request, $className, $model) {
/** @var \Illuminate\Database\Eloquent\Model|null */
$tmp = $className::where('order', $request->direction ? '<' : '>', $model->order)
->orderBy('order', $request->direction ? 'DESC' : 'ASC')->first();
if (!$tmp) {
return redirect()->back()->with('error', trans('crud.messages.order_not_changed'));
}
$newOrder = $tmp->order;
$tmp->order = $model->order;
$model->order = $newOrder;
$tmp->saveOrFail();
$model->saveOrFail();
return redirect()->back()->with('success', trans('crud.messages.order_changed'));
});
}
}

View file

@ -0,0 +1,39 @@
<?php
use App\Models\Product;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddOrderProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('products', function (Blueprint $table) {
$table->integer('order')->default(1)->after('margin')->comment('Ordonnancement du produit.');
});
$allProducts = Product::all();
foreach ($allProducts as $key => $product) {
$product->order = ($key + 1);
$product->saveOrFail();
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('order');
});
}
}

View file

@ -0,0 +1,14 @@
<?php
return [
'messages' => [
'order_changed' => 'L\'ordre a été changé !',
'order_not_changed' => 'L\'ordre n\'a pas été changé !',
],
'other' => [
'up' => 'Modifier l\'ordre d\'apparition vers le haut',
'down' => 'Modifier l\'ordre d\'apparition vers le bas',
'right' => 'Vous n\'avez pas les droits',
]
];

View file

@ -0,0 +1,22 @@
<td class="text-center align-middle">
<div class="d-flex justify-content-center align-items-center">
<a href="{{ route('bo.' . $routeName . '.change-order', [Str::singular($routeName) => $model, 'direction' => 'up']) }}"
class="@if($loop->first and $models->onFirstPage()) invisible @endif">
<button type="submit"
class="btn btn-sm btn-outline-dark @if(($loop->first and $models->onFirstPage())) disabled @endif"
title="{{ __('crud.other.up') }}"
data-bs="tooltip">
<i class="fas fa-arrow-up"></i>
</button>
</a>
<a href="{{ route('bo.' . $routeName . '.change-order', [Str::singular($routeName) => $model, 'direction' => 'down']) }}"
class="@if($loop->last and $models->currentPage() === $models->lastPage()) invisible @endif">
<button type="submit"
class="btn btn-sm btn-outline-dark ms-1 @if($loop->last and $models->currentPage() === $models->lastPage()) disabled @endif"
title="{{ __('crud.other.down') }}"
data-bs="tooltip">
<i class="fas fa-arrow-down"></i>
</button>
</a>
</div>
</td>

View file

@ -1,127 +1,132 @@
@extends('layouts.bo-layout')
@section('content')
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Produits <small class="text-muted">Liste</small></h1>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Produits <small class="text-muted">Liste</small></h1>
<form method="GET">
<div class="row">
<label for="filter_range" class="col-form-label">Gamme</label>
<div class="col">
<select class="form-control" id="filter_range" name="filter_range">
<option value="" @if ($filter_range == '') selected @endif>Toutes</option>
@foreach($ranges as $range)
<option value="{{$range->id}}" @if ($range->id == $filter_range) selected @endif>{{$range->name}}</option>
@endforeach
</select>
</div>
<label for="filter_range" class="col-form-label">Marque</label>
<div class="col">
<select class="form-control" id="filter_brand" name="filter_brand">
<option value="" @if ($filter_brand == '') selected @endif>Toutes</option>
@foreach (ProductBrand::toArray() as $productbrand)
<option value="{{$productbrand->value}}" @if ($productbrand->value == $filter_brand) selected @endif>{{$productbrand->label}}</option>
@endforeach
</select>
</div>
<label for="filter_name" class="col-form-label">Nom</label>
<div class="col">
<input class="form-control" type="text"
placeholder="Recherchez un produit"
id="filter_name" name="filter_name"
value="{{ $filter_name ?? ''}}">
</div>
<div class="col">
<button class="btn btn-primary">Filtrer</button>
<a class="btn btn-info" href="{{ route('bo.products.index') }}">Effacer le filtre</a>
</div>
<form method="GET">
<div class="row">
<label for="filter_range" class="col-form-label">Gamme</label>
<div class="col">
<select class="form-control" id="filter_range" name="filter_range">
<option value="" @if ($filter_range == '') selected @endif>Toutes</option>
@foreach($ranges as $range)
<option value="{{$range->id}}" @if ($range->id == $filter_range) selected @endif>{{$range->name}}</option>
@endforeach
</select>
</div>
</form>
<div class="dropdown">
<button class="btn btn-primary float-right dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Ajouter un produit
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
@foreach (Config::get('theme.enum_product_types') as $productType=>$label)
<a class="dropdown-item" href="{{route('bo.products.create', $productType)}}">{{ __($label)}}</a>
@endforeach
<label for="filter_range" class="col-form-label">Marque</label>
<div class="col">
<select class="form-control" id="filter_brand" name="filter_brand">
<option value="" @if ($filter_brand == '') selected @endif>Toutes</option>
@foreach (ProductBrand::toArray() as $productbrand)
<option value="{{ $productbrand->value }}" @if ($productbrand->value == $filter_brand) selected @endif>{{ $productbrand->label }}</option>
@endforeach
</select>
</div>
<label for="filter_name" class="col-form-label">Nom</label>
<div class="col">
<input class="form-control" type="text"
placeholder="Recherchez un produit"
id="filter_name" name="filter_name"
value="{{ $filter_name ?? ''}}">
</div>
<div class="col">
<button class="btn btn-primary">Filtrer</button>
<a class="btn btn-info" href="{{ route('bo.products.index') }}">Effacer le filtre</a>
</div>
</div>
</div>
<table class="table">
<thead>
@if(count(Config::get('theme.enum_product_types'))>1)
<th scope="col">Type</th>
@endif
<th scope="col">Ref Externe</th>
<th scope="col">Image</th>
<th scope="col">Nom</th>
<th scope="col">Marque</th>
<th scope="col">Prix en €</th>
<th scope="col">Stock</th>
<th scope="col">Référence</th>
<th scope="col">Slug</th>
<th scope="col">Gamme</th>
<th scope="col">Publié</th>
<th></th>
</thead>
<tbody>
@foreach ($products as $product)
<tr>
@if(count(Config::get('theme.enum_product_types'))>1)
<td>
{{ Config::get('theme.enum_product_types')[$product->product_type] }}
</td>
@endif
<td>
@if($product->product_type == "foodProduct")
{{ $product->foodProduct->no_art }}
@endif
</td>
<td>
@if ($product->picture !== null)
<a data-fancybox="gallery" href="/images/produits/{{$product->picture}}">
<img src="/images/produits/{{$product->picture}}" alt="{{$product->name}}" style="max-height: 100px;">
</a>
@endif
</td>
<td>{{$product->name}}</td>
<td>{{$product->brand->label ?? ''}}</td>
<td>{{number_format($product->price, 2, ',', ' ')}}€</td>
<td>{{number_format($product->stock, 0, ',', ' ')}}</td>
<td>{{$product->reference}}</td>
<td>{{$product->slug}}</td>
<td>{{$product->range->name}}</td>
<td>
<form action="{{ route('bo.products.change-published', $product) }}" method="POST">
@csrf
<button type="submit"
class="btn btn-sm"
title="{{ __($product->status ? __('Dépublier') : __('Publier')) }}"
data-bs-toggle="tooltip">
@if($product->status)
<i class="fas fa-check check-green"></i>
@else
<i class="fas fa-times cross-red"></i>
@endif
</button>
</form>
</td>
<td class="text-center">
<a href="{{route('bo.products.edit', $product->id)}}" class="btn btn-sm btn-primary">Éditer</a>
<form action="{{route('bo.products.destroy', $product->id)}}" method="POST" class="d-inline">
@method('DELETE')
@csrf
<input type="submit" class="btn btn-sm btn-danger" value="Supprimer"
onclick="return confirm('Êtes-vous sûr(e) ?')">
</form>
</td>
</tr>
</form>
<div class="dropdown">
<button class="btn btn-primary float-right dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Ajouter un produit
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
@foreach (Config::get('theme.enum_product_types') as $productType=>$label)
<a class="dropdown-item" href="{{route('bo.products.create', $productType)}}">{{ __($label) }}</a>
@endforeach
</tbody>
</table>
@if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )
{{ $products->appends(['filter_name' => $filter_name,'filter_range' => $filter_range])->links() }}
@endif
</div>
</div>
</div>
<table class="table">
<thead>
@if(count(Config::get('theme.enum_product_types'))>1)
<th scope="col">Type</th>
@endif
<th scope="col">Ref Externe</th>
<th scope="col">Image</th>
<th scope="col">Nom</th>
<th scope="col">Marque</th>
<th scope="col">Prix en €</th>
<th scope="col">Stock</th>
<th scope="col">Référence</th>
<th scope="col">Gamme</th>
<th scope="col">Publié</th>
<th scope="col">Ordre</th>
<th></th>
</thead>
<tbody>
@foreach ($products as $product)
<tr>
@if(count(Config::get('theme.enum_product_types'))>1)
<td>
{{ Config::get('theme.enum_product_types')[$product->product_type] }}
</td>
@endif
<td>
@if($product->product_type == "foodProduct")
{{ $product->foodProduct->no_art }}
@endif
</td>
<td>
@if ($product->picture !== null)
<a data-fancybox="gallery" href="/images/produits/{{ $product->picture }}">
<img src="/images/produits/{{ $product->picture }}" alt="{{ $product->name }}" style="max-height: 100px;">
</a>
@endif
</td>
<td>{{ $product->name }}</td>
<td>{{ $product->brand->label ?? '' }}</td>
<td>{{ number_format($product->price, 2, ',', ' ') }}€</td>
<td>{{ number_format($product->stock, 0, ',', ' ') }}</td>
<td>{{ $product->reference }}</td>
<td>{{ $product->range->name }}</td>
<td>
<form action="{{ route('bo.products.change-published', $product) }}" method="POST">
@csrf
<button type="submit"
class="btn btn-sm"
title="{{ __($product->status ? __('Dépublier') : __('Publier')) }}"
data-bs-toggle="tooltip">
@if($product->status)
<i class="fas fa-check check-green"></i>
@else
<i class="fas fa-times cross-red"></i>
@endif
</button>
</form>
</td>
@php $routeName = request()->route()->getName(); @endphp
@include('bo.modules.change-model-order', [
'routeName' => 'products',
'models' => $products,
'model' => $product
])
<td class="text-center">
<a href="{{ route('bo.products.edit', $product->id) }}" class="btn btn-sm btn-primary">Éditer</a>
<form action="{{ route('bo.products.destroy', $product->id) }}" method="POST" class="d-inline">
@method('DELETE')
@csrf
<input type="submit" class="btn btn-sm btn-danger" value="Supprimer"
onclick="return confirm('Êtes-vous sûr(e) ?')">
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
@if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )
{{ $products->appends(['filter_name' => $filter_name,'filter_range' => $filter_range])->links() }}
@endif
@endsection

View file

@ -10,6 +10,10 @@ use App\Http\Controllers\Bo\FaqController;
use App\Http\Controllers\Bo\SettingsController;
use App\Http\Controllers\Bo\OrdersController;
use App\Http\Controllers\Bo\CreneauxController;
use App\Http\Controllers\Bo\MagasinsController;
use App\Http\Controllers\Bo\ProductsController;
use App\Http\Controllers\Bo\SlidesController;
use App\Http\Controllers\Bo\TagsController;
/*
* --------------------------------------------------------------------------
@ -52,67 +56,39 @@ Route::namespace('App\Http\Controllers\Bo')
Route::post('/magasins/{id}/creneaux', [CreneauxController::class, 'updateSettings'])
->name('creneaux.settings.update');
// Exceptions de collecte.
Route::post(
'/ajax/save-creneaux-exception',
[\App\Http\Controllers\Bo\MagasinsController::class, 'saveExceptions']
);
Route::post(
'/ajax/delete-creneaux-exception',
[\App\Http\Controllers\Bo\MagasinsController::class, 'destroyExceptions']
);
Route::post('/ajax/save-creneaux-exception', [MagasinsController::class, 'saveExceptions']);
Route::post('/ajax/delete-creneaux-exception', [MagasinsController::class, 'destroyExceptions']);
// Recherche d'inco.
Route::post('/ajax/check-inco-data', [\App\Http\Controllers\Bo\ProductsController::class, 'checkIncoData']);
Route::post(
'/ajax/get-inco-images',
[\App\Http\Controllers\Bo\ProductsController::class, 'getPrepareIncoImages']
);
Route::post('/ajax/set-inco-images', [\App\Http\Controllers\Bo\ProductsController::class, 'setIncoImage']);
Route::post('/ajax/check-inco-data', [ProductsController::class, 'checkIncoData']);
Route::post('/ajax/get-inco-images', [ProductsController::class, 'getPrepareIncoImages']);
Route::post('/ajax/set-inco-images', [ProductsController::class, 'setIncoImage']);
// Produits.
// Route ajoutée avant la déclaration de route resource.
// Sinon la forme /products/{product} l'emporte lors du routage.
Route::get(
'/products/starred',
[\App\Http\Controllers\Bo\ProductsController::class, 'starred']
)->name('products.starred');
Route::get(
'/products/create/{product_type?}',
[\App\Http\Controllers\Bo\ProductsController::class, 'create']
)->name('products.create');
Route::resource(
'products',
'\App\Http\Controllers\Bo\ProductsController'
)->except(['create', 'show']);
Route::post(
'/products/{product}/change-published',
[\App\Http\Controllers\Bo\ProductsController::class, 'changePublished']
)
->name('products.change-published');
Route::get('/products/starred', [ProductsController::class, 'starred'])->name('products.starred');
Route::get('/products/create/{product_type?}', [ProductsController::class, 'create'])
->name('products.create');
Route::resource('products', 'ProductsController')->except(['create', 'show']);
Route::post('/products/{product}/change-published', [ProductsController::class, 'changePublished'])
->name('products.change-published');
Route::get('/products/change-order/{product}/{direction}', [ProductsController::class, 'changeOrder'])
->where('direction', 'up|down')->name('products.change-order');
// Slides.
Route::resource('slides', SlidesController::class)->except(['show']);
Route::resource('sliders', SlidersController::class)->except(['show']);
Route::resource('tags', TagsController::class)->except(['show']);
Route::resource('promotions', PromotionsController::class)->except(['show']);
Route::resource('magasins', MagasinsController::class)->except(['show']);
Route::resources(['ranges' => RangesController::class]);
Route::get(
'/slide/change-order/{id}/{action}',
[App\Http\Controllers\Bo\SlidesController::class, 'changeOrder']
)->name('slides.change-order');
Route::get(
'/tag/change-order/{id}/{action}',
[App\Http\Controllers\Bo\TagsController::class, 'changeOrder']
)->name('tags.change-order');
Route::get(
'/tag/toggle-status/{id}',
[App\Http\Controllers\Bo\TagsController::class, 'toggleStatus']
)->name('tags.toggle-status');
Route::get(
'/customer-info/{id}/{mode?}',
[OrdersController::class, 'getCustomerInfo']
)->name('get-customer-info');
Route::get(
'/magasin-info/{id}/{mode?}',
[App\Http\Controllers\Bo\MagasinsController::class, 'getMagasinInfo']
)->name('get-magasin-info');
Route::get('/slide/change-order/{id}/{action}', [SlidesController::class, 'changeOrder'])
->name('slides.change-order');
Route::get('/tag/change-order/{id}/{action}', [TagsController::class, 'changeOrder'])
->name('tags.change-order');
Route::get('/tag/toggle-status/{id}', [TagsController::class, 'toggleStatus'])->name('tags.toggle-status');
Route::get('/customer-info/{id}/{mode?}', [OrdersController::class, 'getCustomerInfo'])
->name('get-customer-info');
Route::get('/magasin-info/{id}/{mode?}', [MagasinsController::class, 'getMagasinInfo'])
->name('get-magasin-info');
// Commandes.
Route::get('/orders', [OrdersController::class, 'index'])->name('orders');
Route::get('/orders/today', [OrdersController::class, 'today'])->name('orders.today');