From 57faeada75c4f73c6785fc1a2dd385ba45100a9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Thu, 5 Nov 2026 11:17:20 +0100 Subject: [PATCH] feat(dto): add CategoryProductsDto, ProductDto, and ProductSummaryDto Add new DTOs for handling product and category data structures. These DTOs facilitate data transfer and serialization for products and categories. refactor(controller): update ProductController to use executor pattern Refactor ProductController to utilize an executor for handling product creation, updating, and deletion, improving code organization and maintainability. refactor(controller): update RecipeController to use executor pattern Refactor RecipeController to utilize an executor for handling recipe creation, improving code organization and maintainability. chore: remove MediaController Remove MediaController as it is no longer needed in the application. feat(request): enhance StoreProductRequest and UpdateProductRequest Enhance StoreProductRequest and UpdateProductRequest to include methods for transforming request data into input objects for actions. chore: add ActionExecutorService for executing actions and queries Introduce ActionExecutorService to handle the execution of actions and queries with logging and transaction management. chore(deps): update composer dependencies Update composer dependencies to include webmozart/assert for improved type assertions. --- app/Contracts/Action.php | 18 ++ app/Contracts/ActionInput.php | 9 + app/Contracts/ActionInputEmpty.php | 13 ++ .../Directories/ProductDirectory.php | 10 +- app/Contracts/Directories/RecipeDirectory.php | 2 +- app/Contracts/Executor.php | 19 ++ app/Contracts/Query.php | 18 ++ app/Contracts/QueryInput.php | 9 + app/Contracts/QueryInputEmpty.php | 13 ++ .../Actions/Products/Create/CreateProduct.php | 58 ++++++ .../Products/Create/CreateProductInput.php | 76 ++++++++ .../Products/Create/FailedToCreateProduct.php | 9 + .../Actions/Products/Delete/DeleteProduct.php | 37 ++++ .../Products/Delete/DeleteProductInput.php | 16 ++ .../Products/Delete/FailedToDeleteProduct.php | 9 + .../FailedToForceDeleteProduct.php | 9 + .../ForceDelete/ForceDeleteProduct.php | 55 ++++++ .../ForceDelete/ForceDeleteProductInput.php | 16 ++ .../Restore/FailedToRestoreProduct.php | 9 + .../Products/Restore/RestoreProduct.php | 37 ++++ .../Products/Restore/RestoreProductInput.php | 16 ++ .../Products/Update/FailedToUpdateProduct.php | 9 + .../Actions/Products/Update/UpdateProduct.php | 83 +++++++++ .../Products/Update/UpdateProductInput.php | 78 ++++++++ .../Products/GetProductsSummariesQuery.php | 51 +++++ app/Directories/EloquentProductDirectory.php | 20 +- .../CategoryProductsDto.php} | 4 +- app/Dto/ProductDto.php | 176 ++++++++++++++++++ app/Dto/ProductSummaryDto.php | 15 ++ .../Controllers/Back/ProductController.php | 150 +++++++-------- .../Controllers/Back/RecipeController.php | 16 +- app/Http/Controllers/MediaController.php | 32 ---- .../Back/Products/StoreProductRequest.php | 89 ++++++++- .../Back/Products/UpdateProductRequest.php | 87 +++++++++ app/Providers/AppServiceProvider.php | 9 +- app/Services/ActionExecutorService.php | 117 ++++++++++++ composer.json | 3 +- composer.lock | 68 ++++++- domain/Models/Entities/Product.php | 9 +- .../ValueObjects/Products}/ProductSummary.php | 2 +- resources/ts/front/Pages/Products/Index.tsx | 10 +- resources/ts/front/Pages/Products/Show.tsx | 6 +- resources/ts/front/Pages/Recipes/Show.tsx | 4 +- resources/ts/front/schemas/product.schema.ts | 4 +- routes/web-front.php | 3 - 45 files changed, 1339 insertions(+), 164 deletions(-) create mode 100644 app/Contracts/Action.php create mode 100644 app/Contracts/ActionInput.php create mode 100644 app/Contracts/ActionInputEmpty.php create mode 100644 app/Contracts/Executor.php create mode 100644 app/Contracts/Query.php create mode 100644 app/Contracts/QueryInput.php create mode 100644 app/Contracts/QueryInputEmpty.php create mode 100644 app/Cqs/Actions/Products/Create/CreateProduct.php create mode 100644 app/Cqs/Actions/Products/Create/CreateProductInput.php create mode 100644 app/Cqs/Actions/Products/Create/FailedToCreateProduct.php create mode 100644 app/Cqs/Actions/Products/Delete/DeleteProduct.php create mode 100644 app/Cqs/Actions/Products/Delete/DeleteProductInput.php create mode 100644 app/Cqs/Actions/Products/Delete/FailedToDeleteProduct.php create mode 100644 app/Cqs/Actions/Products/ForceDelete/FailedToForceDeleteProduct.php create mode 100644 app/Cqs/Actions/Products/ForceDelete/ForceDeleteProduct.php create mode 100644 app/Cqs/Actions/Products/ForceDelete/ForceDeleteProductInput.php create mode 100644 app/Cqs/Actions/Products/Restore/FailedToRestoreProduct.php create mode 100644 app/Cqs/Actions/Products/Restore/RestoreProduct.php create mode 100644 app/Cqs/Actions/Products/Restore/RestoreProductInput.php create mode 100644 app/Cqs/Actions/Products/Update/FailedToUpdateProduct.php create mode 100644 app/Cqs/Actions/Products/Update/UpdateProduct.php create mode 100644 app/Cqs/Actions/Products/Update/UpdateProductInput.php create mode 100644 app/Cqs/Queries/Products/GetProductsSummariesQuery.php rename app/{Dtos/CategoryProducts.php => Dto/CategoryProductsDto.php} (92%) create mode 100644 app/Dto/ProductDto.php create mode 100644 app/Dto/ProductSummaryDto.php delete mode 100644 app/Http/Controllers/MediaController.php create mode 100644 app/Services/ActionExecutorService.php rename {app/Dtos => domain/Models/ValueObjects/Products}/ProductSummary.php (81%) diff --git a/app/Contracts/Action.php b/app/Contracts/Action.php new file mode 100644 index 00000000..0d9f1436 --- /dev/null +++ b/app/Contracts/Action.php @@ -0,0 +1,18 @@ + */ +/** @extends Directory */ interface ProductDirectory extends Directory { public function find(ProductId $id): ?Product; @@ -21,9 +21,9 @@ interface ProductDirectory extends Directory public function findBySlug(string $slug): ?Product; /** - * @return \App\Dtos\ProductSummary[] + * @return \Domain\Models\ValueObjects\Products\ProductSummary[] */ - public function getAllProductsSummary(): array; + public function getAllProductsSummaries(): array; /** * @return LengthAwarePaginator @@ -46,7 +46,7 @@ interface ProductDirectory extends Directory ?bool $isEgalim = null, string $search = '', int $limitPerCategory = 6 - ): ?CategoryProducts; + ): ?CategoryProductsDto; /** @return \Domain\Models\Entities\Product[] */ public function getRelatedProducts(RecipeId $recipeId, int $limit = 4): array; diff --git a/app/Contracts/Directories/RecipeDirectory.php b/app/Contracts/Directories/RecipeDirectory.php index 5e9abb5b..51ffd285 100644 --- a/app/Contracts/Directories/RecipeDirectory.php +++ b/app/Contracts/Directories/RecipeDirectory.php @@ -11,7 +11,7 @@ use Domain\Models\ValueObjects\Entities\RecipeId; use Domain\Models\ValueObjects\Pagination; use Illuminate\Pagination\LengthAwarePaginator; -/** @extends Directory */ +/** @extends Directory */ interface RecipeDirectory extends Directory { public function find(RecipeId $id): ?Recipe; diff --git a/app/Contracts/Executor.php b/app/Contracts/Executor.php new file mode 100644 index 00000000..984875ee --- /dev/null +++ b/app/Contracts/Executor.php @@ -0,0 +1,19 @@ +|\App\Contracts\Action $executable + * @param TInputAction|TInputQuery $input + * @return TResult + */ + public function execute(Action | Query $executable, ActionInput | QueryInput $input): mixed; +} diff --git a/app/Contracts/Query.php b/app/Contracts/Query.php new file mode 100644 index 00000000..2df738ac --- /dev/null +++ b/app/Contracts/Query.php @@ -0,0 +1,18 @@ + + * phpcs:enable + */ +final class CreateProduct implements Action +{ + /** + * @param \App\Cqs\Actions\Products\Create\CreateProductInput $input + */ + public function __invoke(ActionInput $input): ProductId | FailedToCreateProduct + { + Assert::isInstanceOf($input, CreateProductInput::class); + + $product = new Product([ + 'seo_title' => $input->seoTitle, + 'seo_description' => $input->seoDescription, + 'name' => $input->name, + 'picture' => $input->picture, + 'picture_alt' => $input->pictureAlt, + 'picture_title' => $input->pictureTitle, + 'category' => $input->category, + 'technology' => $input->technology, + 'is_egalim' => $input->isEgalim, + 'breeding_methods' => $input->breedingMethods, + 'businesses' => $input->businesses, + 'formats' => $input->formats, + 'description' => $input->description, + 'details_and_advantages' => $input->detailsAndAdvantages, + 'handling_advices' => $input->handlingAdvices, + 'ingredients' => $input->ingredients, + 'conservation_before_opening' => $input->conservationBeforeOpening, + 'conservation_after_opening' => $input->conservationAfterOpening, + 'nutritional_values' => $input->nutritionalValues, + 'pdf' => $input->pdf, + ]); + + if (! $product->save()) { + return new FailedToCreateProduct(); + } + + return new ProductId(Uuid::fromString($product->id)); + } +} diff --git a/app/Cqs/Actions/Products/Create/CreateProductInput.php b/app/Cqs/Actions/Products/Create/CreateProductInput.php new file mode 100644 index 00000000..e2b59f19 --- /dev/null +++ b/app/Cqs/Actions/Products/Create/CreateProductInput.php @@ -0,0 +1,76 @@ +name); + Assert::notEmpty($this->seoTitle); + Assert::notEmpty($this->seoDescription); + Assert::notEmpty($this->description); + Assert::notEmpty($this->detailsAndAdvantages); + Assert::notEmpty($this->handlingAdvices); + Assert::notEmpty($this->conservationBeforeOpening); + Assert::notEmpty($this->pictureAlt); + Assert::notEmpty($this->pictureTitle); + + Assert::allIsAOf($this->breedingMethods, BreedingMethod::class); + Assert::allIsAOf($this->businesses, Business::class); + Assert::allIsAOf($this->formats, ProductFormat::class); + + Assert::notEmpty($this->breedingMethods); + Assert::notEmpty($this->businesses); + Assert::notEmpty($this->formats); + + when($this->ingredients !== null, fn () => Assert::notEmpty($this->ingredients)); + when($this->conservationAfterOpening !== null, fn () => Assert::notEmpty($this->conservationAfterOpening)); + + foreach ($this->nutritionalValues as $value) { + Assert::isArray($value); + Assert::keyExists($value, 'unit'); + Assert::keyExists($value, 'value'); + Assert::isInstanceOf($value['unit'], NutritionnalUnit::class); + Assert::string($value['value']); + } + } +} diff --git a/app/Cqs/Actions/Products/Create/FailedToCreateProduct.php b/app/Cqs/Actions/Products/Create/FailedToCreateProduct.php new file mode 100644 index 00000000..35670cbf --- /dev/null +++ b/app/Cqs/Actions/Products/Create/FailedToCreateProduct.php @@ -0,0 +1,9 @@ + + * phpcs:enable + */ +final class DeleteProduct implements Action +{ + /** + * @param \App\Cqs\Actions\Products\Delete\DeleteProductInput $input + */ + public function __invoke(ActionInput $input): ProductId | FailedToDeleteProduct + { + Assert::isInstanceOf($input, DeleteProductInput::class); + + $product = Product::query()->findOrFail((string) $input->id->value); + + if (! $product->delete()) { + return new FailedToDeleteProduct(); + } + + return new ProductId(Uuid::fromString($product->id)); + } +} diff --git a/app/Cqs/Actions/Products/Delete/DeleteProductInput.php b/app/Cqs/Actions/Products/Delete/DeleteProductInput.php new file mode 100644 index 00000000..f5b819ed --- /dev/null +++ b/app/Cqs/Actions/Products/Delete/DeleteProductInput.php @@ -0,0 +1,16 @@ + + * phpcs:enable + */ +final class ForceDeleteProduct implements Action +{ + public function __construct( + private readonly StorageService $storageService, + private readonly PublicS3Disk $s3Disk, + ) { + } + + /** + * @param \App\Cqs\Actions\Products\ForceDelete\ForceDeleteProductInput $input + */ + public function __invoke(ActionInput $input): ProductId | FailedToForceDeleteProduct + { + Assert::isInstanceOf($input, ForceDeleteProductInput::class); + + $product = Product::withTrashed()->findOrFail((string) $input->id->value); + $picture = $product->picture; + $pdf = $product->pdf; + + if (! $product->forceDelete()) { + return new FailedToForceDeleteProduct(); + } + + if ($picture !== null) { + $this->storageService->removeFromDisk($picture, $this->s3Disk->disk); + } + + if ($pdf !== null) { + $this->storageService->removeFromDisk($pdf, $this->s3Disk->disk); + } + + return new ProductId(Uuid::fromString($product->id)); + } +} diff --git a/app/Cqs/Actions/Products/ForceDelete/ForceDeleteProductInput.php b/app/Cqs/Actions/Products/ForceDelete/ForceDeleteProductInput.php new file mode 100644 index 00000000..fa597492 --- /dev/null +++ b/app/Cqs/Actions/Products/ForceDelete/ForceDeleteProductInput.php @@ -0,0 +1,16 @@ + + * phpcs:enable + */ +final class RestoreProduct implements Action +{ + /** + * @param \App\Cqs\Actions\Products\Restore\RestoreProductInput $input + */ + public function __invoke(ActionInput $input): ProductId | FailedToRestoreProduct + { + Assert::isInstanceOf($input, RestoreProductInput::class); + + $product = Product::withTrashed()->findOrFail((string) $input->id->value); + + if (! $product->restore()) { + return new FailedToRestoreProduct(); + } + + return new ProductId(Uuid::fromString($product->id)); + } +} diff --git a/app/Cqs/Actions/Products/Restore/RestoreProductInput.php b/app/Cqs/Actions/Products/Restore/RestoreProductInput.php new file mode 100644 index 00000000..6fd8046d --- /dev/null +++ b/app/Cqs/Actions/Products/Restore/RestoreProductInput.php @@ -0,0 +1,16 @@ + + * phpcs:enable + */ +final class UpdateProduct implements Action +{ + public function __construct( + private readonly StorageService $storageService, + private readonly PublicS3Disk $s3Disk, + ) { + } + + /** + * @param \App\Cqs\Actions\Products\Update\UpdateProductInput $input + */ + public function __invoke(ActionInput $input): ProductDto | FailedToUpdateProduct + { + Assert::isInstanceOf($input, UpdateProductInput::class); + + $product = Product::query()->findOrFail((string) $input->id->value); + + $oldPicture = $product->picture; + $oldPdf = $product->pdf; + + $product->fill([ + 'seo_title' => $input->seoTitle, + 'seo_description' => $input->seoDescription, + 'name' => $input->name, + 'picture_alt' => $input->pictureAlt, + 'picture_title' => $input->pictureTitle, + 'category' => $input->category, + 'technology' => $input->technology, + 'is_egalim' => $input->isEgalim, + 'breeding_methods' => $input->breedingMethods, + 'businesses' => $input->businesses, + 'formats' => $input->formats, + 'description' => $input->description, + 'details_and_advantages' => $input->detailsAndAdvantages, + 'handling_advices' => $input->handlingAdvices, + 'ingredients' => $input->ingredients, + 'conservation_before_opening' => $input->conservationBeforeOpening, + 'conservation_after_opening' => $input->conservationAfterOpening, + 'nutritional_values' => $input->nutritionalValues, + ]); + + if ($input->picture !== null) { + $product->picture = $input->picture; + } + + $product->pdf = $input->pdf; + + if (! $product->save()) { + return new FailedToUpdateProduct(); + } + + // Clean up replaced or removed S3 files + if ($input->picture !== null && $oldPicture !== null && $oldPicture->value !== $input->picture->value) { + $this->storageService->removeFromDisk($oldPicture, $this->s3Disk->disk); + } + + if ($oldPdf !== null && ($input->pdf === null || $oldPdf->value !== $input->pdf->value)) { + $this->storageService->removeFromDisk($oldPdf, $this->s3Disk->disk); + } + + return ProductDto::fromModel($product, $this->s3Disk); + } +} diff --git a/app/Cqs/Actions/Products/Update/UpdateProductInput.php b/app/Cqs/Actions/Products/Update/UpdateProductInput.php new file mode 100644 index 00000000..34747a36 --- /dev/null +++ b/app/Cqs/Actions/Products/Update/UpdateProductInput.php @@ -0,0 +1,78 @@ +name); + Assert::notEmpty($this->seoTitle); + Assert::notEmpty($this->seoDescription); + Assert::notEmpty($this->description); + Assert::notEmpty($this->detailsAndAdvantages); + Assert::notEmpty($this->handlingAdvices); + Assert::notEmpty($this->conservationBeforeOpening); + Assert::notEmpty($this->pictureAlt); + Assert::notEmpty($this->pictureTitle); + + Assert::allIsAOf($this->breedingMethods, BreedingMethod::class); + Assert::allIsAOf($this->businesses, Business::class); + Assert::allIsAOf($this->formats, ProductFormat::class); + + Assert::notEmpty($this->breedingMethods); + Assert::notEmpty($this->businesses); + Assert::notEmpty($this->formats); + + when($this->ingredients !== null, fn () => Assert::notEmpty($this->ingredients)); + when($this->conservationAfterOpening !== null, fn () => Assert::notEmpty($this->conservationAfterOpening)); + + foreach ($this->nutritionalValues as $value) { + Assert::isArray($value); + Assert::keyExists($value, 'unit'); + Assert::keyExists($value, 'value'); + Assert::isInstanceOf($value['unit'], NutritionnalUnit::class); + Assert::string($value['value']); + } + } +} diff --git a/app/Cqs/Queries/Products/GetProductsSummariesQuery.php b/app/Cqs/Queries/Products/GetProductsSummariesQuery.php new file mode 100644 index 00000000..5f0b5bd8 --- /dev/null +++ b/app/Cqs/Queries/Products/GetProductsSummariesQuery.php @@ -0,0 +1,51 @@ +> + */ +final readonly class GetProductsSummariesQuery implements Query +{ + public function __construct( + private ProductDirectory $productDirectory, + private PublicS3Disk $publicS3Disk + ) { + } + + /** + * @return \Illuminate\Support\Collection + */ + public function __invoke(QueryInput $input): Collection + { + Assert::isAOf( + $input, + QueryInputEmpty::class, + ); + + return Collection::make($this->productDirectory->getAllProductsSummaries()) + ->map(fn (ProductSummary $product): ProductSummaryDto => $this->mapToDto($product)); + } + + private function mapToDto(ProductSummary $product): ProductSummaryDto + { + return new ProductSummaryDto( + id: $product->id, + name: $product->name, + pictureUrl: $product->picture ? + $this->publicS3Disk->publicUrlOf($product->picture) : null, + ); + } +} diff --git a/app/Directories/EloquentProductDirectory.php b/app/Directories/EloquentProductDirectory.php index b13b647c..f37762a8 100644 --- a/app/Directories/EloquentProductDirectory.php +++ b/app/Directories/EloquentProductDirectory.php @@ -5,8 +5,8 @@ declare(strict_types=1); namespace App\Directories; use App\Contracts\Directories\ProductDirectory; -use App\Dtos\CategoryProducts; -use App\Dtos\ProductSummary; +use App\Dto\CategoryProductsDto; +use App\Lib\PublicS3Disk; use App\Models\Product; use App\Models\Recipe; use Domain\Models\Entities\Product as DomainProduct; @@ -14,6 +14,7 @@ use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Models\ValueObjects\Entities\RecipeId; use Domain\Models\ValueObjects\Pagination; use Domain\Models\ValueObjects\Products\ProductCategory; +use Domain\Models\ValueObjects\Products\ProductSummary; use Illuminate\Database\Eloquent\Builder; use Illuminate\Pagination\LengthAwarePaginator; use Ramsey\Uuid\Uuid; @@ -21,6 +22,11 @@ use Ramsey\Uuid\UuidInterface; class EloquentProductDirectory implements ProductDirectory { + public function __construct( + private readonly PublicS3Disk $publicS3Disk, + ) { + } + public function find(ProductId $id): ?DomainProduct { return Product::query() @@ -43,7 +49,7 @@ class EloquentProductDirectory implements ProductDirectory ->first(); } - public function getAllProductsSummary(): array + public function getAllProductsSummaries(): array { return Product::query() ->select(['id', 'name', 'picture']) @@ -98,7 +104,7 @@ class EloquentProductDirectory implements ProductDirectory ?bool $isEgalim = null, string $search = '', int $limitPerCategory = 6 - ): ?CategoryProducts { + ): ?CategoryProductsDto { $dbQueryCallback = function (Builder $query) use ($category, $breedingMethods, $technologies, $businesses, $isEgalim) { /** @var \Illuminate\Database\Eloquent\Builder $query */ @@ -157,7 +163,7 @@ class EloquentProductDirectory implements ProductDirectory ->map(fn (Product $product) => $this->mapToEntity($product)) ->all(); - return new CategoryProducts( + return new CategoryProductsDto( category: $category, total: $count, products: $products, @@ -194,10 +200,10 @@ class EloquentProductDirectory implements ProductDirectory seoDescription: $product->seo_description, conservationAfterOpening: $product->conservation_after_opening, nutritionalValues: $product->nutritional_values, - picture: $product->picture->value, + picture: $product->picture ? $this->publicS3Disk->publicUrlOf($product->picture->value) : null, pictureAlt: $product->picture_alt, pictureTitle: $product->picture_title, - pdfFilePath: $product->pdf?->value, + pdfFilePath: $product->pdf ? $this->publicS3Disk->publicUrlOf($product->pdf->value) : null, associatedRecipes: $product->recipes->map( fn (Recipe $recipe): UuidInterface => $recipe->getId()->value )->all() diff --git a/app/Dtos/CategoryProducts.php b/app/Dto/CategoryProductsDto.php similarity index 92% rename from app/Dtos/CategoryProducts.php rename to app/Dto/CategoryProductsDto.php index c0c415ed..184d8377 100644 --- a/app/Dtos/CategoryProducts.php +++ b/app/Dto/CategoryProductsDto.php @@ -2,14 +2,14 @@ declare(strict_types=1); -namespace App\Dtos; +namespace App\Dto; use Domain\Models\Entities\Product; use Domain\Models\ValueObjects\Products\ProductCategory; use Illuminate\Support\Arr; use Override; -final readonly class CategoryProducts implements \JsonSerializable +final readonly class CategoryProductsDto implements \JsonSerializable { public function __construct( public ProductCategory $category, diff --git a/app/Dto/ProductDto.php b/app/Dto/ProductDto.php new file mode 100644 index 00000000..fed28379 --- /dev/null +++ b/app/Dto/ProductDto.php @@ -0,0 +1,176 @@ + + */ +final readonly class ProductDto implements Arrayable, JsonSerializable +{ + /** + * @param \Domain\Models\ValueObjects\Products\BreedingMethod[] $breedingMethods + * @param \Domain\Models\ValueObjects\Products\Business[] $businesses + * @param \Domain\Models\ValueObjects\Products\ProductFormat[] $formats + */ + public function __construct( + public string $id, + public string $seoTitle, + public string $seoDescription, + public string $name, + public ?string $picture, + public ?string $pictureUrl, + public string $pictureAlt, + public string $pictureTitle, + public string $slug, + public ProductCategory $category, + public Technology $technology, + public bool $isEgalim, + public array $breedingMethods, + public array $businesses, + public array $formats, + public string $description, + public string $detailsAndAdvantages, + public string $handlingAdvices, + public ?string $ingredients, + public string $conservationBeforeOpening, + public ?string $conservationAfterOpening, + public ?NutritionalValues $nutritionalValues, + public ?string $pdf, + public ?string $pdfUrl, + public ?CarbonInterface $createdAt, + public ?CarbonInterface $updatedAt, + public ?CarbonInterface $deletedAt, + ) { + } + + public static function fromModel(Product $product, ?PublicS3Disk $publicS3Disk = null): self + { + $publicS3Disk ??= Container::getInstance()->make(PublicS3Disk::class); + + $picturePath = $product->picture?->value; + $pdfPath = $product->pdf?->value; + + return new self( + id: (string) $product->id, + seoTitle: (string) $product->seo_title, + seoDescription: (string) $product->seo_description, + name: (string) $product->name, + picture: $picturePath, + pictureUrl: $picturePath !== null ? $publicS3Disk->publicUrlOf($picturePath) : null, + pictureAlt: (string) $product->picture_alt, + pictureTitle: (string) $product->picture_title, + slug: (string) $product->slug, + category: $product->category, + technology: $product->technology, + isEgalim: (bool) $product->is_egalim, + breedingMethods: $product->breeding_methods->values()->all(), + businesses: $product->businesses->values()->all(), + formats: $product->formats->values()->all(), + description: (string) $product->description, + detailsAndAdvantages: (string) $product->details_and_advantages, + handlingAdvices: (string) $product->handling_advices, + ingredients: $product->ingredients, + conservationBeforeOpening: (string) $product->conservation_before_opening, + conservationAfterOpening: $product->conservation_after_opening, + nutritionalValues: $product->nutritional_values, + pdf: $pdfPath, + pdfUrl: $pdfPath !== null ? $publicS3Disk->publicUrlOf($pdfPath) : null, + createdAt: $product->created_at, + updatedAt: $product->updated_at, + deletedAt: $product->deleted_at, + ); + } + + public static function fromEntity( + \Domain\Models\Entities\Product $product, + ?PublicS3Disk $publicS3Disk = null + ): self { + $publicS3Disk ??= Container::getInstance()->make(PublicS3Disk::class); + + return new self( + id: (string) $product->id->value, + seoTitle: (string) ($product->seoTitle ?? ''), + seoDescription: (string) ($product->seoDescription ?? ''), + name: $product->name, + picture: $product->picture, + pictureUrl: $product->picture !== null ? $publicS3Disk->publicUrlOf($product->picture) : null, + pictureAlt: (string) ($product->pictureAlt ?? ''), + pictureTitle: (string) ($product->pictureTitle ?? ''), + slug: $product->slug, + category: $product->category, + technology: $product->technology, + isEgalim: $product->isEgalim, + breedingMethods: $product->breedingMethods, + businesses: $product->businesses, + formats: $product->formats, + description: $product->description, + detailsAndAdvantages: $product->detailsAndAdvantages, + handlingAdvices: $product->handlingAdvices, + ingredients: $product->ingredients, + conservationBeforeOpening: $product->conservationBeforeOpening, + conservationAfterOpening: $product->conservationAfterOpening, + nutritionalValues: $product->nutritionalValues, + pdf: $product->pdfFilePath, + pdfUrl: $product->pdfFilePath !== null ? $publicS3Disk->publicUrlOf($product->pdfFilePath) : null, + createdAt: null, + updatedAt: null, + deletedAt: null, + ); + } + + /** + * @return array + */ + public function toArray(): array + { + return [ + 'id' => $this->id, + 'seo_title' => $this->seoTitle, + 'seo_description' => $this->seoDescription, + 'name' => $this->name, + 'picture' => $this->picture, + 'pictureUrl' => $this->pictureUrl, + 'picture_alt' => $this->pictureAlt, + 'picture_title' => $this->pictureTitle, + 'slug' => $this->slug, + 'category' => $this->category->value, + 'technology' => $this->technology->value, + 'is_egalim' => $this->isEgalim, + 'breeding_methods' => $this->breedingMethods, + 'businesses' => $this->businesses, + 'formats' => $this->formats, + 'description' => $this->description, + 'details_and_advantages' => $this->detailsAndAdvantages, + 'handling_advices' => $this->handlingAdvices, + 'ingredients' => $this->ingredients, + 'conservation_before_opening' => $this->conservationBeforeOpening, + 'conservation_after_opening' => $this->conservationAfterOpening, + 'nutritional_values' => $this->nutritionalValues?->toArray(), + 'pdf' => $this->pdf, + 'pdfUrl' => $this->pdfUrl, + 'created_at' => $this->createdAt?->toISOString(), + 'updated_at' => $this->updatedAt?->toISOString(), + 'deleted_at' => $this->deletedAt?->toISOString(), + ]; + } + + /** + * @return array + */ + public function jsonSerialize(): array + { + return $this->toArray(); + } +} diff --git a/app/Dto/ProductSummaryDto.php b/app/Dto/ProductSummaryDto.php new file mode 100644 index 00000000..c19746f8 --- /dev/null +++ b/app/Dto/ProductSummaryDto.php @@ -0,0 +1,15 @@ +authorize('create', Product::class); - return DB::transaction(function () use ($request, $s3) { - $product = new Product(); - /** @var array $data */ - $data = $request->only($product->getFillable()); + $result = $this->executor->execute($createProduct, $request->toCreateProductInput()); - /** @var array $dataToFill */ - $dataToFill = Arr::except($data, ['picture', 'pdf']); - $product->fill($dataToFill); - - $product->picture = StorageService::storeUploadedOntoDisk($request->file('picture'), $s3->disk); - if ($request->file('pdf')) { - $product->pdf = StorageService::storeUploadedOntoDisk($request->file('pdf'), $s3->disk); - } - - if ($product->saveOrFail()) { - return redirect()->route('back.products.edit', $product) - ->with('success', trans('uwil-backend::crud.messages.has_been_created', [ - 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); - } - - return redirect()->back() + return match (true) { + $result instanceof ProductId => redirect()->route('back.products.edit', $result) + ->with('success', trans('uwil-backend::crud.messages.has_been_created', [ + 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), + ])), + default => redirect()->back() ->with('error', trans('uwil-backend::crud.messages.cannot_be_created', [ 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); - }); + ])), + }; } public function edit(Product $product): Response @@ -149,38 +143,19 @@ class ProductController extends BackendController public function update( UpdateProductRequest $request, Product $product, - PublicS3Disk $s3, - ): RedirectResponse { + UpdateProduct $updateProduct, + ): ProductDto { $this->authorize('update', $product); - return DB::transaction(function () use ($request, $product, $s3) { - /** @var array $data */ - $data = $request->only($product->getFillable()); + $result = $this->executor->execute($updateProduct, $request->toUpdateProductInput($product)); - /** @var array $dataToFill */ - $dataToFill = Arr::except($data, ['picture', 'pdf']); - $product->fill($dataToFill); + if (! $result instanceof ProductDto) { + abort(500, trans('uwil-backend::crud.messages.cannot_be_updated', [ + 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), + ])); + } - if ($request->file('picture')) { - $product->picture = StorageService::storeUploadedOntoDisk($request->file('picture'), $s3->disk); - } - - if ($request->file('pdf')) { - $product->pdf = StorageService::storeUploadedOntoDisk($request->file('pdf'), $s3->disk); - } - - if ($product->saveOrFail()) { - return redirect()->route('back.products.edit', $product) - ->with('success', trans('uwil-backend::crud.messages.has_been_updated', [ - 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); - } - - return redirect()->route('back.products.edit', $product) - ->with('error', trans('uwil-backend::crud.messages.cannot_be_updated', [ - 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); - }); + return $result; } public function duplicate(Product $product): Response @@ -188,62 +163,65 @@ class ProductController extends BackendController return $this->create($product->replicate()); } - public function restore(string $id): RedirectResponse + public function restore(string $id, RestoreProduct $restoreProduct): RedirectResponse { $product = Product::withTrashed()->findOrFail($id); $this->authorize('restore', $product); $previousQueries = $this->getPreviousQueries(); - if ($product->restore()) { - return redirect()->route('back.products.trash', $previousQueries) + $result = $this->executor->execute($restoreProduct, new RestoreProductInput($product->getId())); + + return match (true) { + $result instanceof ProductId => redirect()->route('back.products.trash', $previousQueries) ->with('success', trans('uwil-backend::crud.messages.has_been_restored', [ 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); - } - - return redirect()->back() - ->with('error', trans('uwil-backend::crud.messages.cannot_be_restored', [ - 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); + ])), + default => redirect()->back() + ->with('error', trans('uwil-backend::crud.messages.cannot_be_restored', [ + 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), + ])), + }; } - public function destroy(Product $product): RedirectResponse + public function destroy(Product $product, DeleteProduct $deleteProduct): RedirectResponse { $this->authorize('delete', $product); $previousQueries = $this->getPreviousQueries(); - if ($product->delete()) { - return redirect()->route('back.products.index', $previousQueries) + $result = $this->executor->execute($deleteProduct, new DeleteProductInput($product->getId())); + + return match (true) { + $result instanceof ProductId => redirect()->route('back.products.index', $previousQueries) ->with('success', trans('uwil-backend::crud.messages.has_been_deleted', [ 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); - } - - return redirect()->back() - ->with('error', trans('uwil-backend::crud.messages.cannot_be_deleted', [ - 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); + ])), + default => redirect()->back() + ->with('error', trans('uwil-backend::crud.messages.cannot_be_deleted', [ + 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), + ])), + }; } - public function forceDestroy(string $id): RedirectResponse + public function forceDestroy(string $id, ForceDeleteProduct $forceDeleteProduct): RedirectResponse { $product = Product::withTrashed()->findOrFail($id); $this->authorize('forceDelete', $product); $previousQueries = $this->getPreviousQueries(); - if ($product->forceDelete()) { - return redirect()->route('back.products.trash', $previousQueries) + $result = $this->executor->execute($forceDeleteProduct, new ForceDeleteProductInput($product->getId())); + + return match (true) { + $result instanceof ProductId => redirect()->route('back.products.trash', $previousQueries) ->with('success', trans('uwil-backend::crud.messages.has_been_deleted', [ 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); - } - - return redirect()->back() - ->with('error', trans('uwil-backend::crud.messages.cannot_be_deleted', [ - 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), - ])); + ])), + default => redirect()->back() + ->with('error', trans('uwil-backend::crud.messages.cannot_be_deleted', [ + 'model' => Str::ucfirst(trans_choice('models.classes.product', 1)), + ])), + }; } /** @return array> */ diff --git a/app/Http/Controllers/Back/RecipeController.php b/app/Http/Controllers/Back/RecipeController.php index 7c6d5624..b445e886 100644 --- a/app/Http/Controllers/Back/RecipeController.php +++ b/app/Http/Controllers/Back/RecipeController.php @@ -5,6 +5,9 @@ declare(strict_types=1); namespace App\Http\Controllers\Back; use App\Contracts\Directories\ProductDirectory; +use App\Contracts\Executor; +use App\Contracts\QueryInputEmpty; +use App\Cqs\Queries\Products\GetProductsSummariesQuery; use App\Http\Requests\Back\Recipes\IndexRecipeRequest; use App\Http\Requests\Back\Recipes\StoreRecipeRequest; use App\Http\Requests\Back\Recipes\UpdateRecipeRequest; @@ -30,6 +33,7 @@ class RecipeController extends BackendController Request $request, Session $session, private readonly ProductDirectory $productDirectory, + private readonly Executor $executor ) { parent::__construct( $request, @@ -86,17 +90,19 @@ class RecipeController extends BackendController return redirect()->route('back.recipes.edit', $recipe); } - public function create(Recipe $recipe): Response + public function create(Recipe $recipe, GetProductsSummariesQuery $getProductsSummaries): Response { $this->authorize('create', Recipe::class); + $productSummaries = $this->executor->execute($getProductsSummaries, QueryInputEmpty::create()); + return $this->inertiaRender('back/Pages/Recipes/Create', [ 'data' => CommonResource::make($recipe), 'enumProductCategory' => ProductCategory::toArray(), 'enumConsumptionTime' => ConsumptionTime::toArray(), 'enumInspiration' => Inspiration::toArray(), 'enumSeason' => Season::toArray(), - 'allProducts' => $this->productDirectory->getAllProductsSummary(), + 'allProducts' => $productSummaries->toArray(), ]); } @@ -144,7 +150,7 @@ class RecipeController extends BackendController 'enumConsumptionTime' => ConsumptionTime::toArray(), 'enumInspiration' => Inspiration::toArray(), 'enumSeason' => Season::toArray(), - 'allProducts' => $this->productDirectory->getAllProductsSummary(), + 'allProducts' => $this->productDirectory->getAllProductsSummaries(), ]); } @@ -184,11 +190,11 @@ class RecipeController extends BackendController }); } - public function duplicate(Recipe $recipe): Response + public function duplicate(Recipe $recipe, GetProductsSummariesQuery $getProductsSummaries): Response { $this->authorize('duplicate', $recipe); - return $this->create($recipe->replicate()); + return $this->create($recipe->replicate(), $getProductsSummaries); } public function restore(string $id): RedirectResponse diff --git a/app/Http/Controllers/MediaController.php b/app/Http/Controllers/MediaController.php deleted file mode 100644 index d9098853..00000000 --- a/app/Http/Controllers/MediaController.php +++ /dev/null @@ -1,32 +0,0 @@ -disk->value); - $prefix = Config::string('storage-service.prefix', 'media'); - - if (! ($disk instanceof AwsS3V3Adapter)) { - throw new \UnexpectedValueException("Expected {$s3->disk->value} to be an S3 disk"); - } - - $trimmedPath = ltrim($path, '/'); - $fullPath = ltrim(trim($prefix, '/') . "/{$trimmedPath}", '/'); - $s3Url = $disk->url($fullPath); - - return redirect()->away($s3Url, 301, [ - 'Cache-Control' => 'public, max-age=31536000, immutable', - ]); - } -} diff --git a/app/Http/Requests/Back/Products/StoreProductRequest.php b/app/Http/Requests/Back/Products/StoreProductRequest.php index 8f3c0f41..0a25199c 100644 --- a/app/Http/Requests/Back/Products/StoreProductRequest.php +++ b/app/Http/Requests/Back/Products/StoreProductRequest.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace App\Http\Requests\Back\Products; +use App\Cqs\Actions\Products\Create\CreateProductInput; +use App\Lib\PublicS3Disk; use App\Rules\MaxStrippedLength; use App\Services\AdminAuthService; use Domain\Models\ValueObjects\Products\BreedingMethod; @@ -13,8 +15,12 @@ use Domain\Models\ValueObjects\Products\ProductCategory; use Domain\Models\ValueObjects\Products\ProductFormat; use Domain\Models\ValueObjects\Products\Technology; use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Http\UploadedFile; +use Illuminate\Support\Arr; use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\Enum; +use Uwil\Storage\Contracts\StorageService; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; class StoreProductRequest extends FormRequest { @@ -25,7 +31,9 @@ class StoreProductRequest extends FormRequest protected const int PICTURE_HEIGHT = 800; public function __construct( - private readonly AdminAuthService $authService + protected readonly AdminAuthService $authService, + protected readonly StorageService $storageService, + protected readonly PublicS3Disk $s3Disk, ) { } @@ -37,6 +45,58 @@ class StoreProductRequest extends FormRequest return $this->authService->check(); } + public function toCreateProductInput(): CreateProductInput + { + return new CreateProductInput( + name: $this->string('name')->trim()->value(), + seoTitle: $this->string('seo_title')->trim()->value(), + seoDescription: $this->string('seo_description')->trim()->value(), + category: $this->enum('category', ProductCategory::class, ProductCategory::HARD_BOILED_EGGS), + technology: $this->enum('technology', Technology::class, Technology::FRESH), + isEgalim: $this->boolean('is_egalim'), + breedingMethods: array_map( + fn ($method) => BreedingMethod::from( + $this->mixedToString($method) + ), + $this->array('breeding_methods') + ), + businesses: array_map( + fn ($business) => Business::from( + $this->mixedToString($business) + ), + $this->array('businesses') + ), + formats: array_map( + fn ($format) => ProductFormat::from( + $this->mixedToString($format) + ), + $this->array('formats') + ), + description: $this->string('description')->trim()->value(), + detailsAndAdvantages: $this->string('details_and_advantages')->trim()->value(), + handlingAdvices: $this->string('handling_advices')->trim()->value(), + ingredients: $this->filled('ingredients') ? $this->string('ingredients')->trim()->value() : null, + conservationBeforeOpening: $this->string('conservation_before_opening')->trim()->value(), + conservationAfterOpening: $this->filled('conservation_after_opening') ? + $this->string('conservation_after_opening')->trim()->value() : null, + picture: $this->hasFile('picture') ? $this->storeFile($this->file('picture')) : null, + pictureAlt: $this->string('picture_alt')->trim()->value(), + pictureTitle: $this->string('picture_title')->trim()->value(), + pdf: $this->hasFile('pdf') ? $this->storeFile($this->file('pdf')) : null, + nutritionalValues: array_map( + function ($value) { + $value = $this->mixedToArray($value); + + return [ + 'unit' => NutritionnalUnit::from(Arr::string($value, 'unit')), + 'value' => Arr::string($value, 'value'), + ]; + }, + $this->array('nutritional_values') + ), + ); + } + /** * Prepare the data for validation. */ @@ -147,4 +207,31 @@ class StoreProductRequest extends FormRequest 'nutritional_values.*.unit' => trans('validation.attributes.nutritional_values_unit'), ]; } + + protected function storeFile(UploadedFile $file): StorageFilePath + { + return $this->storageService->storeUploadedOntoDisk( + $file, + $this->s3Disk->disk + ); + } + + protected function mixedToString(mixed $value): string + { + if (! is_scalar($value)) { + throw new \InvalidArgumentException('Value must be scalar to convert to string.'); + } + + return (string) $value; + } + + /** @return array */ + protected function mixedToArray(mixed $value): array + { + if (! is_array($value)) { + throw new \InvalidArgumentException('Value must be an array to convert to array.'); + } + + return $value; + } } diff --git a/app/Http/Requests/Back/Products/UpdateProductRequest.php b/app/Http/Requests/Back/Products/UpdateProductRequest.php index 117468d9..29f83b01 100644 --- a/app/Http/Requests/Back/Products/UpdateProductRequest.php +++ b/app/Http/Requests/Back/Products/UpdateProductRequest.php @@ -4,10 +4,97 @@ declare(strict_types=1); namespace App\Http\Requests\Back\Products; +use App\Cqs\Actions\Products\Update\UpdateProductInput; +use App\Models\Product; +use Domain\Models\ValueObjects\Products\BreedingMethod; +use Domain\Models\ValueObjects\Products\Business; +use Domain\Models\ValueObjects\Products\NutritionnalUnit; +use Domain\Models\ValueObjects\Products\ProductCategory; +use Domain\Models\ValueObjects\Products\ProductFormat; +use Domain\Models\ValueObjects\Products\Technology; +use Illuminate\Support\Arr; use Illuminate\Validation\Rule; +use Illuminate\Validation\ValidationException; +use Uwil\Storage\Lib\ValueObjects\StorageFilePath; class UpdateProductRequest extends StoreProductRequest { + public function toUpdateProductInput(?Product $product = null): UpdateProductInput + { + $product ??= $this->route('product'); + if (! $product instanceof Product) { + throw ValidationException::withMessages([ + 'product' => ['The product is invalid.'], + ]); + } + + $picture = null; + if ($this->hasFile('picture')) { + $picture = $this->storeFile($this->file('picture')); + } elseif ($this->filled('picture')) { + $picture = new StorageFilePath($this->string('picture')->value()); + } elseif ($product->picture !== null) { + $picture = $product->picture; + } + + $pdf = null; + if ($this->hasFile('pdf')) { + $pdf = $this->storeFile($this->file('pdf')); + } elseif ($this->filled('pdf')) { + $pdf = new StorageFilePath($this->string('pdf')->value()); + } + + return new UpdateProductInput( + id: $product->getId(), + name: $this->string('name')->trim()->value(), + seoTitle: $this->string('seo_title')->trim()->value(), + seoDescription: $this->string('seo_description')->trim()->value(), + category: $this->enum('category', ProductCategory::class, ProductCategory::HARD_BOILED_EGGS), + technology: $this->enum('technology', Technology::class, Technology::FRESH), + isEgalim: $this->boolean('is_egalim'), + breedingMethods: array_map( + fn ($method) => BreedingMethod::from( + $this->mixedToString($method) + ), + $this->array('breeding_methods') + ), + businesses: array_map( + fn ($business) => Business::from( + $this->mixedToString($business) + ), + $this->array('businesses') + ), + formats: array_map( + fn ($format) => ProductFormat::from( + $this->mixedToString($format) + ), + $this->array('formats') + ), + description: $this->string('description')->trim()->value(), + detailsAndAdvantages: $this->string('details_and_advantages')->trim()->value(), + handlingAdvices: $this->string('handling_advices')->trim()->value(), + ingredients: $this->filled('ingredients') ? $this->string('ingredients')->trim()->value() : null, + conservationBeforeOpening: $this->string('conservation_before_opening')->trim()->value(), + conservationAfterOpening: $this->filled('conservation_after_opening') ? + $this->string('conservation_after_opening')->trim()->value() : null, + picture: $picture, + pictureAlt: $this->string('picture_alt')->trim()->value(), + pictureTitle: $this->string('picture_title')->trim()->value(), + pdf: $pdf, + nutritionalValues: array_map( + function ($value) { + $value = $this->mixedToArray($value); + + return [ + 'unit' => NutritionnalUnit::from(Arr::string($value, 'unit')), + 'value' => Arr::string($value, 'value'), + ]; + }, + $this->array('nutritional_values') + ), + ); + } + public function rules(): array { return array_merge(parent::rules(), [ diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 31a95558..8c4f720a 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -6,12 +6,14 @@ namespace App\Providers; use App\Contracts\Directories\ProductDirectory; use App\Contracts\Directories\RecipeDirectory; +use App\Contracts\Executor; use App\Directories\EloquentProductDirectory; use App\Directories\EloquentRecipeDirectory; use App\Enums\Contact\ActivitySectorEnum; use App\Enums\Contact\ObjectEnum; use App\Lib\PrivateS3Disk; use App\Lib\PublicS3Disk; +use App\Services\ActionExecutorService; use App\Services\AdminAuthService; use Domain\Models\ValueObjects\Pagination; use Domain\Models\ValueObjects\Products\BreedingMethod; @@ -22,6 +24,7 @@ use Domain\Models\ValueObjects\Products\Technology; use Domain\Models\ValueObjects\Recipes\ConsumptionTime; use Domain\Models\ValueObjects\Recipes\Inspiration; use Domain\Models\ValueObjects\Recipes\Season; +use Illuminate\Contracts\Foundation\Application; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Config; @@ -50,7 +53,9 @@ class AppServiceProvider extends ServiceProvider ); $this->app->singleton( ProductDirectory::class, - fn () => new EloquentProductDirectory() + fn (Application $app) => new EloquentProductDirectory( + $app->make(PublicS3Disk::class) + ) ); $this->app->singleton( RecipeDirectory::class, @@ -67,6 +72,8 @@ class AppServiceProvider extends ServiceProvider ) ); + $this->app->bind(Executor::class, ActionExecutorService::class); + $this->requestMacro(); } diff --git a/app/Services/ActionExecutorService.php b/app/Services/ActionExecutorService.php new file mode 100644 index 00000000..0c41d463 --- /dev/null +++ b/app/Services/ActionExecutorService.php @@ -0,0 +1,117 @@ +logger?->info("[{$type}] Executing {$actionName}", [ + 'action' => $executableClass, + 'input' => $input::class, + ]); + + try { + if ($executable instanceof Action) { + $this->assertInputIsAction($input); + + return $this->executeWithinTransaction( + $executable, + $input, + $actionName + ); + } + + $this->assertInputIsQuery($input); + + return $this->executeWithoutTransaction( + $executable, + $input, + $actionName + ); + } catch (\Throwable $e) { + $this->logger?->error("[{$type}] Failed {$actionName}: {$e->getMessage()}", [ + 'action' => $executableClass, + 'input' => $input::class, + 'message' => $e->getMessage(), + 'exception' => $e, + ]); + + throw $e; + } + } + + /** + * @template TQuery of Query + * @template TQueryInput of QueryInput + * + * @param TQuery $executable + * @param TQueryInput $input + */ + private function executeWithoutTransaction(Query $executable, QueryInput $input, string $actionName): mixed + { + $result = $executable($input); + + $this->logger?->info("[Query] Succeeded {$actionName}"); + + return $result; + } + + /** + * @template TAction of Action + * @template TActionInput of ActionInput + * + * @param TAction $executable + * @param TActionInput $input + */ + private function executeWithinTransaction(Action $executable, ActionInput $input, string $actionName): mixed + { + return DB::transaction(function () use ($executable, $input, $actionName): mixed { + $result = $executable($input); + + $this->logger?->info("[Action] Succeeded {$actionName}"); + + return $result; + }); + } + + /** + * @psalm-assert QueryInput $input + */ + private function assertInputIsQuery(mixed $input): void + { + if (! $input instanceof QueryInput) { + throw new \InvalidArgumentException('Input must be an instance of QueryInput.'); + } + } + + /** + * @psalm-assert ActionInput $input + */ + private function assertInputIsAction(mixed $input): void + { + if (! $input instanceof ActionInput) { + throw new \InvalidArgumentException('Input must be an instance of ActionInput.'); + } + } +} diff --git a/composer.json b/composer.json index ab69e686..3cc3229e 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,8 @@ "uwil/k8s-laravel": "^3.0", "uwil/laravel-admin-secure": "^6.0.1", "uwil/laravel-dynamic-pages": "^5.0", - "uwil/storage-laravel": "^1.0" + "uwil/storage-laravel": "^1.0", + "webmozart/assert": "^2.5" }, "require-dev": { "barryvdh/laravel-ide-helper": "^3.7", diff --git a/composer.lock b/composer.lock index 1ee700a0..122e76e2 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "0aa1e48d61e00e2c6e541692a40fb7b9", + "content-hash": "1e5f5a5ce4a789d4537599c310129986", "packages": [ { "name": "aws/aws-crt-php", @@ -9225,6 +9225,72 @@ } ], "time": "2026-04-26T05:33:54+00:00" + }, + { + "name": "webmozart/assert", + "version": "2.5.0", + "source": { + "type": "git", + "url": "https://github.com/webmozarts/assert.git", + "reference": "8a163706bbcac613733dba03f51e13b5eb1bb819" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/webmozarts/assert/zipball/8a163706bbcac613733dba03f51e13b5eb1bb819", + "reference": "8a163706bbcac613733dba03f51e13b5eb1bb819", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-date": "*", + "ext-filter": "*", + "php": "^8.2" + }, + "suggest": { + "ext-intl": "", + "ext-simplexml": "", + "ext-spl": "" + }, + "type": "library", + "extra": { + "psalm": { + "pluginClass": "Webmozart\\Assert\\PsalmPlugin" + }, + "branch-alias": { + "dev-master": "2.0-dev", + "dev-feature/2-0": "2.0-dev" + } + }, + "autoload": { + "psr-4": { + "Webmozart\\Assert\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + }, + { + "name": "Woody Gilk", + "email": "woody.gilk@gmail.com" + } + ], + "description": "Assertions to validate method input/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "support": { + "issues": "https://github.com/webmozarts/assert/issues", + "source": "https://github.com/webmozarts/assert/tree/2.5.0" + }, + "time": "2026-10-05T23:14:19+00:00" } ], "packages-dev": [ diff --git a/domain/Models/Entities/Product.php b/domain/Models/Entities/Product.php index 887a7c45..b055c4f4 100644 --- a/domain/Models/Entities/Product.php +++ b/domain/Models/Entities/Product.php @@ -15,6 +15,12 @@ use Shared\DDD\Entity; */ readonly class Product implements Entity { + /** + * @param \Domain\Models\ValueObjects\Products\BreedingMethod[] $breedingMethods + * @param \Domain\Models\ValueObjects\Products\Business[] $businesses + * @param \Domain\Models\ValueObjects\Products\ProductFormat[] $formats + * @param \Ramsey\Uuid\UuidInterface[] $associatedRecipes + */ public function __construct( public ProductId $id, public string $name, @@ -22,12 +28,9 @@ readonly class Product implements Entity public ProductCategory $category, public Technology $technology, public bool $isEgalim, - /** @var \Domain\Models\ValueObjects\Products\BreedingMethod[] */ public array $breedingMethods, - /** @var \Domain\Models\ValueObjects\Products\Business[] */ public array $businesses, public string $detailsAndAdvantages, - /** @var \Domain\Models\ValueObjects\Products\ProductFormat[] */ public array $formats, public string $handlingAdvices, public ?string $ingredients, diff --git a/app/Dtos/ProductSummary.php b/domain/Models/ValueObjects/Products/ProductSummary.php similarity index 81% rename from app/Dtos/ProductSummary.php rename to domain/Models/ValueObjects/Products/ProductSummary.php index adc6cd85..ceb227be 100644 --- a/app/Dtos/ProductSummary.php +++ b/domain/Models/ValueObjects/Products/ProductSummary.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace App\Dtos; +namespace Domain\Models\ValueObjects\Products; final readonly class ProductSummary { diff --git a/resources/ts/front/Pages/Products/Index.tsx b/resources/ts/front/Pages/Products/Index.tsx index 5ae9df57..d681dd0b 100644 --- a/resources/ts/front/Pages/Products/Index.tsx +++ b/resources/ts/front/Pages/Products/Index.tsx @@ -214,9 +214,8 @@ export default function Index() { ) : null; const productCards = visibleProducts.map((product) => { - const pictureSrc = product.picture - ? `/${product.picture}` - : "/assets/img/placeholder.jpg"; + const pictureSrc = + product.picture ?? "/assets/img/placeholder.jpg"; return (
{ - const pictureSrc = product.picture - ? `/${product.picture}` - : "/assets/img/placeholder.jpg"; + const pictureSrc = + product.picture ?? "/assets/img/placeholder.jpg"; return (
@@ -456,7 +454,7 @@ export default function Show({ {product.pdfFilePath && (
({ image: { - src: p.picture - ? `/${p.picture}` - : "/assets/img/placeholder.jpg", + src: p.picture ?? "/assets/img/placeholder.jpg", alt: p.name, }, title: { text: p.name }, diff --git a/resources/ts/front/schemas/product.schema.ts b/resources/ts/front/schemas/product.schema.ts index 6b6d479e..7c4ea865 100644 --- a/resources/ts/front/schemas/product.schema.ts +++ b/resources/ts/front/schemas/product.schema.ts @@ -48,10 +48,10 @@ export const ProductSchema = zod.object({ conservationBeforeOpening: zod.string(), conservationAfterOpening: zod.string().nullable(), nutritionalValues: NutritionalValuesSchema.nullable(), - picture: zod.string().nullable(), + picture: zod.url().nullable(), pictureAlt: zod.string().nullable(), pictureTitle: zod.string().nullable(), - pdfFilePath: zod.string().nullable(), + pdfFilePath: zod.url().nullable(), associatedRecipes: zod.array(zod.uuid()), }); diff --git a/routes/web-front.php b/routes/web-front.php index ca608bbf..9b20c104 100644 --- a/routes/web-front.php +++ b/routes/web-front.php @@ -4,7 +4,6 @@ declare(strict_types=1); use App\Http\Controllers\Front\ProductController; use App\Http\Controllers\Front\RecipeController; -use App\Http\Controllers\MediaController; use Illuminate\Support\Facades\Route; use Inertia\Inertia; @@ -42,8 +41,6 @@ Route::name('recipes.')->prefix('recettes')->group(function () { Route::get('/{recipe}', [RecipeController::class, 'show'])->name('show'); }); -Route::get('/media/{path}', MediaController::class)->where('path', '.*'); - if (! app()->isProduction()) { Route::get('/demo', function () { return Inertia::render('front/Pages/Demo');