Merge branch 'develop' into trunk
This commit is contained in:
commit
3d60dfb2b4
53 changed files with 650 additions and 157 deletions
|
|
@ -36,6 +36,7 @@ final class CreateProduct implements Action
|
|||
'category' => $input->category,
|
||||
'technology' => $input->technology,
|
||||
'is_egalim' => $input->isEgalim,
|
||||
'is_published' => $input->isPublished,
|
||||
'breeding_methods' => $input->breedingMethods,
|
||||
'businesses' => $input->businesses,
|
||||
'formats' => $input->formats,
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ final readonly class CreateProductInput implements ActionInput
|
|||
public ProductCategory $category,
|
||||
public Technology $technology,
|
||||
public bool $isEgalim,
|
||||
public bool $isPublished,
|
||||
public array $breedingMethods,
|
||||
public array $businesses,
|
||||
public array $formats,
|
||||
|
|
|
|||
112
app/Cqs/Actions/Products/Duplicate/DuplicateProduct.php
Normal file
112
app/Cqs/Actions/Products/Duplicate/DuplicateProduct.php
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Products\Duplicate;
|
||||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Lib\PublicS3Disk;
|
||||
use App\Models\Product;
|
||||
use Domain\Models\ValueObjects\Entities\ProductId;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* phpcs:disable Generic.Files.LineLength.TooLong
|
||||
*
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Products\Duplicate\DuplicateProductInput, \Domain\Models\ValueObjects\Entities\ProductId|\App\Cqs\Actions\Products\Duplicate\FailedToDuplicateProduct>
|
||||
* phpcs:enable
|
||||
*/
|
||||
final class DuplicateProduct implements Action
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PublicS3Disk $s3Disk,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Products\Duplicate\DuplicateProductInput $input
|
||||
*/
|
||||
public function __invoke(ActionInput $input): ProductId | FailedToDuplicateProduct
|
||||
{
|
||||
Assert::isInstanceOf($input, DuplicateProductInput::class);
|
||||
|
||||
$original = Product::withTrashed()->findOrFail((string) $input->productId->value);
|
||||
|
||||
$clone = $original->replicate();
|
||||
$clone->name = $this->generateUniqueName($original->name);
|
||||
$clone->slug = Str::slug($clone->name);
|
||||
|
||||
$duplicatedPicture = $this->duplicateFile($original->picture);
|
||||
if ($duplicatedPicture !== null) {
|
||||
$clone->picture = $duplicatedPicture;
|
||||
}
|
||||
$clone->pdf = $this->duplicateFile($original->pdf);
|
||||
$clone->is_published = false;
|
||||
|
||||
if (! $clone->save()) {
|
||||
return new FailedToDuplicateProduct();
|
||||
}
|
||||
|
||||
return new ProductId(Uuid::fromString($clone->id));
|
||||
}
|
||||
|
||||
private function generateUniqueName(string $originalName): string
|
||||
{
|
||||
$rootName = $originalName;
|
||||
if (preg_match('/^(.*?)(?: \(Copie(?: (\d+))?\))?$/', $originalName, $matches)) {
|
||||
$rootName = $matches[1];
|
||||
}
|
||||
|
||||
$baseName = "{$rootName} (Copie)";
|
||||
if (
|
||||
! Product::withTrashed()
|
||||
->where('name', $baseName)
|
||||
->orWhere('slug', Str::slug($baseName))
|
||||
->exists()
|
||||
) {
|
||||
return $baseName;
|
||||
}
|
||||
|
||||
$i = 2;
|
||||
while (
|
||||
Product::withTrashed()
|
||||
->where('name', "{$rootName} (Copie {$i})")
|
||||
->orWhere('slug', Str::slug("{$rootName} (Copie {$i})"))
|
||||
->exists()
|
||||
) {
|
||||
$i++;
|
||||
}
|
||||
|
||||
return "{$rootName} (Copie {$i})";
|
||||
}
|
||||
|
||||
private function duplicateFile(?StorageFilePath $filePath): ?StorageFilePath
|
||||
{
|
||||
if ($filePath === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$sourcePath = $filePath->value;
|
||||
$disk = Storage::disk($this->s3Disk->disk->value);
|
||||
|
||||
if (! $disk->exists($sourcePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$extension = pathinfo($sourcePath, PATHINFO_EXTENSION);
|
||||
$dirname = pathinfo($sourcePath, PATHINFO_DIRNAME);
|
||||
$newFilename = Str::uuid()->toString() . ($extension !== '' ? '.' . $extension : '');
|
||||
$destinationPath = ($dirname !== '.' && $dirname !== '') ? "{$dirname}/{$newFilename}" : $newFilename;
|
||||
|
||||
if (! $disk->copy($sourcePath, $destinationPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new StorageFilePath($destinationPath);
|
||||
}
|
||||
}
|
||||
16
app/Cqs/Actions/Products/Duplicate/DuplicateProductInput.php
Normal file
16
app/Cqs/Actions/Products/Duplicate/DuplicateProductInput.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Products\Duplicate;
|
||||
|
||||
use App\Contracts\ActionInput;
|
||||
use Domain\Models\ValueObjects\Entities\ProductId;
|
||||
|
||||
final readonly class DuplicateProductInput implements ActionInput
|
||||
{
|
||||
public function __construct(
|
||||
public ProductId $productId,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Products\Duplicate;
|
||||
|
||||
final readonly class FailedToDuplicateProduct
|
||||
{
|
||||
}
|
||||
|
|
@ -47,6 +47,7 @@ final class UpdateProduct implements Action
|
|||
'category' => $input->category,
|
||||
'technology' => $input->technology,
|
||||
'is_egalim' => $input->isEgalim,
|
||||
'is_published' => $input->isPublished,
|
||||
'breeding_methods' => $input->breedingMethods,
|
||||
'businesses' => $input->businesses,
|
||||
'formats' => $input->formats,
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ final readonly class UpdateProductInput implements ActionInput
|
|||
public ProductCategory $category,
|
||||
public Technology $technology,
|
||||
public bool $isEgalim,
|
||||
public bool $isPublished,
|
||||
public array $breedingMethods,
|
||||
public array $businesses,
|
||||
public array $formats,
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ final class CreateRecipe implements Action
|
|||
'seo_title' => $input->seoTitle,
|
||||
'seo_description' => $input->seoDescription,
|
||||
'name' => $input->name,
|
||||
'is_published' => $input->isPublished,
|
||||
'picture' => $input->picture,
|
||||
'picture_alt' => $input->pictureAlt,
|
||||
'picture_title' => $input->pictureTitle,
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ final readonly class CreateRecipeInput implements ActionInput
|
|||
public string $name,
|
||||
public string $seoTitle,
|
||||
public string $seoDescription,
|
||||
public bool $isPublished,
|
||||
public ProductCategory $productCategory,
|
||||
public ConsumptionTime $consomptionTime,
|
||||
public Inspiration $inspiration,
|
||||
|
|
|
|||
116
app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipe.php
Normal file
116
app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipe.php
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Recipes\Duplicate;
|
||||
|
||||
use App\Contracts\Action;
|
||||
use App\Contracts\ActionInput;
|
||||
use App\Lib\PublicS3Disk;
|
||||
use App\Models\Recipe;
|
||||
use Domain\Models\ValueObjects\Entities\RecipeId;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Ramsey\Uuid\Uuid;
|
||||
use Uwil\Storage\Lib\ValueObjects\StorageFilePath;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* phpcs:disable Generic.Files.LineLength.TooLong
|
||||
*
|
||||
* @implements \App\Contracts\Action<\App\Cqs\Actions\Recipes\Duplicate\DuplicateRecipeInput, \Domain\Models\ValueObjects\Entities\RecipeId|\App\Cqs\Actions\Recipes\Duplicate\FailedToDuplicateRecipe>
|
||||
* phpcs:enable
|
||||
*/
|
||||
final class DuplicateRecipe implements Action
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PublicS3Disk $s3Disk,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \App\Cqs\Actions\Recipes\Duplicate\DuplicateRecipeInput $input
|
||||
*/
|
||||
public function __invoke(ActionInput $input): RecipeId | FailedToDuplicateRecipe
|
||||
{
|
||||
Assert::isInstanceOf($input, DuplicateRecipeInput::class);
|
||||
|
||||
$original = Recipe::withTrashed()->with('products')->findOrFail((string) $input->recipeId->value);
|
||||
|
||||
$clone = $original->replicate();
|
||||
$clone->name = $this->generateUniqueName($original->name);
|
||||
$clone->slug = Str::slug($clone->name);
|
||||
|
||||
$duplicatedPicture = $this->duplicateFile($original->picture);
|
||||
if ($duplicatedPicture !== null) {
|
||||
$clone->picture = $duplicatedPicture;
|
||||
}
|
||||
|
||||
$clone->is_published = false;
|
||||
|
||||
if (! $clone->save()) {
|
||||
return new FailedToDuplicateRecipe();
|
||||
}
|
||||
|
||||
$productIds = $original->products->pluck('id')->all();
|
||||
if (! empty($productIds)) {
|
||||
$clone->products()->sync($productIds);
|
||||
}
|
||||
|
||||
return new RecipeId(Uuid::fromString($clone->id));
|
||||
}
|
||||
|
||||
private function generateUniqueName(string $originalName): string
|
||||
{
|
||||
$rootName = $originalName;
|
||||
if (preg_match('/^(.*?)(?: \(Copie(?: (\d+))?\))?$/', $originalName, $matches)) {
|
||||
$rootName = $matches[1];
|
||||
}
|
||||
|
||||
$baseName = "{$rootName} (Copie)";
|
||||
if (
|
||||
! Recipe::withTrashed()
|
||||
->where('name', $baseName)
|
||||
->orWhere('slug', Str::slug($baseName))
|
||||
->exists()
|
||||
) {
|
||||
return $baseName;
|
||||
}
|
||||
|
||||
$i = 2;
|
||||
while (
|
||||
Recipe::withTrashed()
|
||||
->where('name', "{$rootName} (Copie {$i})")
|
||||
->orWhere('slug', Str::slug("{$rootName} (Copie {$i})"))->exists()
|
||||
) {
|
||||
$i++;
|
||||
}
|
||||
|
||||
return "{$rootName} (Copie {$i})";
|
||||
}
|
||||
|
||||
private function duplicateFile(?StorageFilePath $filePath): ?StorageFilePath
|
||||
{
|
||||
if ($filePath === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$sourcePath = $filePath->value;
|
||||
$disk = Storage::disk($this->s3Disk->disk->value);
|
||||
|
||||
if (! $disk->exists($sourcePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$extension = pathinfo($sourcePath, PATHINFO_EXTENSION);
|
||||
$dirname = pathinfo($sourcePath, PATHINFO_DIRNAME);
|
||||
$newFilename = Str::uuid()->toString() . ($extension !== '' ? '.' . $extension : '');
|
||||
$destinationPath = ($dirname !== '.' && $dirname !== '') ? "{$dirname}/{$newFilename}" : $newFilename;
|
||||
|
||||
if (! $disk->copy($sourcePath, $destinationPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new StorageFilePath($destinationPath);
|
||||
}
|
||||
}
|
||||
16
app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipeInput.php
Normal file
16
app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipeInput.php
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Recipes\Duplicate;
|
||||
|
||||
use App\Contracts\ActionInput;
|
||||
use Domain\Models\ValueObjects\Entities\RecipeId;
|
||||
|
||||
final readonly class DuplicateRecipeInput implements ActionInput
|
||||
{
|
||||
public function __construct(
|
||||
public RecipeId $recipeId,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Cqs\Actions\Recipes\Duplicate;
|
||||
|
||||
final readonly class FailedToDuplicateRecipe
|
||||
{
|
||||
}
|
||||
|
|
@ -41,6 +41,7 @@ final class UpdateRecipe implements Action
|
|||
'seo_title' => $input->seoTitle,
|
||||
'seo_description' => $input->seoDescription,
|
||||
'name' => $input->name,
|
||||
'is_published' => $input->isPublished,
|
||||
'picture_alt' => $input->pictureAlt,
|
||||
'picture_title' => $input->pictureTitle,
|
||||
'product_category' => $input->productCategory,
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ final readonly class UpdateRecipeInput implements ActionInput
|
|||
public string $name,
|
||||
public string $seoTitle,
|
||||
public string $seoDescription,
|
||||
public bool $isPublished,
|
||||
public ProductCategory $productCategory,
|
||||
public ConsumptionTime $consomptionTime,
|
||||
public Inspiration $inspiration,
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ final readonly class GetBoPaginatedProductsQuery implements Query
|
|||
'category',
|
||||
'technology',
|
||||
'is_egalim',
|
||||
'is_published',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
];
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ namespace App\Cqs\Queries\Products;
|
|||
use App\Contracts\Directories\ProductDirectory;
|
||||
use App\Contracts\Query;
|
||||
use App\Contracts\QueryInput;
|
||||
use App\Dto\CategoryProductsDto;
|
||||
use Domain\Models\ValueObjects\Products\ProductCategory;
|
||||
use Webmozart\Assert\Assert;
|
||||
|
||||
|
|
@ -22,7 +21,7 @@ final readonly class GetCategoriesProductsQuery implements Query
|
|||
}
|
||||
|
||||
/**
|
||||
* @return array<int, CategoryProductsDto>
|
||||
* @return array<int, \App\Dto\CategoryProductsDto>
|
||||
*/
|
||||
public function __invoke(QueryInput $input): array
|
||||
{
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ final readonly class GetBoPaginatedRecipesQuery implements Query
|
|||
'consomption_time',
|
||||
'inspiration',
|
||||
'season',
|
||||
'is_published',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
];
|
||||
|
|
|
|||
|
|
@ -14,7 +14,11 @@ use Illuminate\Pagination\LengthAwarePaginator;
|
|||
use Webmozart\Assert\Assert;
|
||||
|
||||
/**
|
||||
* phpcs:disable Generic.Files.LineLength.TooLong
|
||||
*
|
||||
* @implements \App\Contracts\Query<\App\Cqs\Queries\Recipes\GetFrontRecipesQueryInput, \Illuminate\Pagination\LengthAwarePaginator<array-key, \App\Dto\RecipeDto>>
|
||||
*
|
||||
* phpcs:enable
|
||||
*/
|
||||
final readonly class GetFrontRecipesQuery implements Query
|
||||
{
|
||||
|
|
|
|||
|
|
@ -103,6 +103,7 @@ class EloquentProductDirectory implements ProductDirectory
|
|||
$dbQueryCallback = function (Builder $query) use ($category, $breedingMethods, $technologies, $businesses, $isEgalim) {
|
||||
/** @var \Illuminate\Database\Eloquent\Builder<Product> $query */
|
||||
$query->where('category', $category->value)
|
||||
->where('is_published', true)
|
||||
->with(['recipes']);
|
||||
|
||||
if (! empty($breedingMethods)) {
|
||||
|
|
@ -182,6 +183,7 @@ class EloquentProductDirectory implements ProductDirectory
|
|||
category: $product->category,
|
||||
technology: $product->technology,
|
||||
isEgalim: $product->is_egalim,
|
||||
isPublished: (bool) $product->is_published,
|
||||
breedingMethods: $product->breeding_methods->all(),
|
||||
businesses: $product->businesses->all(),
|
||||
detailsAndAdvantages: $product->details_and_advantages,
|
||||
|
|
@ -217,6 +219,7 @@ class EloquentProductDirectory implements ProductDirectory
|
|||
}
|
||||
|
||||
return $recipe->products()
|
||||
->where('is_published', true)
|
||||
->limit($limit)
|
||||
->get()
|
||||
->map(fn (Product $product) => $this->mapToEntity($product))
|
||||
|
|
|
|||
|
|
@ -49,7 +49,8 @@ class EloquentRecipeDirectory implements RecipeDirectory
|
|||
): LengthAwarePaginator {
|
||||
$dbQueryCallback = function (Builder $query) use ($productRanges, $consumptionTimes, $inspirations, $seasons) {
|
||||
/** @var \Illuminate\Database\Eloquent\Builder<Recipe> $query */
|
||||
$query->with(['products']);
|
||||
$query->with(['products'])
|
||||
->where('is_published', true);
|
||||
|
||||
if (! empty($productRanges)) {
|
||||
$rangesValues = array_map(fn ($r) => $r->value, $productRanges);
|
||||
|
|
@ -103,6 +104,7 @@ class EloquentRecipeDirectory implements RecipeDirectory
|
|||
id: new RecipeId(Uuid::fromString($recipe->id)),
|
||||
name: $recipe->name,
|
||||
slug: $recipe->slug,
|
||||
isPublished: (bool) $recipe->is_published,
|
||||
picture: $recipe->picture?->value,
|
||||
seoTitle: $recipe->seo_title,
|
||||
seoDescription: $recipe->seo_description,
|
||||
|
|
@ -132,6 +134,7 @@ class EloquentRecipeDirectory implements RecipeDirectory
|
|||
}
|
||||
|
||||
return $product->recipes()
|
||||
->where('is_published', true)
|
||||
->limit($limit)
|
||||
->get()
|
||||
->map(fn (Recipe $recipe) => $this->mapToEntity($recipe))
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ final readonly class ProductDto implements \JsonSerializable, Arrayable, UrlRout
|
|||
public ProductCategory $category,
|
||||
public Technology $technology,
|
||||
public bool $isEgalim,
|
||||
public bool $isPublished,
|
||||
public array $breedingMethods,
|
||||
public array $businesses,
|
||||
public array $formats,
|
||||
|
|
@ -75,6 +76,7 @@ final readonly class ProductDto implements \JsonSerializable, Arrayable, UrlRout
|
|||
category: $product->category,
|
||||
technology: $product->technology,
|
||||
isEgalim: (bool) $product->is_egalim,
|
||||
isPublished: (bool) $product->is_published,
|
||||
breedingMethods: $product->breeding_methods->values()->all(),
|
||||
businesses: $product->businesses->values()->all(),
|
||||
formats: $product->formats->values()->all(),
|
||||
|
|
@ -113,6 +115,7 @@ final readonly class ProductDto implements \JsonSerializable, Arrayable, UrlRout
|
|||
category: $product->category,
|
||||
technology: $product->technology,
|
||||
isEgalim: $product->isEgalim,
|
||||
isPublished: $product->isPublished,
|
||||
breedingMethods: $product->breedingMethods,
|
||||
businesses: $product->businesses,
|
||||
formats: $product->formats,
|
||||
|
|
@ -146,6 +149,7 @@ final readonly class ProductDto implements \JsonSerializable, Arrayable, UrlRout
|
|||
category: ProductCategory::OMELETS_AND_DELI_AND_DESSERT_LINES,
|
||||
technology: Technology::FRESH,
|
||||
isEgalim: false,
|
||||
isPublished: true,
|
||||
breedingMethods: [],
|
||||
businesses: [],
|
||||
formats: [],
|
||||
|
|
@ -210,6 +214,7 @@ final readonly class ProductDto implements \JsonSerializable, Arrayable, UrlRout
|
|||
'category' => $this->category->value,
|
||||
'technology' => $this->technology->value,
|
||||
'is_egalim' => $this->isEgalim,
|
||||
'is_published' => $this->isPublished,
|
||||
'breeding_methods' => $this->breedingMethods,
|
||||
'businesses' => $this->businesses,
|
||||
'formats' => $this->formats,
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ final readonly class RecipeDto implements Arrayable, JsonSerializable, UrlRoutab
|
|||
public string $pictureAlt,
|
||||
public string $pictureTitle,
|
||||
public string $slug,
|
||||
public bool $isPublished,
|
||||
public ProductCategory $productCategory,
|
||||
public ConsumptionTime $consomptionTime,
|
||||
public Inspiration $inspiration,
|
||||
|
|
@ -62,6 +63,7 @@ final readonly class RecipeDto implements Arrayable, JsonSerializable, UrlRoutab
|
|||
pictureAlt: (string) $recipe->picture_alt,
|
||||
pictureTitle: (string) $recipe->picture_title,
|
||||
slug: (string) $recipe->slug,
|
||||
isPublished: (bool) $recipe->is_published,
|
||||
productCategory: $recipe->product_category,
|
||||
consomptionTime: $recipe->consomption_time,
|
||||
inspiration: $recipe->inspiration,
|
||||
|
|
@ -93,6 +95,7 @@ final readonly class RecipeDto implements Arrayable, JsonSerializable, UrlRoutab
|
|||
pictureAlt: '',
|
||||
pictureTitle: '',
|
||||
slug: $recipe->slug,
|
||||
isPublished: $recipe->isPublished,
|
||||
productCategory: $recipe->productRange,
|
||||
consomptionTime: $recipe->consomptionTime,
|
||||
inspiration: $recipe->inspiration,
|
||||
|
|
@ -120,6 +123,7 @@ final readonly class RecipeDto implements Arrayable, JsonSerializable, UrlRoutab
|
|||
pictureAlt: 'dummy-picture-alt',
|
||||
pictureTitle: 'dummy-picture-title',
|
||||
slug: 'dummy-slug',
|
||||
isPublished: true,
|
||||
productCategory: ProductCategory::OMELETS_AND_DELI_AND_DESSERT_LINES,
|
||||
consomptionTime: ConsumptionTime::LUNCH_DINNER,
|
||||
inspiration: Inspiration::FRENCH_COOKING,
|
||||
|
|
@ -173,6 +177,7 @@ final readonly class RecipeDto implements Arrayable, JsonSerializable, UrlRoutab
|
|||
'id' => $this->id,
|
||||
'name' => $this->name,
|
||||
'slug' => $this->slug,
|
||||
'is_published' => $this->isPublished,
|
||||
'seo_title' => $this->seoTitle,
|
||||
'seo_description' => $this->seoDescription,
|
||||
'picture' => $this->pictureUrl,
|
||||
|
|
|
|||
|
|
@ -8,6 +8,8 @@ use App\Contracts\Executor;
|
|||
use App\Cqs\Actions\Products\Create\CreateProduct;
|
||||
use App\Cqs\Actions\Products\Delete\DeleteProduct;
|
||||
use App\Cqs\Actions\Products\Delete\DeleteProductInput;
|
||||
use App\Cqs\Actions\Products\Duplicate\DuplicateProduct;
|
||||
use App\Cqs\Actions\Products\Duplicate\DuplicateProductInput;
|
||||
use App\Cqs\Actions\Products\ForceDelete\ForceDeleteProduct;
|
||||
use App\Cqs\Actions\Products\ForceDelete\ForceDeleteProductInput;
|
||||
use App\Cqs\Actions\Products\Restore\RestoreProduct;
|
||||
|
|
@ -140,11 +142,22 @@ class ProductController extends BackendController
|
|||
};
|
||||
}
|
||||
|
||||
public function duplicate(ProductDto $product): Response
|
||||
public function duplicate(ProductDto $product, DuplicateProduct $duplicateProduct): RedirectResponse
|
||||
{
|
||||
$model = Product::withTrashed()->findOrFail($product->id);
|
||||
$this->authorize('duplicate', $product);
|
||||
|
||||
return $this->create($model->replicate());
|
||||
$result = $this->executor->execute($duplicateProduct, new DuplicateProductInput($product->getId()));
|
||||
|
||||
return match (true) {
|
||||
$result instanceof ProductId => redirect()->route('back.products.edit', $result)
|
||||
->with('success', trans('back.has_been_duplicated', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.product', 1)),
|
||||
])),
|
||||
default => redirect()->back()
|
||||
->with('error', trans('back.cannot_be_duplicated', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.product', 1)),
|
||||
])),
|
||||
};
|
||||
}
|
||||
|
||||
public function restore(string $id, RestoreProduct $restoreProduct): RedirectResponse
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ use App\Contracts\QueryInputEmpty;
|
|||
use App\Cqs\Actions\Recipes\Create\CreateRecipe;
|
||||
use App\Cqs\Actions\Recipes\Delete\DeleteRecipe;
|
||||
use App\Cqs\Actions\Recipes\Delete\DeleteRecipeInput;
|
||||
use App\Cqs\Actions\Recipes\Duplicate\DuplicateRecipe;
|
||||
use App\Cqs\Actions\Recipes\Duplicate\DuplicateRecipeInput;
|
||||
use App\Cqs\Actions\Recipes\ForceDelete\ForceDeleteRecipe;
|
||||
use App\Cqs\Actions\Recipes\ForceDelete\ForceDeleteRecipeInput;
|
||||
use App\Cqs\Actions\Recipes\Restore\RestoreRecipe;
|
||||
|
|
@ -156,13 +158,22 @@ class RecipeController extends BackendController
|
|||
};
|
||||
}
|
||||
|
||||
public function duplicate(RecipeDto $recipe, GetProductsSummariesQuery $getProductsSummaries): Response
|
||||
public function duplicate(RecipeDto $recipe, DuplicateRecipe $duplicateRecipe): RedirectResponse
|
||||
{
|
||||
$this->authorize('duplicate', $recipe);
|
||||
|
||||
$model = Recipe::withTrashed()->findOrFail($recipe->id);
|
||||
$result = $this->executor->execute($duplicateRecipe, new DuplicateRecipeInput($recipe->getId()));
|
||||
|
||||
return $this->create($model->replicate(), $getProductsSummaries);
|
||||
return match (true) {
|
||||
$result instanceof RecipeId => redirect()->route('back.recipes.edit', $result)
|
||||
->with('success', trans('back.has_been_duplicated', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.recipe', 1)),
|
||||
])),
|
||||
default => redirect()->back()
|
||||
->with('error', trans('back.cannot_be_duplicated', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.recipe', 1)),
|
||||
])),
|
||||
};
|
||||
}
|
||||
|
||||
public function restore(string $id, RestoreRecipe $restoreRecipe): RedirectResponse
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ class StoreProductRequest extends FormRequest
|
|||
category: $this->enum('category', ProductCategory::class, ProductCategory::HARD_BOILED_EGGS),
|
||||
technology: $this->enum('technology', Technology::class, Technology::FRESH),
|
||||
isEgalim: $this->boolean('is_egalim'),
|
||||
isPublished: $this->boolean('is_published'),
|
||||
breedingMethods: array_map(
|
||||
fn ($method) => BreedingMethod::from(
|
||||
$this->mixedToString($method)
|
||||
|
|
@ -147,6 +148,7 @@ class StoreProductRequest extends FormRequest
|
|||
'category' => ['required', new Enum(ProductCategory::class)],
|
||||
'technology' => ['required', new Enum(Technology::class)],
|
||||
'is_egalim' => ['boolean'],
|
||||
'is_published' => ['boolean'],
|
||||
'breeding_methods' => ['required', 'array'],
|
||||
'breeding_methods.*' => ['required', new Enum(BreedingMethod::class)],
|
||||
'businesses' => ['required', 'array'],
|
||||
|
|
@ -197,6 +199,7 @@ class StoreProductRequest extends FormRequest
|
|||
'category' => trans('validation.attributes.category'),
|
||||
'technology' => trans('validation.attributes.technology'),
|
||||
'is_egalim' => trans('validation.attributes.is_egalim'),
|
||||
'is_published' => trans('validation.attributes.is_published'),
|
||||
'breeding_methods' => trans('validation.attributes.breeding_methods'),
|
||||
'breeding_methods.*' => trans('validation.attributes.breeding_methods'),
|
||||
'businesses' => trans('validation.attributes.businesses'),
|
||||
|
|
|
|||
|
|
@ -26,24 +26,8 @@ class UpdateProductRequest extends StoreProductRequest
|
|||
]);
|
||||
}
|
||||
|
||||
$existingPicture = $product->picture !== null ? new StorageFilePath($product->picture) : null;
|
||||
$existingPdf = $product->pdf !== null ? new StorageFilePath($product->pdf) : null;
|
||||
|
||||
$picture = null;
|
||||
if ($this->hasFile('picture')) {
|
||||
$picture = $this->storeFile($this->file('picture'));
|
||||
} elseif ($existingPicture !== null) {
|
||||
$picture = $existingPicture;
|
||||
}
|
||||
|
||||
$pdf = null;
|
||||
if ($this->hasFile('pdf')) {
|
||||
$pdf = $this->storeFile($this->file('pdf'));
|
||||
} elseif ($this->exists('pdf') && $this->input('pdf') === null) {
|
||||
$pdf = null;
|
||||
} elseif ($existingPdf !== null) {
|
||||
$pdf = $existingPdf;
|
||||
}
|
||||
$picture = $this->resolvePicture($product->picture);
|
||||
$pdf = $this->resolvePdf($product->pdf);
|
||||
|
||||
return new UpdateProductInput(
|
||||
id: $product->getId(),
|
||||
|
|
@ -53,6 +37,7 @@ class UpdateProductRequest extends StoreProductRequest
|
|||
category: $this->enum('category', ProductCategory::class, ProductCategory::HARD_BOILED_EGGS),
|
||||
technology: $this->enum('technology', Technology::class, Technology::FRESH),
|
||||
isEgalim: $this->boolean('is_egalim'),
|
||||
isPublished: $this->boolean('is_published'),
|
||||
breedingMethods: array_map(
|
||||
fn ($method) => BreedingMethod::from(
|
||||
$this->mixedToString($method)
|
||||
|
|
@ -108,4 +93,26 @@ class UpdateProductRequest extends StoreProductRequest
|
|||
],
|
||||
]);
|
||||
}
|
||||
|
||||
private function resolvePicture(?string $existingPicture): ?StorageFilePath
|
||||
{
|
||||
if ($this->hasFile('picture')) {
|
||||
return $this->storeFile($this->file('picture'));
|
||||
}
|
||||
|
||||
return $existingPicture !== null ? new StorageFilePath($existingPicture) : null;
|
||||
}
|
||||
|
||||
private function resolvePdf(?string $existingPdf): ?StorageFilePath
|
||||
{
|
||||
if ($this->hasFile('pdf')) {
|
||||
return $this->storeFile($this->file('pdf'));
|
||||
}
|
||||
|
||||
if ($this->exists('pdf') && $this->input('pdf') === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $existingPdf !== null ? new StorageFilePath($existingPdf) : null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ class StoreRecipeRequest extends FormRequest
|
|||
name: $this->string('name')->trim()->value(),
|
||||
seoTitle: $this->string('seo_title')->trim()->value(),
|
||||
seoDescription: $this->string('seo_description')->trim()->value(),
|
||||
isPublished: $this->boolean('is_published'),
|
||||
productCategory: $this->enum('product_category', ProductCategory::class, ProductCategory::HARD_BOILED_EGGS),
|
||||
consomptionTime: $this->enum('consomption_time', ConsumptionTime::class, ConsumptionTime::BREAK_FAST_BRUNCH),
|
||||
inspiration: $this->enum('inspiration', Inspiration::class, Inspiration::FRENCH_COOKING),
|
||||
|
|
@ -102,6 +103,7 @@ class StoreRecipeRequest extends FormRequest
|
|||
'name' => ['required', 'string', 'min:3', 'max:255'],
|
||||
'seo_title' => ['required', 'string', 'between:45,70'],
|
||||
'seo_description' => ['required', 'string', 'between:50,160'],
|
||||
'is_published' => ['boolean'],
|
||||
'product_category' => ['required', new Enum(ProductCategory::class)],
|
||||
'consomption_time' => ['required', new Enum(ConsumptionTime::class)],
|
||||
'inspiration' => ['required', new Enum(Inspiration::class)],
|
||||
|
|
@ -139,6 +141,7 @@ class StoreRecipeRequest extends FormRequest
|
|||
'name' => trans('validation.attributes.name'),
|
||||
'seo_title' => trans('validation.attributes.seo_title'),
|
||||
'seo_description' => trans('validation.attributes.seo_description'),
|
||||
'is_published' => trans('validation.attributes.is_published'),
|
||||
'product_category' => trans('validation.attributes.product_category'),
|
||||
'consomption_time' => trans('validation.attributes.consomption_time'),
|
||||
'inspiration' => trans('validation.attributes.inspiration'),
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ class UpdateRecipeRequest extends StoreRecipeRequest
|
|||
name: $this->string('name')->trim()->value(),
|
||||
seoTitle: $this->string('seo_title')->trim()->value(),
|
||||
seoDescription: $this->string('seo_description')->trim()->value(),
|
||||
isPublished: $this->boolean('is_published'),
|
||||
productCategory: $this->enum('product_category', ProductCategory::class, ProductCategory::HARD_BOILED_EGGS),
|
||||
consomptionTime: $this->enum('consomption_time', ConsumptionTime::class, ConsumptionTime::BREAK_FAST_BRUNCH),
|
||||
inspiration: $this->enum('inspiration', Inspiration::class, Inspiration::FRENCH_COOKING),
|
||||
|
|
|
|||
|
|
@ -44,6 +44,6 @@ final readonly class PublicS3Disk
|
|||
($prefix !== '' ? "{$prefix}/{$trimmedPath}" : $trimmedPath)
|
||||
);
|
||||
|
||||
return $this->adapter->publicUrl($fullPath);
|
||||
return $this->adapter->url($fullPath);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@ use Uwil\LaravelBackend\Traits\Models\HasUwilImages;
|
|||
* @property \Illuminate\Support\Carbon|null $deleted_at
|
||||
* @property \Illuminate\Support\Carbon|null $created_at
|
||||
* @property \Illuminate\Support\Carbon|null $updated_at
|
||||
* @property bool $is_published
|
||||
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Uwil\LaravelBackend\Models\ActivityLog> $activityLogs
|
||||
* @property-read array $translatable_columns_from
|
||||
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Recipe> $recipes
|
||||
|
|
@ -100,6 +101,7 @@ class Product extends Model implements TranslatableModel
|
|||
'category',
|
||||
'technology',
|
||||
'is_egalim',
|
||||
'is_published',
|
||||
'breeding_methods',
|
||||
'businesses',
|
||||
'formats',
|
||||
|
|
@ -115,6 +117,7 @@ class Product extends Model implements TranslatableModel
|
|||
|
||||
protected $casts = [
|
||||
'is_egalim' => 'boolean',
|
||||
'is_published' => 'boolean',
|
||||
'category' => ProductCategory::class,
|
||||
'technology' => Technology::class,
|
||||
'breeding_methods' => AsEnumCollection::class . ':' . BreedingMethod::class,
|
||||
|
|
|
|||
|
|
@ -51,6 +51,7 @@ use Uwil\LaravelBackend\Traits\Models\HasUwilImages;
|
|||
* @property \Illuminate\Support\Carbon|null $deleted_at
|
||||
* @property \Illuminate\Support\Carbon|null $created_at
|
||||
* @property \Illuminate\Support\Carbon|null $updated_at
|
||||
* @property bool $is_published
|
||||
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Uwil\LaravelBackend\Models\ActivityLog> $activityLogs
|
||||
* @property-read array $translatable_columns_from
|
||||
* @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Product> $products
|
||||
|
|
@ -91,6 +92,7 @@ class Recipe extends Model implements TranslatableModel
|
|||
'picture_alt',
|
||||
'picture_title',
|
||||
'name',
|
||||
'is_published',
|
||||
'product_category',
|
||||
'consomption_time',
|
||||
'inspiration',
|
||||
|
|
@ -103,6 +105,7 @@ class Recipe extends Model implements TranslatableModel
|
|||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_published' => 'boolean',
|
||||
'product_category' => ProductCategory::class,
|
||||
'consomption_time' => ConsumptionTime::class,
|
||||
'inspiration' => Inspiration::class,
|
||||
|
|
|
|||
|
|
@ -39,7 +39,14 @@ class RouteServiceProvider extends ServiceProvider
|
|||
? new FindProductByIdInput(Uuid::fromString($value), includeTrashed: $this->isBackRequest())
|
||||
: new FindProductBySlugInput($value, includeTrashed: $this->isBackRequest());
|
||||
|
||||
return $executor->execute($findProductQuery, $input) ?? abort(404);
|
||||
/** @var ProductDto $product */
|
||||
$product = $executor->execute($findProductQuery, $input) ?? abort(404);
|
||||
|
||||
if (! $this->isBackRequest() && ! $product->isPublished) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
return $product;
|
||||
}
|
||||
|
||||
private function resolveRecipe(string $value): RecipeDto
|
||||
|
|
@ -51,7 +58,14 @@ class RouteServiceProvider extends ServiceProvider
|
|||
? new FindRecipeByIdInput(Uuid::fromString($value), includeTrashed: $this->isBackRequest())
|
||||
: new FindRecipeBySlugInput($value, includeTrashed: $this->isBackRequest());
|
||||
|
||||
return $executor->execute($findRecipeQuery, $input) ?? abort(404);
|
||||
/** @var RecipeDto $recipe */
|
||||
$recipe = $executor->execute($findRecipeQuery, $input) ?? abort(404);
|
||||
|
||||
if (! $this->isBackRequest() && ! $recipe->isPublished) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
return $recipe;
|
||||
}
|
||||
|
||||
private function isBackRequest(): bool
|
||||
|
|
|
|||
|
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class () extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('products', function (Blueprint $table) {
|
||||
$table->boolean('is_published')->default(true)->index();
|
||||
});
|
||||
|
||||
Schema::table('recipes', function (Blueprint $table) {
|
||||
$table->boolean('is_published')->default(true)->index();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('products', function (Blueprint $table) {
|
||||
$table->dropIndex(['is_published']);
|
||||
$table->dropColumn('is_published');
|
||||
});
|
||||
|
||||
Schema::table('recipes', function (Blueprint $table) {
|
||||
$table->dropIndex(['is_published']);
|
||||
$table->dropColumn('is_published');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -28,6 +28,7 @@ readonly class Product implements Entity
|
|||
public ProductCategory $category,
|
||||
public Technology $technology,
|
||||
public bool $isEgalim,
|
||||
public bool $isPublished,
|
||||
public array $breedingMethods,
|
||||
public array $businesses,
|
||||
public string $detailsAndAdvantages,
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ readonly class Recipe implements Entity
|
|||
public readonly RecipeId $id,
|
||||
public string $name,
|
||||
public string $slug,
|
||||
public bool $isPublished,
|
||||
public ?string $picture,
|
||||
public ?string $seoTitle,
|
||||
public ?string $seoDescription,
|
||||
|
|
|
|||
|
|
@ -3,5 +3,8 @@
|
|||
declare(strict_types=1);
|
||||
|
||||
return [
|
||||
// "dashboard" => "Tableau de bord",
|
||||
'has_been_duplicated' => ':model has been duplicated',
|
||||
'cannot_be_duplicated' => ':model cannot be duplicated',
|
||||
'published' => 'Published',
|
||||
'draft' => 'Draft',
|
||||
];
|
||||
|
|
|
|||
|
|
@ -213,6 +213,7 @@ return [
|
|||
'is_subscribed' => 'is subscribed',
|
||||
'is_visible' => 'is visible',
|
||||
'is_winner' => 'is winner',
|
||||
'is_published' => 'published',
|
||||
'items' => 'items',
|
||||
'key' => 'key',
|
||||
'last_name' => 'last name',
|
||||
|
|
|
|||
|
|
@ -3,5 +3,8 @@
|
|||
declare(strict_types=1);
|
||||
|
||||
return [
|
||||
// "dashboard" => "Tableau de bord",
|
||||
'has_been_duplicated' => ':model a été dupliqué',
|
||||
'cannot_be_duplicated' => ':model ne peut être dupliqué',
|
||||
'published' => 'Publié',
|
||||
'draft' => 'Brouillon',
|
||||
];
|
||||
|
|
|
|||
|
|
@ -224,6 +224,7 @@ return [
|
|||
'inspiration' => 'inspiration',
|
||||
'is_audience_winner' => 'est le gagnant du public',
|
||||
'is_egalim' => 'EGalim',
|
||||
'is_published' => 'publié',
|
||||
'is_hidden' => 'est caché',
|
||||
'is_subscribed' => 'est abonné',
|
||||
'is_visible' => 'est visible',
|
||||
|
|
|
|||
|
|
@ -13,7 +13,6 @@ import {
|
|||
ZoomOutIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type Dispatch,
|
||||
|
|
@ -25,7 +24,6 @@ import { type FileWithPath } from "react-dropzone";
|
|||
import ReactCrop, { type Crop, type PixelCrop } from "react-image-crop";
|
||||
import "react-image-crop/dist/ReactCrop.css";
|
||||
|
||||
import type { ConfigBackend } from "@/back/types/global";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Collapsible,
|
||||
|
|
@ -87,18 +85,14 @@ export default function ImageCropper({
|
|||
reset,
|
||||
setIsReset,
|
||||
isReset,
|
||||
url,
|
||||
finalFileName,
|
||||
}: Readonly<ImageCropperProps>) {
|
||||
const { routes } = usePage().props.configBackend as ConfigBackend;
|
||||
const { errors } = usePage().props;
|
||||
|
||||
const aspect = 1;
|
||||
const { isDesktop } = useDeviceType();
|
||||
const imgRef = useRef<HTMLImageElement | null>(null);
|
||||
|
||||
const isDuplicating = route().current(`${routes.name}*.duplicate`);
|
||||
|
||||
// Zone of the crop in %.
|
||||
const [cropZone, setCropZone] = useState<Crop>();
|
||||
const [croppedImage, setCroppedImage] = useState<string>("");
|
||||
|
|
@ -231,34 +225,6 @@ export default function ImageCropper({
|
|||
return canvas.toDataURL("image/png");
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate base64 from an url.
|
||||
* @param targetUrl string
|
||||
* @param callback (base64: string | ArrayBuffer | null) => void
|
||||
* @param errorCallback (error: string) => void
|
||||
*/
|
||||
function urlToBase64(
|
||||
targetUrl: string,
|
||||
|
||||
callback: (base64: string | ArrayBuffer | null) => void,
|
||||
|
||||
errorCallback?: (error: string) => void,
|
||||
): void {
|
||||
fetch(targetUrl)
|
||||
.then((response) => response.blob())
|
||||
.then((blob) => {
|
||||
const reader = new FileReader();
|
||||
|
||||
reader.onloadend = () => {
|
||||
callback(reader.result);
|
||||
};
|
||||
reader.readAsDataURL(blob);
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (errorCallback) errorCallback(String(error));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate file from the base64.
|
||||
* @param dataUrl base64 string
|
||||
|
|
@ -302,28 +268,6 @@ export default function ImageCropper({
|
|||
setIsDragging(false);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!value || !isDuplicating) return;
|
||||
const rawPath = typeof value === "object" ? value?.name : value;
|
||||
if (!rawPath) return;
|
||||
const pathFileBase = /^https?:\/\//i.test(rawPath)
|
||||
? rawPath
|
||||
: `${url}/${rawPath.replace(/^\/+/, "")}`;
|
||||
urlToBase64(
|
||||
pathFileBase,
|
||||
(base64) => {
|
||||
if (typeof base64 === "string") {
|
||||
const file = base64ToFile(base64);
|
||||
setData(name, file);
|
||||
}
|
||||
},
|
||||
(err) => {
|
||||
console.error(err);
|
||||
},
|
||||
);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Crop the image with all options.
|
||||
* @return void
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { MoreHorizontalIcon } from "lucide-react";
|
|||
import {
|
||||
useState,
|
||||
type Dispatch,
|
||||
type FormEvent,
|
||||
type ReactNode,
|
||||
type SetStateAction,
|
||||
type SubmitEvent,
|
||||
|
|
@ -352,6 +353,56 @@ function PostAction({
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Button for DUPLICATE POST action.
|
||||
* @param action ViewsType[number]
|
||||
* @param modelRoute string
|
||||
* @param model ActionableModel
|
||||
* @param routes ConfigBackend["routes"]
|
||||
* @param setOpen Dispatch<SetStateAction<boolean>>
|
||||
* @returns Element
|
||||
*/
|
||||
function DuplicateAction({
|
||||
action,
|
||||
modelRoute,
|
||||
model,
|
||||
routes,
|
||||
setOpen,
|
||||
}: Readonly<{
|
||||
action: ViewsType[number];
|
||||
modelRoute: string;
|
||||
model: ActionableModel;
|
||||
routes: ConfigBackend["routes"];
|
||||
setOpen: Dispatch<SetStateAction<boolean>>;
|
||||
}>) {
|
||||
const { post, processing } = useForm();
|
||||
const actionLabelTrans = str(
|
||||
trans(`uwil-backend::crud.actions.${action.label}`),
|
||||
)
|
||||
.ucFirst()
|
||||
.value();
|
||||
|
||||
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setOpen(false);
|
||||
post(route(`${routes.name}${modelRoute}.${action.value}`, model.id));
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="w-full">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="ghost"
|
||||
className="w-full"
|
||||
disabled={processing}
|
||||
>
|
||||
<action.icon />
|
||||
{actionLabelTrans}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all action buttons.
|
||||
* @returns Element[]
|
||||
|
|
@ -379,28 +430,44 @@ const AllBtnActions = ({
|
|||
]);
|
||||
|
||||
return allowedActions.map((action) => {
|
||||
const isDuplicateAction = action.value === Views.DUPLICATION.value;
|
||||
const isPostAction = postActionValues.has(action.value);
|
||||
const showSeparator =
|
||||
inDialog && isPostAction && action.value !== allowedActions[0].value;
|
||||
|
||||
const content = isPostAction ? (
|
||||
<>
|
||||
{showSeparator && <DropdownMenuSeparator />}
|
||||
<PostAction
|
||||
let content: ReactNode;
|
||||
if (isDuplicateAction) {
|
||||
content = (
|
||||
<DuplicateAction
|
||||
action={action}
|
||||
model={model}
|
||||
modelRoute={modelRoute}
|
||||
routes={routes}
|
||||
setOpen={setOpen}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<GetAction
|
||||
action={action}
|
||||
model={model}
|
||||
modelRoute={modelRoute}
|
||||
routes={routes}
|
||||
/>
|
||||
);
|
||||
);
|
||||
} else if (isPostAction) {
|
||||
content = (
|
||||
<>
|
||||
{showSeparator && <DropdownMenuSeparator />}
|
||||
<PostAction
|
||||
action={action}
|
||||
model={model}
|
||||
modelRoute={modelRoute}
|
||||
setOpen={setOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
content = (
|
||||
<GetAction
|
||||
action={action}
|
||||
model={model}
|
||||
modelRoute={modelRoute}
|
||||
routes={routes}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={`${action.value}-${action.label}`} className="w-full">
|
||||
|
|
|
|||
|
|
@ -7,11 +7,7 @@ import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout";
|
|||
import { Actions, Methods } from "@/back/lib/enums";
|
||||
import Form from "@/back/Pages/Products/Form";
|
||||
import { SingleResource } from "@/back/types/global";
|
||||
import {
|
||||
RawProductModel,
|
||||
validateAsProductModel,
|
||||
validateAsRawProductModel,
|
||||
} from "@/back/types/products";
|
||||
import { RawProductModel, validateAsProductModel } from "@/back/types/products";
|
||||
import usePermissions from "@/hooks/use-permissions";
|
||||
import trans from "@/hooks/use-translations";
|
||||
|
||||
|
|
@ -30,11 +26,7 @@ export default function Create({
|
|||
? data.data.length > 0
|
||||
: Object.keys(data.data).length > 0);
|
||||
if (hasData) {
|
||||
if (route().current(`back.products.duplicate`)) {
|
||||
product = validateAsRawProductModel(data.data);
|
||||
} else {
|
||||
product = validateAsProductModel(data.data);
|
||||
}
|
||||
product = validateAsProductModel(data.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Zod validation failed, falling back to empty model.", error);
|
||||
|
|
@ -42,18 +34,13 @@ export default function Create({
|
|||
|
||||
// Translations.
|
||||
const transBackToList = trans("uwil-backend::back.crud_back_to_list");
|
||||
const transTitle = trans(
|
||||
route().current(`back.products.duplicate`)
|
||||
? "uwil-backend::crud.helpers.duplication_model"
|
||||
: "uwil-backend::crud.helpers.creation_model",
|
||||
{
|
||||
params: {
|
||||
model: trans(`models.classes.product`, {
|
||||
choice: 1,
|
||||
}),
|
||||
},
|
||||
const transTitle = trans("uwil-backend::crud.helpers.creation_model", {
|
||||
params: {
|
||||
model: trans(`models.classes.product`, {
|
||||
choice: 1,
|
||||
}),
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const beforeNode = () => {
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ interface FormData {
|
|||
category: string;
|
||||
technology: string;
|
||||
is_egalim: boolean;
|
||||
is_published: boolean;
|
||||
breeding_methods: string[];
|
||||
businesses: string[];
|
||||
formats: string[];
|
||||
|
|
@ -108,6 +109,7 @@ export default function Form({
|
|||
category: model?.category ?? "",
|
||||
technology: model?.technology ?? "",
|
||||
is_egalim: model?.is_egalim ?? false,
|
||||
is_published: model?.is_published ?? true,
|
||||
breeding_methods: Array.from(new Set(model?.breeding_methods ?? [])),
|
||||
businesses: Array.from(new Set(model?.businesses ?? [])),
|
||||
formats: Array.from(new Set(model?.formats ?? [])),
|
||||
|
|
@ -206,6 +208,13 @@ export default function Form({
|
|||
checked={data.is_egalim}
|
||||
setData={setData}
|
||||
/>
|
||||
|
||||
<SimpleSwitch
|
||||
name="is_published"
|
||||
label="Publié"
|
||||
checked={data.is_published}
|
||||
setData={setData}
|
||||
/>
|
||||
</FieldsetWrapper>
|
||||
|
||||
{/* Relations (MultiSelects) */}
|
||||
|
|
|
|||
|
|
@ -162,6 +162,42 @@ const getColumns = (
|
|||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "is_published",
|
||||
header: ({ column }: { column: { id: string } }) => (
|
||||
<DataTableFilterButton
|
||||
label={str(trans(`validation.attributes.${column.id}`))
|
||||
.ucFirst()
|
||||
.value()}
|
||||
field={column.id}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }: { row: Row<DefaultModel & Record<string, unknown>> }) => (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`border-0 ${
|
||||
row.getValue("is_published")
|
||||
? "bg-green-200 dark:bg-green-900 text-green-900 dark:text-green-100"
|
||||
: "bg-amber-200 dark:bg-amber-900 text-amber-900 dark:text-amber-100"
|
||||
}`}
|
||||
>
|
||||
{row.getValue("is_published") ? (
|
||||
<CheckIcon size={15} className="mr-1" />
|
||||
) : (
|
||||
<XIcon size={15} className="mr-1" />
|
||||
)}
|
||||
{str(
|
||||
trans(
|
||||
row.getValue("is_published")
|
||||
? "back.published"
|
||||
: "back.draft",
|
||||
),
|
||||
)
|
||||
.ucFirst()
|
||||
.value()}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "updated_at",
|
||||
header: ({ column }: { column: { id: string } }) => (
|
||||
|
|
|
|||
|
|
@ -5,11 +5,7 @@ import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout";
|
|||
import { Actions, Methods } from "@/back/lib/enums";
|
||||
import Form from "@/back/Pages/Recipes/Form";
|
||||
import { SingleResource } from "@/back/types/global";
|
||||
import {
|
||||
RawRecipeModel,
|
||||
validateAsRawRecipeModel,
|
||||
validateAsRecipeModel,
|
||||
} from "@/back/types/recipes";
|
||||
import { RawRecipeModel, validateAsRecipeModel } from "@/back/types/recipes";
|
||||
import usePermissions from "@/hooks/use-permissions";
|
||||
import trans, { UseTransOptions } from "@/hooks/use-translations";
|
||||
import { ArrowLeftIcon } from "lucide-react";
|
||||
|
|
@ -29,29 +25,20 @@ export default function Create({
|
|||
? data.data.length > 0
|
||||
: Object.keys(data.data).length > 0);
|
||||
if (hasData) {
|
||||
if (route().current(`back.recipes.duplicate`)) {
|
||||
recipe = validateAsRawRecipeModel(data.data);
|
||||
} else {
|
||||
recipe = validateAsRecipeModel(data.data);
|
||||
}
|
||||
recipe = validateAsRecipeModel(data.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Zod validation failed, falling back to empty model.", error);
|
||||
}
|
||||
|
||||
const transBackToList = trans("uwil-backend::back.crud_back_to_list");
|
||||
const title = trans(
|
||||
route().current(`back.recipes.duplicate`)
|
||||
? "uwil-backend::crud.helpers.duplication_model"
|
||||
: "uwil-backend::crud.helpers.creation_model",
|
||||
{
|
||||
params: {
|
||||
model: trans(`models.classes.recipe`, {
|
||||
choice: 1,
|
||||
}),
|
||||
},
|
||||
} as UseTransOptions,
|
||||
);
|
||||
const title = trans("uwil-backend::crud.helpers.creation_model", {
|
||||
params: {
|
||||
model: trans(`models.classes.recipe`, {
|
||||
choice: 1,
|
||||
}),
|
||||
},
|
||||
} as UseTransOptions);
|
||||
|
||||
const beforeNode = () => {
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import FieldsetWrapper from "@/back/Components/FieldsetWrapper";
|
|||
import InputError from "@/back/Components/InputError";
|
||||
import EnumSelect from "@/back/Components/Inputs/EnumSelect";
|
||||
import SimpleString from "@/back/Components/Inputs/SimpleString";
|
||||
import SimpleSwitch from "@/back/Components/Inputs/SimpleSwitch";
|
||||
import SimpleWysiwyg from "@/back/Components/Inputs/Wysiwyg/SimpleWysiwyg";
|
||||
import SubmitButton from "@/back/Components/SubmitButton";
|
||||
import useCrudSubmit from "@/back/hooks/use-crud-submit";
|
||||
|
|
@ -25,6 +26,7 @@ interface FormData {
|
|||
slug: string;
|
||||
seo_title: string;
|
||||
seo_description: string;
|
||||
is_published: boolean;
|
||||
product_category: string;
|
||||
consomption_time: string;
|
||||
inspiration: string;
|
||||
|
|
@ -75,6 +77,7 @@ export default function Form({
|
|||
slug: model?.slug ?? "",
|
||||
seo_title: model?.seo_title ?? "",
|
||||
seo_description: model?.seo_description ?? "",
|
||||
is_published: model?.is_published ?? true,
|
||||
product_category: model?.product_category ?? "",
|
||||
consomption_time: model?.consomption_time ?? "",
|
||||
inspiration: model?.inspiration ?? "",
|
||||
|
|
@ -196,6 +199,13 @@ export default function Form({
|
|||
setData={setData}
|
||||
parentErrors={formErrors}
|
||||
/>
|
||||
|
||||
<SimpleSwitch
|
||||
name="is_published"
|
||||
label="Publié"
|
||||
checked={data.is_published}
|
||||
setData={setData}
|
||||
/>
|
||||
</FieldsetWrapper>
|
||||
|
||||
{/* Textes Longs */}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,12 @@
|
|||
// * Packages
|
||||
import { Row } from "@tanstack/react-table";
|
||||
import { ArchiveIcon, ArrowLeftIcon, PlusIcon } from "lucide-react";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
ArrowLeftIcon,
|
||||
CheckIcon,
|
||||
PlusIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { route } from "ziggy-js";
|
||||
// * Components shadcn
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
|
@ -190,6 +196,42 @@ const getColumns = (
|
|||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
accessorKey: "is_published",
|
||||
header: ({ column }: { column: { id: string } }) => (
|
||||
<DataTableFilterButton
|
||||
label={str(trans(`validation.attributes.${column.id}`))
|
||||
.ucFirst()
|
||||
.value()}
|
||||
field={column.id}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }: { row: Row<DefaultModel & Record<string, unknown>> }) => (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={`border-0 ${
|
||||
row.getValue("is_published")
|
||||
? "bg-green-200 dark:bg-green-900 text-green-900 dark:text-green-100"
|
||||
: "bg-amber-200 dark:bg-amber-900 text-amber-900 dark:text-amber-100"
|
||||
}`}
|
||||
>
|
||||
{row.getValue("is_published") ? (
|
||||
<CheckIcon size={15} className="mr-1" />
|
||||
) : (
|
||||
<XIcon size={15} className="mr-1" />
|
||||
)}
|
||||
{str(
|
||||
trans(
|
||||
row.getValue("is_published")
|
||||
? "back.published"
|
||||
: "back.draft",
|
||||
),
|
||||
)
|
||||
.ucFirst()
|
||||
.value()}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "updated_at",
|
||||
header: ({ column }: { column: { id: string } }) => (
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ export interface RawProductModel extends ModelWithPolicies {
|
|||
category: ProductCategory;
|
||||
technology: Technology;
|
||||
is_egalim: boolean;
|
||||
is_published: boolean;
|
||||
breeding_methods: BreedingMethod[];
|
||||
businesses: Business[];
|
||||
formats: ProductFormat[];
|
||||
|
|
@ -91,6 +92,7 @@ export const rawProductModelSchema = zod.object({
|
|||
category: zod.enum(ProductCategory),
|
||||
technology: zod.enum(Technology),
|
||||
is_egalim: zod.boolean(),
|
||||
is_published: zod.boolean().default(true),
|
||||
breeding_methods: zod.array(zod.enum(BreedingMethod)),
|
||||
businesses: zod.array(zod.enum(Business)),
|
||||
formats: zod.array(zod.enum(ProductFormat)),
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ export interface RawRecipeModel extends ModelWithPolicies {
|
|||
picture_title: string;
|
||||
name: string;
|
||||
slug: Slug;
|
||||
is_published: boolean;
|
||||
product_category: ProductCategory;
|
||||
consomption_time: ConsumptionTime;
|
||||
inspiration: Inspiration;
|
||||
|
|
@ -47,6 +48,7 @@ export const rawRecipeModelSchema = zod.object({
|
|||
picture_title: zod.string(),
|
||||
name: zod.string(),
|
||||
slug: zod.string().transform((v) => v as Slug),
|
||||
is_published: zod.boolean().default(true),
|
||||
product_category: zod.enum(ProductCategory),
|
||||
consomption_time: zod.enum(ConsumptionTime),
|
||||
inspiration: zod.enum(Inspiration),
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ export interface Product {
|
|||
category: ProductCategory;
|
||||
technology: Technology;
|
||||
is_egalim: boolean;
|
||||
is_published: boolean;
|
||||
breeding_methods: BreedingMethod[];
|
||||
businesses: Business[];
|
||||
details_and_advantages: string;
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ export type Recipe = {
|
|||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
is_published: boolean;
|
||||
picture: string | null;
|
||||
picture_alt?: string | null;
|
||||
picture_title?: string | null;
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
|
|||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::get('recipes/trash', [RecipeController::class, 'index'])->name('recipes.trash');
|
||||
Route::get('recipes/{recipe}/duplicate', [RecipeController::class, 'duplicate'])->name('recipes.duplicate');
|
||||
Route::post('recipes/{recipe}/duplicate', [RecipeController::class, 'duplicate'])->name('recipes.duplicate');
|
||||
Route::patch('recipes/{id}/restore', [RecipeController::class, 'restore'])->name('recipes.restore');
|
||||
Route::delete('recipes/{id}/forceDestroy', [RecipeController::class, 'forceDestroy'])->name('recipes.forceDestroy');
|
||||
Route::resource('recipes', RecipeController::class)
|
||||
|
|
@ -16,7 +16,7 @@ Route::resource('recipes', RecipeController::class)
|
|||
->middleware(['htmlsanitize:description,details,ingredients_list,preparation_steps,tips_and_advices', HandlePrecognitiveRequests::class]);
|
||||
|
||||
Route::get('products/trash', [ProductController::class, 'index'])->name('products.trash');
|
||||
Route::get('products/{product}/duplicate', [ProductController::class, 'duplicate'])->name('products.duplicate');
|
||||
Route::post('products/{product}/duplicate', [ProductController::class, 'duplicate'])->name('products.duplicate');
|
||||
Route::patch('products/{id}/restore', [ProductController::class, 'restore'])->name('products.restore');
|
||||
Route::delete('products/{id}/forceDestroy', [ProductController::class, 'forceDestroy'])->name('products.forceDestroy');
|
||||
Route::resource('products', ProductController::class)
|
||||
|
|
|
|||
|
|
@ -38,11 +38,6 @@ Breadcrumbs::for('back.products.edit', function (Generator $trail) {
|
|||
);
|
||||
});
|
||||
|
||||
Breadcrumbs::for('back.products.duplicate', function (Generator $trail) {
|
||||
$trail->parent('back.products.index');
|
||||
$trail->push(Str::ucfirst(trans('uwil-backend::crud.actions.duplicate')));
|
||||
});
|
||||
|
||||
Breadcrumbs::for('back.products.trash', function (Generator $trail) {
|
||||
$trail->parent('back.products.index');
|
||||
$trail->push(Str::ucfirst(trans('uwil-backend::back.archives')));
|
||||
|
|
@ -78,11 +73,6 @@ Breadcrumbs::for('back.recipes.edit', function (Generator $trail) {
|
|||
);
|
||||
});
|
||||
|
||||
Breadcrumbs::for('back.recipes.duplicate', function (Generator $trail) {
|
||||
$trail->parent('back.recipes.index');
|
||||
$trail->push(Str::ucfirst(trans('uwil-backend::crud.actions.duplicate')));
|
||||
});
|
||||
|
||||
Breadcrumbs::for('back.recipes.trash', function (Generator $trail) {
|
||||
$trail->parent('back.recipes.index');
|
||||
$trail->push(Str::ucfirst(trans('uwil-backend::back.archives')));
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue