diff --git a/app/Cqs/Actions/Products/Create/CreateProduct.php b/app/Cqs/Actions/Products/Create/CreateProduct.php index 73b1b460..550e9fe2 100644 --- a/app/Cqs/Actions/Products/Create/CreateProduct.php +++ b/app/Cqs/Actions/Products/Create/CreateProduct.php @@ -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, diff --git a/app/Cqs/Actions/Products/Create/CreateProductInput.php b/app/Cqs/Actions/Products/Create/CreateProductInput.php index 399a9b51..df4fbcda 100644 --- a/app/Cqs/Actions/Products/Create/CreateProductInput.php +++ b/app/Cqs/Actions/Products/Create/CreateProductInput.php @@ -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, diff --git a/app/Cqs/Actions/Products/Duplicate/DuplicateProduct.php b/app/Cqs/Actions/Products/Duplicate/DuplicateProduct.php new file mode 100644 index 00000000..33cb2fdb --- /dev/null +++ b/app/Cqs/Actions/Products/Duplicate/DuplicateProduct.php @@ -0,0 +1,112 @@ + + * 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); + } +} diff --git a/app/Cqs/Actions/Products/Duplicate/DuplicateProductInput.php b/app/Cqs/Actions/Products/Duplicate/DuplicateProductInput.php new file mode 100644 index 00000000..4bb42500 --- /dev/null +++ b/app/Cqs/Actions/Products/Duplicate/DuplicateProductInput.php @@ -0,0 +1,16 @@ + $input->category, 'technology' => $input->technology, 'is_egalim' => $input->isEgalim, + 'is_published' => $input->isPublished, 'breeding_methods' => $input->breedingMethods, 'businesses' => $input->businesses, 'formats' => $input->formats, diff --git a/app/Cqs/Actions/Products/Update/UpdateProductInput.php b/app/Cqs/Actions/Products/Update/UpdateProductInput.php index f7c68968..4a58cb29 100644 --- a/app/Cqs/Actions/Products/Update/UpdateProductInput.php +++ b/app/Cqs/Actions/Products/Update/UpdateProductInput.php @@ -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, diff --git a/app/Cqs/Actions/Recipes/Create/CreateRecipe.php b/app/Cqs/Actions/Recipes/Create/CreateRecipe.php index 743ba621..1f87aba2 100644 --- a/app/Cqs/Actions/Recipes/Create/CreateRecipe.php +++ b/app/Cqs/Actions/Recipes/Create/CreateRecipe.php @@ -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, diff --git a/app/Cqs/Actions/Recipes/Create/CreateRecipeInput.php b/app/Cqs/Actions/Recipes/Create/CreateRecipeInput.php index 89c17bce..9c97590c 100644 --- a/app/Cqs/Actions/Recipes/Create/CreateRecipeInput.php +++ b/app/Cqs/Actions/Recipes/Create/CreateRecipeInput.php @@ -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, diff --git a/app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipe.php b/app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipe.php new file mode 100644 index 00000000..7d76b3b3 --- /dev/null +++ b/app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipe.php @@ -0,0 +1,116 @@ + + * 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); + } +} diff --git a/app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipeInput.php b/app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipeInput.php new file mode 100644 index 00000000..96693c25 --- /dev/null +++ b/app/Cqs/Actions/Recipes/Duplicate/DuplicateRecipeInput.php @@ -0,0 +1,16 @@ + $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, diff --git a/app/Cqs/Actions/Recipes/Update/UpdateRecipeInput.php b/app/Cqs/Actions/Recipes/Update/UpdateRecipeInput.php index ceef5aff..574ebfc9 100644 --- a/app/Cqs/Actions/Recipes/Update/UpdateRecipeInput.php +++ b/app/Cqs/Actions/Recipes/Update/UpdateRecipeInput.php @@ -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, diff --git a/app/Cqs/Queries/Products/GetBoPaginatedProductsQuery.php b/app/Cqs/Queries/Products/GetBoPaginatedProductsQuery.php index 6a464f0a..99005595 100644 --- a/app/Cqs/Queries/Products/GetBoPaginatedProductsQuery.php +++ b/app/Cqs/Queries/Products/GetBoPaginatedProductsQuery.php @@ -26,6 +26,7 @@ final readonly class GetBoPaginatedProductsQuery implements Query 'category', 'technology', 'is_egalim', + 'is_published', 'created_at', 'updated_at', ]; diff --git a/app/Cqs/Queries/Products/GetCategoriesProductsQuery.php b/app/Cqs/Queries/Products/GetCategoriesProductsQuery.php index c8c10b65..741f33f8 100644 --- a/app/Cqs/Queries/Products/GetCategoriesProductsQuery.php +++ b/app/Cqs/Queries/Products/GetCategoriesProductsQuery.php @@ -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 + * @return array */ public function __invoke(QueryInput $input): array { diff --git a/app/Cqs/Queries/Recipes/GetBoPaginatedRecipesQuery.php b/app/Cqs/Queries/Recipes/GetBoPaginatedRecipesQuery.php index 4cace00e..e292152f 100644 --- a/app/Cqs/Queries/Recipes/GetBoPaginatedRecipesQuery.php +++ b/app/Cqs/Queries/Recipes/GetBoPaginatedRecipesQuery.php @@ -29,6 +29,7 @@ final readonly class GetBoPaginatedRecipesQuery implements Query 'consomption_time', 'inspiration', 'season', + 'is_published', 'created_at', 'updated_at', ]; diff --git a/app/Cqs/Queries/Recipes/GetFrontRecipesQuery.php b/app/Cqs/Queries/Recipes/GetFrontRecipesQuery.php index fb8b9521..763db381 100644 --- a/app/Cqs/Queries/Recipes/GetFrontRecipesQuery.php +++ b/app/Cqs/Queries/Recipes/GetFrontRecipesQuery.php @@ -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> + * + * phpcs:enable */ final readonly class GetFrontRecipesQuery implements Query { diff --git a/app/Directories/EloquentProductDirectory.php b/app/Directories/EloquentProductDirectory.php index 404aa2a7..9813bab9 100644 --- a/app/Directories/EloquentProductDirectory.php +++ b/app/Directories/EloquentProductDirectory.php @@ -103,6 +103,7 @@ class EloquentProductDirectory implements ProductDirectory $dbQueryCallback = function (Builder $query) use ($category, $breedingMethods, $technologies, $businesses, $isEgalim) { /** @var \Illuminate\Database\Eloquent\Builder $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)) diff --git a/app/Directories/EloquentRecipeDirectory.php b/app/Directories/EloquentRecipeDirectory.php index d13cae7d..0e4ee73d 100644 --- a/app/Directories/EloquentRecipeDirectory.php +++ b/app/Directories/EloquentRecipeDirectory.php @@ -49,7 +49,8 @@ class EloquentRecipeDirectory implements RecipeDirectory ): LengthAwarePaginator { $dbQueryCallback = function (Builder $query) use ($productRanges, $consumptionTimes, $inspirations, $seasons) { /** @var \Illuminate\Database\Eloquent\Builder $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)) diff --git a/app/Dto/ProductDto.php b/app/Dto/ProductDto.php index 9fbb8466..36e63332 100644 --- a/app/Dto/ProductDto.php +++ b/app/Dto/ProductDto.php @@ -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, diff --git a/app/Dto/RecipeDto.php b/app/Dto/RecipeDto.php index df91384a..67c3dafc 100644 --- a/app/Dto/RecipeDto.php +++ b/app/Dto/RecipeDto.php @@ -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, diff --git a/app/Http/Controllers/Back/ProductController.php b/app/Http/Controllers/Back/ProductController.php index d91ae0a4..a81888e8 100644 --- a/app/Http/Controllers/Back/ProductController.php +++ b/app/Http/Controllers/Back/ProductController.php @@ -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 diff --git a/app/Http/Controllers/Back/RecipeController.php b/app/Http/Controllers/Back/RecipeController.php index 071c0a20..ae79da5d 100644 --- a/app/Http/Controllers/Back/RecipeController.php +++ b/app/Http/Controllers/Back/RecipeController.php @@ -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 diff --git a/app/Http/Requests/Back/Products/StoreProductRequest.php b/app/Http/Requests/Back/Products/StoreProductRequest.php index 7b46acff..7d76fa16 100644 --- a/app/Http/Requests/Back/Products/StoreProductRequest.php +++ b/app/Http/Requests/Back/Products/StoreProductRequest.php @@ -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'), diff --git a/app/Http/Requests/Back/Products/UpdateProductRequest.php b/app/Http/Requests/Back/Products/UpdateProductRequest.php index d2705371..77630f32 100644 --- a/app/Http/Requests/Back/Products/UpdateProductRequest.php +++ b/app/Http/Requests/Back/Products/UpdateProductRequest.php @@ -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; + } } diff --git a/app/Http/Requests/Back/Recipes/StoreRecipeRequest.php b/app/Http/Requests/Back/Recipes/StoreRecipeRequest.php index 82953c76..a7d5c115 100644 --- a/app/Http/Requests/Back/Recipes/StoreRecipeRequest.php +++ b/app/Http/Requests/Back/Recipes/StoreRecipeRequest.php @@ -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'), diff --git a/app/Http/Requests/Back/Recipes/UpdateRecipeRequest.php b/app/Http/Requests/Back/Recipes/UpdateRecipeRequest.php index 1fe2188a..50a8e424 100644 --- a/app/Http/Requests/Back/Recipes/UpdateRecipeRequest.php +++ b/app/Http/Requests/Back/Recipes/UpdateRecipeRequest.php @@ -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), diff --git a/app/Lib/PublicS3Disk.php b/app/Lib/PublicS3Disk.php index 037d3f5d..5e7e5a0b 100644 --- a/app/Lib/PublicS3Disk.php +++ b/app/Lib/PublicS3Disk.php @@ -44,6 +44,6 @@ final readonly class PublicS3Disk ($prefix !== '' ? "{$prefix}/{$trimmedPath}" : $trimmedPath) ); - return $this->adapter->publicUrl($fullPath); + return $this->adapter->url($fullPath); } } diff --git a/app/Models/Product.php b/app/Models/Product.php index 57594383..03cef896 100644 --- a/app/Models/Product.php +++ b/app/Models/Product.php @@ -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 $activityLogs * @property-read array $translatable_columns_from * @property-read \Illuminate\Database\Eloquent\Collection $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, diff --git a/app/Models/Recipe.php b/app/Models/Recipe.php index 24a95248..405f0ce7 100644 --- a/app/Models/Recipe.php +++ b/app/Models/Recipe.php @@ -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 $activityLogs * @property-read array $translatable_columns_from * @property-read \Illuminate\Database\Eloquent\Collection $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, diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index 690ec037..72ccdfd0 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -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 diff --git a/database/migrations/2026_11_05_174917_add_is_published_to_products_and_recipes_tables.php b/database/migrations/2026_11_05_174917_add_is_published_to_products_and_recipes_tables.php new file mode 100644 index 00000000..a68fe3eb --- /dev/null +++ b/database/migrations/2026_11_05_174917_add_is_published_to_products_and_recipes_tables.php @@ -0,0 +1,40 @@ +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'); + }); + } +}; diff --git a/domain/Models/Entities/Product.php b/domain/Models/Entities/Product.php index b055c4f4..f1acd5a3 100644 --- a/domain/Models/Entities/Product.php +++ b/domain/Models/Entities/Product.php @@ -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, diff --git a/domain/Models/Entities/Recipe.php b/domain/Models/Entities/Recipe.php index 5ec433bb..f7e0e517 100644 --- a/domain/Models/Entities/Recipe.php +++ b/domain/Models/Entities/Recipe.php @@ -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, diff --git a/lang/en/back.php b/lang/en/back.php index 7570e5eb..e74fe8c8 100644 --- a/lang/en/back.php +++ b/lang/en/back.php @@ -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', ]; diff --git a/lang/en/validation.php b/lang/en/validation.php index 5f6e54b1..81fd2815 100644 --- a/lang/en/validation.php +++ b/lang/en/validation.php @@ -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', diff --git a/lang/fr/back.php b/lang/fr/back.php index 7570e5eb..4840f9a1 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -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', ]; diff --git a/lang/fr/validation.php b/lang/fr/validation.php index a940fb3e..4f612cce 100644 --- a/lang/fr/validation.php +++ b/lang/fr/validation.php @@ -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', diff --git a/resources/ts/back/Components/Inputs/ImageCropper.tsx b/resources/ts/back/Components/Inputs/ImageCropper.tsx index 31eebdf4..e042ff49 100644 --- a/resources/ts/back/Components/Inputs/ImageCropper.tsx +++ b/resources/ts/back/Components/Inputs/ImageCropper.tsx @@ -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) { - const { routes } = usePage().props.configBackend as ConfigBackend; const { errors } = usePage().props; const aspect = 1; const { isDesktop } = useDeviceType(); const imgRef = useRef(null); - const isDuplicating = route().current(`${routes.name}*.duplicate`); - // Zone of the crop in %. const [cropZone, setCropZone] = useState(); const [croppedImage, setCroppedImage] = useState(""); @@ -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 diff --git a/resources/ts/back/Components/ModelActions.tsx b/resources/ts/back/Components/ModelActions.tsx index 97afc1e4..d0377248 100644 --- a/resources/ts/back/Components/ModelActions.tsx +++ b/resources/ts/back/Components/ModelActions.tsx @@ -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> + * @returns Element + */ +function DuplicateAction({ + action, + modelRoute, + model, + routes, + setOpen, +}: Readonly<{ + action: ViewsType[number]; + modelRoute: string; + model: ActionableModel; + routes: ConfigBackend["routes"]; + setOpen: Dispatch>; +}>) { + const { post, processing } = useForm(); + const actionLabelTrans = str( + trans(`uwil-backend::crud.actions.${action.label}`), + ) + .ucFirst() + .value(); + + const handleSubmit = (event: FormEvent) => { + event.preventDefault(); + setOpen(false); + post(route(`${routes.name}${modelRoute}.${action.value}`, model.id)); + }; + + return ( +
+ +
+ ); +} + /** * 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 && } - - - ) : ( - - ); + ); + } else if (isPostAction) { + content = ( + <> + {showSeparator && } + + + ); + } else { + content = ( + + ); + } return (
diff --git a/resources/ts/back/Pages/Products/Create.tsx b/resources/ts/back/Pages/Products/Create.tsx index 468d4daf..5cb31142 100644 --- a/resources/ts/back/Pages/Products/Create.tsx +++ b/resources/ts/back/Pages/Products/Create.tsx @@ -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 ( diff --git a/resources/ts/back/Pages/Products/Form.tsx b/resources/ts/back/Pages/Products/Form.tsx index 59a25a03..520e61db 100644 --- a/resources/ts/back/Pages/Products/Form.tsx +++ b/resources/ts/back/Pages/Products/Form.tsx @@ -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} /> + + {/* Relations (MultiSelects) */} diff --git a/resources/ts/back/Pages/Products/Index.tsx b/resources/ts/back/Pages/Products/Index.tsx index 93e3538e..7cd3d5b1 100644 --- a/resources/ts/back/Pages/Products/Index.tsx +++ b/resources/ts/back/Pages/Products/Index.tsx @@ -162,6 +162,42 @@ const getColumns = ( ), }, + { + accessorKey: "is_published", + header: ({ column }: { column: { id: string } }) => ( + + ), + cell: ({ row }: { row: Row> }) => ( + + {row.getValue("is_published") ? ( + + ) : ( + + )} + {str( + trans( + row.getValue("is_published") + ? "back.published" + : "back.draft", + ), + ) + .ucFirst() + .value()} + + ), + }, { accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( diff --git a/resources/ts/back/Pages/Recipes/Create.tsx b/resources/ts/back/Pages/Recipes/Create.tsx index 5c4a153e..813a46b1 100644 --- a/resources/ts/back/Pages/Recipes/Create.tsx +++ b/resources/ts/back/Pages/Recipes/Create.tsx @@ -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 ( diff --git a/resources/ts/back/Pages/Recipes/Form.tsx b/resources/ts/back/Pages/Recipes/Form.tsx index 6637f33f..5d4b400c 100644 --- a/resources/ts/back/Pages/Recipes/Form.tsx +++ b/resources/ts/back/Pages/Recipes/Form.tsx @@ -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} /> + + {/* Textes Longs */} diff --git a/resources/ts/back/Pages/Recipes/Index.tsx b/resources/ts/back/Pages/Recipes/Index.tsx index a4e34a0b..9b35fe53 100644 --- a/resources/ts/back/Pages/Recipes/Index.tsx +++ b/resources/ts/back/Pages/Recipes/Index.tsx @@ -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 } }) => ( + + ), + cell: ({ row }: { row: Row> }) => ( + + {row.getValue("is_published") ? ( + + ) : ( + + )} + {str( + trans( + row.getValue("is_published") + ? "back.published" + : "back.draft", + ), + ) + .ucFirst() + .value()} + + ), + }, { accessorKey: "updated_at", header: ({ column }: { column: { id: string } }) => ( diff --git a/resources/ts/back/types/products.ts b/resources/ts/back/types/products.ts index e699a341..094b73f7 100644 --- a/resources/ts/back/types/products.ts +++ b/resources/ts/back/types/products.ts @@ -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)), diff --git a/resources/ts/back/types/recipes.ts b/resources/ts/back/types/recipes.ts index f5602b47..e4b7bde7 100644 --- a/resources/ts/back/types/recipes.ts +++ b/resources/ts/back/types/recipes.ts @@ -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), diff --git a/resources/ts/domain/entities/product.ts b/resources/ts/domain/entities/product.ts index 4151fdc4..c8d01325 100644 --- a/resources/ts/domain/entities/product.ts +++ b/resources/ts/domain/entities/product.ts @@ -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; diff --git a/resources/ts/domain/entities/recipe.ts b/resources/ts/domain/entities/recipe.ts index adaac24f..7a95ffd4 100644 --- a/resources/ts/domain/entities/recipe.ts +++ b/resources/ts/domain/entities/recipe.ts @@ -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; diff --git a/routes/back/web-back.php b/routes/back/web-back.php index 2e683f93..7a40e525 100644 --- a/routes/back/web-back.php +++ b/routes/back/web-back.php @@ -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) diff --git a/routes/breadcrumbs/back.php b/routes/breadcrumbs/back.php index 6ee456d0..8ba78820 100644 --- a/routes/breadcrumbs/back.php +++ b/routes/breadcrumbs/back.php @@ -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')));