diff --git a/app/Actions/Discounts/CreateDiscount.php b/app/Actions/Discounts/CreateDiscount.php new file mode 100644 index 00000000..d731e330 --- /dev/null +++ b/app/Actions/Discounts/CreateDiscount.php @@ -0,0 +1,56 @@ + + */ +final class CreateDiscount implements Action +{ + /** + * @param \App\Actions\Discounts\CreateDiscountInput $input + */ + public function __invoke(ActionInput $input): Discount + { + Assert::isInstanceOf($input, CreateDiscountInput::class); + + $discount = new Discount(); + $discount->type = $input->type; + $discount->value = $input->value; + $discount->is_old_price_displayed = $input->is_old_price_displayed; + $discount->date_start = $input->period->start !== null ? Carbon::instance($input->period->start) : null; + $discount->date_end = $input->period->end !== null ? Carbon::instance($input->period->end) : null; + + $discount->saveOrFail(); + + $this->syncAssociatedProducts($discount, $input->associatedProductsIds); + + return $discount; + } + + /** + * @param array $productIdList + */ + private function syncAssociatedProducts(Discount $discount, array $productIdList): void + { + Product::query() + ->where('discount_id', $discount->id) + ->whereNotIn('id', $productIdList) + ->update(['discount_id' => null]); + + if (! empty($productIdList)) { + Product::query() + ->whereIn('id', $productIdList) + ->update(['discount_id' => $discount->id]); + } + } +} diff --git a/app/Actions/Discounts/CreateDiscountInput.php b/app/Actions/Discounts/CreateDiscountInput.php new file mode 100644 index 00000000..4792a00f --- /dev/null +++ b/app/Actions/Discounts/CreateDiscountInput.php @@ -0,0 +1,28 @@ + $associatedProductsIds + */ + public function __construct( + public DiscountType $type, + public DiscountValue $value, + public bool $is_old_price_displayed, + public DatePeriod $period = new DatePeriod(), + public array $associatedProductsIds = [], + ) { + Assert::same($this->type, $this->value->type, 'The discount value type must match the discount type.'); + Assert::allString($this->associatedProductsIds); + } +} diff --git a/app/Actions/Discounts/DeleteDiscount.php b/app/Actions/Discounts/DeleteDiscount.php new file mode 100644 index 00000000..b4f91e46 --- /dev/null +++ b/app/Actions/Discounts/DeleteDiscount.php @@ -0,0 +1,25 @@ + + */ +final class DeleteDiscount implements Action +{ + /** + * @param \App\Actions\Discounts\DeleteDiscountInput $input + */ + public function __invoke(ActionInput $input): bool + { + Assert::isInstanceOf($input, DeleteDiscountInput::class); + + return (bool) $input->discount->deleteOrFail(); + } +} diff --git a/app/Actions/Discounts/DeleteDiscountInput.php b/app/Actions/Discounts/DeleteDiscountInput.php new file mode 100644 index 00000000..f256f40b --- /dev/null +++ b/app/Actions/Discounts/DeleteDiscountInput.php @@ -0,0 +1,16 @@ + + */ +final class UpdateDiscount implements Action +{ + /** + * @param \App\Actions\Discounts\UpdateDiscountInput $input + */ + public function __invoke(ActionInput $input): Discount + { + Assert::isInstanceOf($input, UpdateDiscountInput::class); + + $discount = $input->discount; + $discount->type = $input->type; + $discount->value = $input->value; + $discount->is_old_price_displayed = $input->is_old_price_displayed; + $discount->date_start = $input->period->start !== null ? Carbon::instance($input->period->start) : null; + $discount->date_end = $input->period->end !== null ? Carbon::instance($input->period->end) : null; + + $discount->saveOrFail(); + + $this->syncAssociatedProducts($discount, $input->associatedProductsIds); + + return $discount; + } + + /** + * @param array $productIdList + */ + private function syncAssociatedProducts(Discount $discount, array $productIdList): void + { + Product::query() + ->where('discount_id', $discount->id) + ->whereNotIn('id', $productIdList) + ->update(['discount_id' => null]); + + if (! empty($productIdList)) { + Product::query() + ->whereIn('id', $productIdList) + ->update(['discount_id' => $discount->id]); + } + } +} diff --git a/app/Actions/Discounts/UpdateDiscountInput.php b/app/Actions/Discounts/UpdateDiscountInput.php new file mode 100644 index 00000000..f8ed9d86 --- /dev/null +++ b/app/Actions/Discounts/UpdateDiscountInput.php @@ -0,0 +1,30 @@ + $associatedProductsIds + */ + public function __construct( + public Discount $discount, + public DiscountType $type, + public DiscountValue $value, + public bool $is_old_price_displayed, + public DatePeriod $period = new DatePeriod(), + public array $associatedProductsIds = [], + ) { + Assert::same($this->type, $this->value->type, 'The discount value type must match the discount type.'); + Assert::allString($this->associatedProductsIds); + } +} diff --git a/app/Dto/DiscountDto.php b/app/Dto/DiscountDto.php new file mode 100644 index 00000000..b6270404 --- /dev/null +++ b/app/Dto/DiscountDto.php @@ -0,0 +1,86 @@ + + */ +final readonly class DiscountDto implements Arrayable, UrlRoutable +{ + public function __construct( + public int $id, + public DiscountType $type, + public DiscountValue $value, + public bool $is_old_price_displayed, + public ?Carbon $date_start = null, + public ?Carbon $date_end = null, + public ?Carbon $created_at = null, + public ?Carbon $updated_at = null, + ) { + } + + public static function fromModel(Discount $discount): self + { + return new self( + id: $discount->id, + type: $discount->type, + value: $discount->value, + is_old_price_displayed: $discount->is_old_price_displayed, + date_start: $discount->date_start, + date_end: $discount->date_end, + created_at: $discount->created_at, + updated_at: $discount->updated_at, + ); + } + + #[\Override] + public function getRouteKey(): mixed + { + return $this->id; + } + + #[\Override] + public function getRouteKeyName(): string + { + return 'id'; + } + + #[\Override] + public function resolveRouteBinding($value, $field = null): mixed + { + return null; + } + + #[\Override] + public function resolveChildRouteBinding($childType, $value, $field): mixed + { + return null; + } + + /** + * @return array + */ + #[\Override] + public function toArray(): array + { + return [ + 'id' => $this->id, + 'type' => $this->type->value(), + 'value' => $this->value->value(), + 'is_old_price_displayed' => $this->is_old_price_displayed, + 'date_start' => $this->date_start, + 'date_end' => $this->date_end, + 'created_at' => $this->created_at, + 'updated_at' => $this->updated_at, + ]; + } +} diff --git a/app/Dto/DiscountProductDto.php b/app/Dto/DiscountProductDto.php new file mode 100644 index 00000000..ce592521 --- /dev/null +++ b/app/Dto/DiscountProductDto.php @@ -0,0 +1,49 @@ + + */ +final readonly class DiscountProductDto implements \JsonSerializable, Arrayable +{ + public function __construct( + public string $id, + public string $name, + ) { + } + + public static function fromModel(Product $product): self + { + return new self( + id: (string) $product->id, + name: (string) $product->name, + ); + } + + /** + * @return array{id: string, name: string} + */ + #[\Override] + public function toArray(): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + ]; + } + + /** + * @return array{id: string, name: string} + */ + #[\Override] + public function jsonSerialize(): array + { + return $this->toArray(); + } +} diff --git a/app/Http/Controllers/Bo/DiscountsController.php b/app/Http/Controllers/Bo/DiscountsController.php index a05d4e60..7e14b17a 100644 --- a/app/Http/Controllers/Bo/DiscountsController.php +++ b/app/Http/Controllers/Bo/DiscountsController.php @@ -4,171 +4,137 @@ declare(strict_types=1); namespace App\Http\Controllers\Bo; +use App\Actions\Discounts\CreateDiscount; +use App\Actions\Discounts\CreateDiscountInput; +use App\Actions\Discounts\DeleteDiscount; +use App\Actions\Discounts\DeleteDiscountInput; +use App\Actions\Discounts\UpdateDiscount; +use App\Actions\Discounts\UpdateDiscountInput; +use App\Contracts\Executor; use App\Http\Controllers\Controller; use App\Http\Requests\Bo\Discounts\StoreDiscountRequest; use App\Http\Requests\Bo\Discounts\UpdateDiscountRequest; use App\Models\Discount; -use App\Models\Product; -use App\Services\DataTableService; -use App\Traits\Controllers\ChangesModelOrder; -use App\Traits\Controllers\TogglesModelStatus; -use Domain\Enums\DiscountType; +use App\Queries\Discounts\GetDiscountFormDataQuery; +use App\Queries\Discounts\GetDiscountFormDataQueryInput; +use App\Queries\Discounts\GetPaginatedDiscountsQuery; +use App\Queries\Discounts\GetPaginatedDiscountsQueryInput; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; -use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; class DiscountsController extends Controller { - use ChangesModelOrder; - use TogglesModelStatus; + public function __construct( + private readonly Executor $executor, + ) { + } - public function index(Request $request, DataTableService $dataTable): View + public function index(Request $request, GetPaginatedDiscountsQuery $query): View { $this->authorize('viewAny', Discount::class); - $query = Discount::query(); - - $dataTable->sortQuery(Discount::class, $query); - $pagination = $request->pagination(); - $discounts = $dataTable->paginateQuery($query, $pagination); + + $discounts = $this->executor->execute( + $query, + new GetPaginatedDiscountsQueryInput( + pagination: $pagination, + ) + ); return view('bo.discounts.index', compact('discounts')); } - public function create(): View + public function create(GetDiscountFormDataQuery $query): View { $this->authorize('create', Discount::class); - $discountTypes = DiscountType::cases(); - $existingProds = Product::query() - ->select(['id', 'name']) - ->orderBy('name') - ->get(); - $selectedProds = []; + $formData = $this->executor->execute( + $query, + new GetDiscountFormDataQueryInput() + ); - return view('bo.discounts.create', compact( - 'discountTypes', - 'existingProds', - 'selectedProds' - )); + return view('bo.discounts.create', [ + 'discountTypes' => $formData->discountTypes, + 'existingProds' => $formData->existingProds, + 'selectedProds' => $formData->selectedProds, + ]); } - public function store(StoreDiscountRequest $request): RedirectResponse + public function store(StoreDiscountRequest $request, CreateDiscount $action): RedirectResponse { $this->authorize('create', Discount::class); - return DB::transaction(function () use ($request) { - $discount = new Discount(); - $discount->fill($request->only( - $discount->getFillable() - )); - $discount->value = $request->getDiscountValue(); + $discount = $this->executor->execute( + $action, + new CreateDiscountInput( + type: $request->toDiscountType(), + value: $request->toDiscountValue(), + is_old_price_displayed: $request->boolean('is_old_price_displayed'), + period: $request->toDatePeriod(), + associatedProductsIds: $request->toAssociatedProductsIds(), + ), + ); - if ($discount->saveOrFail()) { - $this->syncAssociatedProducts( - $request->getAssociatedProductsIds(), - $discount - ); - - return to_route('bo.discounts.edit', $discount) - ->with('success', trans('crud.messages.has_been_created', [ - 'model' => Str::ucfirst(trans_choice('models.classes.discounts', 1)), - ])); - } - - return to_route('bo.discounts.create') - ->with('error', trans('crud.messages.cannot_be_created', [ - 'model' => Str::ucfirst(trans_choice('models.classes.discounts', 1)), - ])); - }); + return to_route('bo.discounts.edit', $discount) + ->with('success', trans('crud.messages.has_been_created', [ + 'model' => Str::ucfirst(trans_choice('models.classes.discounts', 1)), + ])); } - public function edit(Discount $discount): View + public function edit(Discount $discount, GetDiscountFormDataQuery $query): View { $this->authorize('update', $discount); - $discountTypes = DiscountType::cases(); + $formData = $this->executor->execute( + $query, + new GetDiscountFormDataQueryInput($discount) + ); - $selectedProds = $discount->products() - ->select(['products.id', 'products.name']) - ->get(); - $existingProds = Product::query() - ->select(['id', 'name']) - ->whereNotIn('id', $selectedProds->pluck('id')) - ->orderBy('name') - ->get(); - - return view('bo.discounts.edit', compact( - 'discount', - 'discountTypes', - 'existingProds', - 'selectedProds', - )); + return view('bo.discounts.edit', [ + 'discount' => $formData->discount, + 'discountTypes' => $formData->discountTypes, + 'existingProds' => $formData->existingProds, + 'selectedProds' => $formData->selectedProds, + ]); } - public function update(UpdateDiscountRequest $request, Discount $discount): RedirectResponse + public function update(UpdateDiscountRequest $request, Discount $discount, UpdateDiscount $action): RedirectResponse { $this->authorize('update', $discount); - return DB::transaction(function () use ($request, $discount) { - $discount->fill($request->only( - $discount->getFillable() - )); + $this->executor->execute( + $action, + new UpdateDiscountInput( + discount: $discount, + type: $request->toDiscountType(), + value: $request->toDiscountValue(), + is_old_price_displayed: $request->boolean('is_old_price_displayed'), + period: $request->toDatePeriod(), + associatedProductsIds: $request->toAssociatedProductsIds(), + ), + ); - $discount->value = $request->getDiscountValue(); - - $this->syncAssociatedProducts( - $request->getAssociatedProductsIds(), - $discount - ); - - if ($discount->saveOrFail()) { - return to_route('bo.discounts.edit', $discount) - ->with('success', trans('crud.messages.has_been_updated', [ - 'model' => Str::ucfirst(trans_choice('models.classes.discounts', 1)), - ])); - } - - return to_route('bo.discounts.edit', $discount) - ->with('error', trans('crud.messages.cannot_be_updated', [ - 'model' => Str::ucfirst(trans_choice('models.classes.discounts', 1)), - ])); - }); + return to_route('bo.discounts.edit', $discount) + ->with('success', trans('crud.messages.has_been_updated', [ + 'model' => Str::ucfirst(trans_choice('models.classes.discounts', 1)), + ])); } - public function destroy(Discount $discount): RedirectResponse + public function destroy(Discount $discount, DeleteDiscount $action): RedirectResponse { $this->authorize('delete', $discount); - return DB::transaction(function () use ($discount) { - if ($discount->deleteOrFail()) { - return to_route('bo.discounts.index') - ->with('warning', trans('crud.messages.has_been_deleted', [ - 'model' => Str::ucfirst(trans_choice('models.classes.discounts', 1)), - ])); - } + $this->executor->execute( + $action, + new DeleteDiscountInput(discount: $discount), + ); - return to_route('bo.discounts.edit', $discount) - ->with('error', trans('crud.messages.cannot_be_deleted', [ - 'model' => Str::ucfirst(trans_choice('models.classes.discounts', 1)), - ])); - }); - } - - /** @param array $productIdList */ - private function syncAssociatedProducts(array $productIdList, Discount $discount): void - { - $discount->products() - ->whereNotIn('id', $productIdList) - ->update(['discount_id' => null]); - - if (! empty($productIdList)) { - Product::query() - ->whereIn('id', $productIdList) - ->update(['discount_id' => $discount->id]); - } + return to_route('bo.discounts.index') + ->with('warning', trans('crud.messages.has_been_deleted', [ + 'model' => Str::ucfirst(trans_choice('models.classes.discounts', 1)), + ])); } } diff --git a/app/Http/Requests/Bo/Discounts/StoreDiscountRequest.php b/app/Http/Requests/Bo/Discounts/StoreDiscountRequest.php index a2d8be86..84976446 100644 --- a/app/Http/Requests/Bo/Discounts/StoreDiscountRequest.php +++ b/app/Http/Requests/Bo/Discounts/StoreDiscountRequest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Http\Requests\Bo\Discounts; use Domain\Enums\DiscountType; +use Domain\Models\ValueObjects\DatePeriod; use Domain\Models\ValueObjects\DiscountValue; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Date; @@ -44,6 +45,18 @@ class StoreDiscountRequest extends FormRequest ); } + /** @return array */ + public function toAssociatedProductsIds(): array + { + return $this->getAssociatedProductsIds(); + } + + public function toDiscountType(): DiscountType + { + /** @var DiscountType */ + return $this->enum('type', DiscountType::class); + } + public function getDiscountValue(): DiscountValue { $type = $this->enum('type', DiscountType::class); @@ -62,6 +75,23 @@ class StoreDiscountRequest extends FormRequest ); } + public function toDiscountValue(): DiscountValue + { + return $this->getDiscountValue(); + } + + public function toDatePeriod(): DatePeriod + { + $start = $this->filled('date_start') + ? new \DateTimeImmutable($this->string('date_start')->value(), new \DateTimeZone('UTC')) + : null; + $end = $this->filled('date_end') + ? new \DateTimeImmutable($this->string('date_end')->value(), new \DateTimeZone('UTC')) + : null; + + return new DatePeriod($start, $end); + } + /** @return array */ public function rules(): array { diff --git a/app/Policies/Backend/DiscountPolicy.php b/app/Policies/Backend/DiscountPolicy.php index 5dd04ff2..633514c7 100644 --- a/app/Policies/Backend/DiscountPolicy.php +++ b/app/Policies/Backend/DiscountPolicy.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Policies\Backend; +use App\Dto\DiscountDto; use App\Models\Customer; use App\Models\Discount; use App\Models\User; @@ -20,7 +21,7 @@ class DiscountPolicy return $user->role->isAtLeastEqualsTo(UserRole::Admin); } - public function view(Customer | User $user, Discount $_): bool + public function view(Customer | User $user, Discount | DiscountDto $_): bool { if ($user instanceof Customer) { return false; @@ -38,7 +39,7 @@ class DiscountPolicy return $user->role->isAtLeastEqualsTo(UserRole::Admin); } - public function update(Customer | User $user, Discount $_): bool + public function update(Customer | User $user, Discount | DiscountDto $_): bool { if ($user instanceof Customer) { return false; @@ -47,7 +48,7 @@ class DiscountPolicy return $user->role->isAtLeastEqualsTo(UserRole::Admin); } - public function delete(Customer | User $user, Discount $_): bool + public function delete(Customer | User $user, Discount | DiscountDto $_): bool { if ($user instanceof Customer) { return false; diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index df6cec17..6fb548d9 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Providers; +use App\Dto\DiscountDto; use App\Dto\FaqDto; use App\Dto\PageDto; use App\Dto\PickupExceptionDto; @@ -12,6 +13,7 @@ use App\Dto\ShopDto; use App\Dto\SlideDto; use App\Dto\TagDto; use App\Models\Customer; +use App\Policies\Backend\DiscountPolicy; use App\Policies\Backend\FaqPolicy; use App\Policies\Backend\PagePolicy; use App\Policies\Backend\PickupExceptionPolicy; @@ -42,6 +44,7 @@ class AuthServiceProvider extends ServiceProvider protected $policies = [ // * Policies Exceptions BasketProduct::class => BasketPolicy::class, + DiscountDto::class => DiscountPolicy::class, FaqDto::class => FaqPolicy::class, PageDto::class => PagePolicy::class, PickupExceptionDto::class => PickupExceptionPolicy::class, diff --git a/app/Queries/Discounts/GetDiscountFormDataQuery.php b/app/Queries/Discounts/GetDiscountFormDataQuery.php new file mode 100644 index 00000000..40d105ce --- /dev/null +++ b/app/Queries/Discounts/GetDiscountFormDataQuery.php @@ -0,0 +1,64 @@ + + */ +final readonly class GetDiscountFormDataQuery implements Query +{ + /** + * @param \App\Queries\Discounts\GetDiscountFormDataQueryInput $input + */ + #[\Override] + public function __invoke(QueryInput $input): GetDiscountFormDataQueryOutput + { + Assert::isInstanceOf($input, GetDiscountFormDataQueryInput::class); + + $discountTypes = DiscountType::cases(); + + if ($input->discount !== null) { + $selectedProds = Product::query() + ->select(['id', 'name']) + ->where('discount_id', $input->discount->id) + ->orderBy('name') + ->get() + ->map(fn (Product $p): DiscountProductDto => DiscountProductDto::fromModel($p)); + + $existingProds = Product::query() + ->select(['id', 'name']) + ->whereNotIn('id', $selectedProds->pluck('id')) + ->orderBy('name') + ->get() + ->map(fn (Product $p): DiscountProductDto => DiscountProductDto::fromModel($p)); + + $discountDto = DiscountDto::fromModel($input->discount); + } else { + $selectedProds = collect(); + $existingProds = Product::query() + ->select(['id', 'name']) + ->orderBy('name') + ->get() + ->map(fn (Product $p): DiscountProductDto => DiscountProductDto::fromModel($p)); + + $discountDto = null; + } + + return new GetDiscountFormDataQueryOutput( + discount: $discountDto, + discountTypes: $discountTypes, + existingProds: $existingProds, + selectedProds: $selectedProds, + ); + } +} diff --git a/app/Queries/Discounts/GetDiscountFormDataQueryInput.php b/app/Queries/Discounts/GetDiscountFormDataQueryInput.php new file mode 100644 index 00000000..1d283ed1 --- /dev/null +++ b/app/Queries/Discounts/GetDiscountFormDataQueryInput.php @@ -0,0 +1,16 @@ + $discountTypes + * @param Collection $existingProds + * @param Collection $selectedProds + */ + public function __construct( + public ?DiscountDto $discount, + public array $discountTypes, + public Collection $existingProds, + public Collection $selectedProds, + ) { + } +} diff --git a/app/Queries/Discounts/GetPaginatedDiscountsQuery.php b/app/Queries/Discounts/GetPaginatedDiscountsQuery.php new file mode 100644 index 00000000..639ae16b --- /dev/null +++ b/app/Queries/Discounts/GetPaginatedDiscountsQuery.php @@ -0,0 +1,42 @@ +> + */ +final readonly class GetPaginatedDiscountsQuery implements Query +{ + public function __construct( + private DataTableService $dataTable, + ) { + } + + /** + * @param \App\Queries\Discounts\GetPaginatedDiscountsQueryInput $input + * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator + */ + #[\Override] + public function __invoke(QueryInput $input): LengthAwarePaginator + { + Assert::isInstanceOf($input, GetPaginatedDiscountsQueryInput::class); + + $query = Discount::query(); + + $this->dataTable->sortQuery(Discount::class, $query); + + $paginator = $this->dataTable->paginateQuery($query, $input->pagination); + + return $paginator->through(fn (Discount $discount): DiscountDto => DiscountDto::fromModel($discount)); + } +} diff --git a/app/Queries/Discounts/GetPaginatedDiscountsQueryInput.php b/app/Queries/Discounts/GetPaginatedDiscountsQueryInput.php new file mode 100644 index 00000000..3b6ffc0f --- /dev/null +++ b/app/Queries/Discounts/GetPaginatedDiscountsQueryInput.php @@ -0,0 +1,16 @@ +
- @can('create', \App\Models\Slide::class) + @can('create', \App\Models\Discount::class) diff --git a/routes/breadcrumbs-bo.php b/routes/breadcrumbs-bo.php index 26a13832..86134088 100644 --- a/routes/breadcrumbs-bo.php +++ b/routes/breadcrumbs-bo.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use App\Dto\DiscountDto; use App\Dto\PageDto; use App\Dto\PickupExceptionDto; use App\Dto\RangeDto; @@ -143,7 +144,7 @@ Breadcrumbs::for('bo.discounts.create', function (Generator $trail) use ($creati $trail->parent('bo.discounts.index'); $trail->push($creationLabel); }); -Breadcrumbs::for('bo.discounts.edit', function (Generator $trail, Discount $discount) use ($editionLabel): void { +Breadcrumbs::for('bo.discounts.edit', function (Generator $trail, Discount | DiscountDto $discount) use ($editionLabel): void { $trail->parent('bo.discounts.index'); $trail->push($editionLabel, route('bo.discounts.edit', $discount)); }); diff --git a/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php index 32bbd1ea..c9648120 100644 --- a/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php @@ -2,32 +2,92 @@ declare(strict_types=1); +namespace Tests\Feature\App\Http\Controllers\Bo; + use App\Models\Customer; use App\Models\Discount; +use App\Models\Product; +use App\Models\Range; use App\Models\User; use Domain\Enums\DiscountType; +use Domain\Enums\ProductBrand; +use Domain\Enums\SellUnit; +use Domain\Enums\TaxRate; +use Domain\Enums\Units\InvoicingUnit; +use Domain\Enums\Units\OrderUnit; use Domain\Enums\UserRole; use Domain\Models\ValueObjects\DiscountValue; +use Money\Money; -describe('DiscountsController', function () { - beforeEach(function () { +describe('DiscountsController', function (): void { + beforeEach(function (): void { + /** @var \Tests\TestCase $this */ $this->user = User::factory()->create(['role' => UserRole::SuperAdmin]); $this->actingAs($this->user, 'backend'); + + $this->range = new Range(); + $this->range->name = 'Gamme ' . uniqid(); + $this->range->status = true; + $this->range->order = random_int(1, 9999); + $this->range->picture_alt = 'alt'; + $this->range->picture_title = 'title'; + $this->range->save(); }); - it('can access index', function () { + $createProduct = function (string $name, Range $range): Product { + $product = new Product([ + 'range_id' => $range->id, + 'name' => $name . ' ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => true, + ]); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(1000); + $product->short_description = 'Court'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->save(); + + return $product; + }; + + it('can access index', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + + // WHEN $response = $this->get('/bo/discounts'); + + // THEN expect($response->status())->toBe(200); $response->assertViewIs('bo.discounts.index'); }); - it('can access create', function () { + it('can access create', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + + // WHEN $response = $this->get('/bo/discounts/create'); + + // THEN expect($response->status())->toBe(200); $response->assertViewIs('bo.discounts.create'); }); - it('can store a discount', function () { + it('can store a discount with associated products', function () use ($createProduct): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $product1 = $createProduct('Produit 1', $this->range); + $product2 = $createProduct('Produit 2', $this->range); + $data = [ 'type' => DiscountType::PERCENT->value, 'value' => 15, @@ -35,37 +95,57 @@ describe('DiscountsController', function () { 'date_start' => null, 'date_end' => null, 'client_timezone' => 'UTC', - 'associated_products' => [], + 'associated_products' => [(string) $product1->id, (string) $product2->id], ]; + // WHEN $response = $this->post('/bo/discounts', $data); - $discount = Discount::first(); + // THEN + $discount = Discount::query()->first(); expect($discount)->not->toBeNull() - ->and($discount->type)->toBe(DiscountType::PERCENT); + ->and($discount?->type)->toBe(DiscountType::PERCENT) + ->and($discount?->value->getPercentage())->toBe(15); - $response->assertRedirect("/bo/discounts/{$discount->id}/edit"); + $freshProduct1 = Product::query()->find($product1->id); + $freshProduct2 = Product::query()->find($product2->id); + expect($freshProduct1?->discount_id)->toBe($discount?->id) + ->and($freshProduct2?->discount_id)->toBe($discount?->id); + + $response->assertRedirect("/bo/discounts/{$discount?->id}/edit"); }); - it('can access edit', function () { + it('can access edit', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN $discount = new Discount(); $discount->type = DiscountType::PERCENT; $discount->value = DiscountValue::fromPercentage(10); $discount->is_old_price_displayed = true; $discount->save(); + // WHEN $response = $this->get("/bo/discounts/{$discount->id}/edit"); + + // THEN expect($response->status())->toBe(200); $response->assertViewIs('bo.discounts.edit'); }); - it('can update a discount', function () { + it('can update a discount and sync products', function () use ($createProduct): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $product1 = $createProduct('P1', $this->range); + $product2 = $createProduct('P2', $this->range); + $discount = new Discount(); $discount->type = DiscountType::PERCENT; $discount->value = DiscountValue::fromPercentage(10); $discount->is_old_price_displayed = true; $discount->save(); + Product::query()->where('id', $product1->id)->update(['discount_id' => $discount->id]); + $data = [ 'type' => DiscountType::PERCENT->value, 'value' => 20, @@ -73,47 +153,66 @@ describe('DiscountsController', function () { 'date_start' => null, 'date_end' => null, 'client_timezone' => 'UTC', - 'associated_products' => [], + 'associated_products' => [(string) $product2->id], ]; + // WHEN $response = $this->put("/bo/discounts/{$discount->id}", $data); + // THEN $discount->refresh(); expect($discount->is_old_price_displayed)->toBeFalse() ->and($discount->value->getPercentage())->toBe(20); + $freshP1 = Product::query()->find($product1->id); + $freshP2 = Product::query()->find($product2->id); + expect($freshP1?->discount_id)->toBeNull() + ->and($freshP2?->discount_id)->toBe($discount->id); + $response->assertRedirect("/bo/discounts/{$discount->id}/edit"); }); - it('can delete a discount', function () { + it('can delete a discount', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN $discount = new Discount(); $discount->type = DiscountType::PERCENT; $discount->value = DiscountValue::fromPercentage(10); $discount->is_old_price_displayed = true; $discount->save(); + // WHEN $response = $this->delete("/bo/discounts/{$discount->id}"); + // THEN - expect(Discount::find($discount->id))->toBeNull(); + expect(Discount::query()->find($discount->id))->toBeNull(); $response->assertRedirect('/bo/discounts'); }); - describe('authorization rejections', function () { - it('redirects unauthenticated guest to login', function () { + describe('authorization rejections', function (): void { + it('redirects unauthenticated guest to login', function (): void { /** @var \Tests\TestCase $this */ + // GIVEN auth('backend')->logout(); + // WHEN $response = $this->get('/bo/discounts'); + + // THEN $response->assertRedirect('/bo/login'); }); - it('redirects frontend customer trying to access bo to login', function () { + it('redirects frontend customer trying to access bo to login', function (): void { /** @var \Tests\TestCase $this */ + // GIVEN auth('backend')->logout(); $customer = new Customer(); $this->actingAs($customer, 'frontend'); + // WHEN $response = $this->get('/bo/discounts'); + + // THEN $response->assertRedirect('/bo/login'); }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php index acf6fc2c..d2380260 100644 --- a/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Discounts/StoreDiscountRequestTest.php @@ -156,4 +156,31 @@ describe('StoreDiscountRequest', function () { expect($request->rules())->toHaveKeys(['type', 'value', 'is_old_price_displayed', 'date_start', 'date_end', 'associated_products']) ->and($request->attributes())->toHaveKeys(['type', 'value', 'is_old_price_displayed', 'date_start', 'date_end', 'associated_products']); }); + + it('returns domain Value Objects and typed properties via to* methods', function () { + // GIVEN + $authService = mock(AppAdminAuthService::class); + $request = new StoreDiscountRequest($authService); + $request->initialize(); + $request->merge([ + 'type' => DiscountType::PERCENT->value, + 'value' => 25, + 'associated_products' => ['prod-1', 'prod-2'], + 'date_start' => '2026-06-01 10:00:00', + 'date_end' => '2026-06-30 20:00:00', + ]); + + // WHEN + $type = $request->toDiscountType(); + $value = $request->toDiscountValue(); + $productIds = $request->toAssociatedProductsIds(); + $period = $request->toDatePeriod(); + + // THEN + expect($type)->toBe(DiscountType::PERCENT) + ->and($value->getPercentage())->toBe(25) + ->and($productIds)->toBe(['prod-1', 'prod-2']) + ->and($period->start?->format('Y-m-d H:i:s'))->toBe('2026-06-01 10:00:00') + ->and($period->end?->format('Y-m-d H:i:s'))->toBe('2026-06-30 20:00:00'); + }); }); diff --git a/tests/Integration/WithApp/App/Actions/Discounts/CreateDiscountTest.php b/tests/Integration/WithApp/App/Actions/Discounts/CreateDiscountTest.php new file mode 100644 index 00000000..69992ba4 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Discounts/CreateDiscountTest.php @@ -0,0 +1,138 @@ +range = new Range(); + $this->range->name = 'Gamme ' . uniqid(); + $this->range->status = true; + $this->range->order = random_int(1, 9999); + $this->range->picture_alt = 'alt'; + $this->range->picture_title = 'title'; + $this->range->save(); + }); + + $createProduct = function (string $name, Range $range): Product { + $product = new Product([ + 'range_id' => $range->id, + 'name' => $name . ' ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => true, + ]); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(1000); + $product->short_description = 'Court'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->save(); + + return $product; + }; + + it('creates and persists a percent discount in database with associated products', function () use ($createProduct): void { + // GIVEN + $product1 = $createProduct('Produit 1', $this->range); + $product2 = $createProduct('Produit 2', $this->range); + + $action = new CreateDiscount(); + $start = new \DateTimeImmutable('2026-06-01 10:00:00'); + $end = new \DateTimeImmutable('2026-06-30 20:00:00'); + $period = new DatePeriod($start, $end); + $value = DiscountValue::fromPercentage(20); + + $input = new CreateDiscountInput( + type: DiscountType::PERCENT, + value: $value, + is_old_price_displayed: true, + period: $period, + associatedProductsIds: [(string) $product1->id, (string) $product2->id], + ); + + // WHEN + $discount = $action($input); + + // THEN + expect($discount)->toBeInstanceOf(Discount::class) + ->and($discount->id)->toBeGreaterThan(0) + ->and($discount->type)->toBe(DiscountType::PERCENT) + ->and($discount->is_old_price_displayed)->toBeTrue() + ->and($discount->value->getPercentage())->toBe(20); + + $fresh = Discount::query()->find($discount->id); + expect($fresh)->not->toBeNull() + ->and($fresh?->type)->toBe(DiscountType::PERCENT); + + $freshProduct1 = Product::query()->find($product1->id); + $freshProduct2 = Product::query()->find($product2->id); + expect($freshProduct1?->discount_id)->toBe($discount->id) + ->and($freshProduct2?->discount_id)->toBe($discount->id); + }); + + it('creates and persists an amount discount in database', function (): void { + // GIVEN + $action = new CreateDiscount(); + $value = DiscountValue::fromAmount(new Money(1000, new Currency('EUR'))); + + $input = new CreateDiscountInput( + type: DiscountType::AMOUNT, + value: $value, + is_old_price_displayed: false, + ); + + // WHEN + $discount = $action($input); + + // THEN + expect($discount)->toBeInstanceOf(Discount::class) + ->and($discount->id)->toBeGreaterThan(0) + ->and($discount->type)->toBe(DiscountType::AMOUNT) + ->and($discount->is_old_price_displayed)->toBeFalse(); + + $fresh = Discount::query()->find($discount->id); + expect($fresh)->not->toBeNull() + ->and($fresh?->value->getAmount()->getAmount())->toBe('1000'); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new CreateDiscount(); + $invalidInput = new class () implements ActionInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Discounts/DeleteDiscountTest.php b/tests/Integration/WithApp/App/Actions/Discounts/DeleteDiscountTest.php new file mode 100644 index 00000000..69de5137 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Discounts/DeleteDiscountTest.php @@ -0,0 +1,100 @@ +range = new Range(); + $this->range->name = 'Gamme ' . uniqid(); + $this->range->status = true; + $this->range->order = random_int(1, 9999); + $this->range->picture_alt = 'alt'; + $this->range->picture_title = 'title'; + $this->range->save(); + }); + + $createProduct = function (string $name, Range $range): Product { + $product = new Product([ + 'range_id' => $range->id, + 'name' => $name . ' ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => true, + ]); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(1000); + $product->short_description = 'Court'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->save(); + + return $product; + }; + + it('deletes a discount and nullifies product discount_id', function () use ($createProduct): void { + // GIVEN + $product = $createProduct('P1', $this->range); + + $discount = new Discount(); + $discount->type = DiscountType::PERCENT; + $discount->value = DiscountValue::fromPercentage(15); + $discount->is_old_price_displayed = true; + $discount->save(); + + Product::query()->where('id', $product->id)->update(['discount_id' => $discount->id]); + + $action = new DeleteDiscount(); + $input = new DeleteDiscountInput(discount: $discount); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeTrue(); + + $freshDiscount = Discount::query()->find($discount->id); + expect($freshDiscount)->toBeNull(); + + $freshProduct = Product::query()->find($product->id); + expect($freshProduct?->discount_id)->toBeNull(); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new DeleteDiscount(); + $invalidInput = new class () implements ActionInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Actions/Discounts/UpdateDiscountTest.php b/tests/Integration/WithApp/App/Actions/Discounts/UpdateDiscountTest.php new file mode 100644 index 00000000..a7ce0701 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Discounts/UpdateDiscountTest.php @@ -0,0 +1,125 @@ +range = new Range(); + $this->range->name = 'Gamme ' . uniqid(); + $this->range->status = true; + $this->range->order = random_int(1, 9999); + $this->range->picture_alt = 'alt'; + $this->range->picture_title = 'title'; + $this->range->save(); + }); + + $createProduct = function (string $name, Range $range): Product { + $product = new Product([ + 'range_id' => $range->id, + 'name' => $name . ' ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => true, + ]); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(1000); + $product->short_description = 'Court'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->save(); + + return $product; + }; + + it('updates and persists a discount in database with synchronised products', function () use ($createProduct): void { + // GIVEN + $product1 = $createProduct('P1', $this->range); + $product2 = $createProduct('P2', $this->range); + $product3 = $createProduct('P3', $this->range); + + $discount = new Discount(); + $discount->type = DiscountType::PERCENT; + $discount->value = DiscountValue::fromPercentage(10); + $discount->is_old_price_displayed = true; + $discount->save(); + + Product::query()->whereIn('id', [$product1->id, $product2->id])->update(['discount_id' => $discount->id]); + + $action = new UpdateDiscount(); + $start = new \DateTimeImmutable('2026-07-01 10:00:00'); + $end = new \DateTimeImmutable('2026-07-31 20:00:00'); + $period = new DatePeriod($start, $end); + $value = DiscountValue::fromPercentage(30); + + // Keep product2, remove product1, add product3 + $input = new UpdateDiscountInput( + discount: $discount, + type: DiscountType::PERCENT, + value: $value, + is_old_price_displayed: false, + period: $period, + associatedProductsIds: [(string) $product2->id, (string) $product3->id], + ); + + // WHEN + $updated = $action($input); + + // THEN + expect($updated->id)->toBe($discount->id) + ->and($updated->value->getPercentage())->toBe(30) + ->and($updated->is_old_price_displayed)->toBeFalse(); + + $fresh = Discount::query()->find($discount->id); + expect($fresh)->not->toBeNull() + ->and($fresh?->value->getPercentage())->toBe(30) + ->and($fresh?->is_old_price_displayed)->toBeFalse(); + + $freshP1 = Product::query()->find($product1->id); + $freshP2 = Product::query()->find($product2->id); + $freshP3 = Product::query()->find($product3->id); + + expect($freshP1?->discount_id)->toBeNull() + ->and($freshP2?->discount_id)->toBe($discount->id) + ->and($freshP3?->discount_id)->toBe($discount->id); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new UpdateDiscount(); + $invalidInput = new class () implements ActionInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $action($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Queries/Discounts/GetDiscountFormDataQueryTest.php b/tests/Integration/WithApp/App/Queries/Discounts/GetDiscountFormDataQueryTest.php new file mode 100644 index 00000000..a795917a --- /dev/null +++ b/tests/Integration/WithApp/App/Queries/Discounts/GetDiscountFormDataQueryTest.php @@ -0,0 +1,121 @@ +range = new Range(); + $this->range->name = 'Gamme ' . uniqid(); + $this->range->status = true; + $this->range->order = random_int(1, 9999); + $this->range->picture_alt = 'alt'; + $this->range->picture_title = 'title'; + $this->range->save(); + }); + + $createProduct = function (string $name, Range $range): Product { + $product = new Product([ + 'range_id' => $range->id, + 'name' => $name . ' ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Description test', + 'status' => true, + ]); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(1000); + $product->short_description = 'Court'; + $product->picture_alt = 'alt'; + $product->picture_title = 'title'; + $product->picture_large_alt = 'alt'; + $product->picture_large_title = 'title'; + $product->save(); + + return $product; + }; + + it('returns form data for create mode when discount is null', function () use ($createProduct): void { + // GIVEN + $product1 = $createProduct('Poulet', $this->range); + $product2 = $createProduct('Canard', $this->range); + + $query = new GetDiscountFormDataQuery(); + $input = new GetDiscountFormDataQueryInput(); + + // WHEN + $output = $query($input); + + // THEN + expect($output->discount)->toBeNull() + ->and($output->discountTypes)->toHaveCount(count(DiscountType::cases())) + ->and($output->selectedProds)->toBeEmpty() + ->and($output->existingProds->pluck('id')->all())->toContain((string) $product1->id, (string) $product2->id) + ->and($output->existingProds->first())->toBeInstanceOf(DiscountProductDto::class); + }); + + it('returns form data for edit mode when discount is provided', function () use ($createProduct): void { + // GIVEN + $productAssociated = $createProduct('Associe', $this->range); + $productNotAssociated = $createProduct('NonAssocie', $this->range); + + $discount = new Discount(); + $discount->type = DiscountType::PERCENT; + $discount->value = DiscountValue::fromPercentage(15); + $discount->is_old_price_displayed = true; + $discount->save(); + + Product::query()->where('id', $productAssociated->id)->update(['discount_id' => $discount->id]); + + $query = new GetDiscountFormDataQuery(); + $input = new GetDiscountFormDataQueryInput(discount: $discount); + + // WHEN + $output = $query($input); + + // THEN + expect($output->discount)->toBeInstanceOf(DiscountDto::class) + ->and($output->discount?->id)->toBe($discount->id) + ->and($output->discountTypes)->toHaveCount(count(DiscountType::cases())) + ->and($output->selectedProds->pluck('id')->all())->toBe([(string) $productAssociated->id]) + ->and($output->existingProds->pluck('id')->all())->toContain((string) $productNotAssociated->id) + ->and($output->existingProds->pluck('id')->all())->not->toContain((string) $productAssociated->id); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $query = new GetDiscountFormDataQuery(); + $invalidInput = new class () implements QueryInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $query($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php b/tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php new file mode 100644 index 00000000..0cd31a90 --- /dev/null +++ b/tests/Integration/WithApp/App/Queries/Discounts/GetPaginatedDiscountsQueryTest.php @@ -0,0 +1,62 @@ +type = DiscountType::PERCENT; + $discount1->value = DiscountValue::fromPercentage(10); + $discount1->is_old_price_displayed = true; + $discount1->save(); + + $discount2 = new Discount(); + $discount2->type = DiscountType::PERCENT; + $discount2->value = DiscountValue::fromPercentage(20); + $discount2->is_old_price_displayed = false; + $discount2->save(); + + $query = new GetPaginatedDiscountsQuery(app(DataTableService::class)); + $input = new GetPaginatedDiscountsQueryInput( + pagination: Pagination::ofPage(1, 10), + ); + + // WHEN + $paginator = $query($input); + + // THEN + expect($paginator->total())->toBe(2) + ->and($paginator->items())->toHaveCount(2) + ->and($paginator->items()[0])->toBeInstanceOf(DiscountDto::class) + ->and($paginator->items()[1])->toBeInstanceOf(DiscountDto::class); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $query = new GetPaginatedDiscountsQuery(app(DataTableService::class)); + $invalidInput = new class () implements QueryInput + { + }; + + // WHEN + expect( + /** @phpstan-ignore argument.type */ + fn () => $query($invalidInput) + ) + // THEN + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Unit/App/Actions/Discounts/CreateDiscountInputTest.php b/tests/Unit/App/Actions/Discounts/CreateDiscountInputTest.php new file mode 100644 index 00000000..7aa7f5ac --- /dev/null +++ b/tests/Unit/App/Actions/Discounts/CreateDiscountInputTest.php @@ -0,0 +1,88 @@ +type)->toBe(DiscountType::PERCENT) + ->and($input->value)->toBe($value) + ->and($input->is_old_price_displayed)->toBeTrue() + ->and($input->period)->toBe($period) + ->and($input->associatedProductsIds)->toBe(['018f-product-1', '018f-product-2']); + }); + + it('creates a valid CreateDiscountInput instance with amount', function (): void { + // GIVEN + $type = DiscountType::AMOUNT; + $value = DiscountValue::fromAmount(new Money(500, new Currency('EUR'))); + + // WHEN + $input = new CreateDiscountInput( + type: $type, + value: $value, + is_old_price_displayed: false, + ); + + // THEN + expect($input->type)->toBe(DiscountType::AMOUNT) + ->and($input->value)->toBe($value) + ->and($input->is_old_price_displayed)->toBeFalse() + ->and($input->associatedProductsIds)->toBeEmpty(); + }); + + it('throws when discount value type does not match discount type', function (): void { + // GIVEN + $type = DiscountType::PERCENT; + $value = DiscountValue::fromAmount(new Money(500, new Currency('EUR'))); + + // WHEN + expect(fn () => new CreateDiscountInput( + type: $type, + value: $value, + is_old_price_displayed: true, + )) + // THEN + ->toThrow(InvalidArgumentException::class, 'The discount value type must match the discount type.'); + }); + + it('throws when associatedProductsIds contains non-string items', function (): void { + // GIVEN + $type = DiscountType::PERCENT; + $value = DiscountValue::fromPercentage(10); + + // WHEN + expect(fn () => new CreateDiscountInput( + type: $type, + value: $value, + is_old_price_displayed: true, + associatedProductsIds: [123], // @phpstan-ignore argument.type + )) + // THEN + ->toThrow(InvalidArgumentException::class); + }); +}); diff --git a/tests/Unit/App/Actions/Discounts/DeleteDiscountInputTest.php b/tests/Unit/App/Actions/Discounts/DeleteDiscountInputTest.php new file mode 100644 index 00000000..a7572f0a --- /dev/null +++ b/tests/Unit/App/Actions/Discounts/DeleteDiscountInputTest.php @@ -0,0 +1,21 @@ +discount)->toBe($discount); + }); +}); diff --git a/tests/Unit/App/Actions/Discounts/UpdateDiscountInputTest.php b/tests/Unit/App/Actions/Discounts/UpdateDiscountInputTest.php new file mode 100644 index 00000000..f8673968 --- /dev/null +++ b/tests/Unit/App/Actions/Discounts/UpdateDiscountInputTest.php @@ -0,0 +1,98 @@ +discount)->toBe($discount) + ->and($input->type)->toBe(DiscountType::PERCENT) + ->and($input->value)->toBe($value) + ->and($input->is_old_price_displayed)->toBeTrue() + ->and($input->period)->toBe($period) + ->and($input->associatedProductsIds)->toBe(['prod-1', 'prod-2']); + }); + + it('creates a valid UpdateDiscountInput instance with amount', function (): void { + // GIVEN + $discount = new Discount(); + $type = DiscountType::AMOUNT; + $value = DiscountValue::fromAmount(new Money(1500, new Currency('EUR'))); + + // WHEN + $input = new UpdateDiscountInput( + discount: $discount, + type: $type, + value: $value, + is_old_price_displayed: false, + ); + + // THEN + expect($input->type)->toBe(DiscountType::AMOUNT) + ->and($input->value)->toBe($value) + ->and($input->is_old_price_displayed)->toBeFalse() + ->and($input->associatedProductsIds)->toBeEmpty(); + }); + + it('throws when discount value type does not match discount type', function (): void { + // GIVEN + $discount = new Discount(); + $type = DiscountType::AMOUNT; + $value = DiscountValue::fromPercentage(15); + + // WHEN + expect(fn () => new UpdateDiscountInput( + discount: $discount, + type: $type, + value: $value, + is_old_price_displayed: true, + )) + // THEN + ->toThrow(InvalidArgumentException::class, 'The discount value type must match the discount type.'); + }); + + it('throws when associatedProductsIds contains non-string items', function (): void { + // GIVEN + $discount = new Discount(); + $type = DiscountType::PERCENT; + $value = DiscountValue::fromPercentage(10); + + // WHEN + expect(fn () => new UpdateDiscountInput( + discount: $discount, + type: $type, + value: $value, + is_old_price_displayed: true, + associatedProductsIds: [123], // @phpstan-ignore argument.type + )) + // THEN + ->toThrow(InvalidArgumentException::class); + }); +}); diff --git a/tests/Unit/App/Dto/DiscountDtoTest.php b/tests/Unit/App/Dto/DiscountDtoTest.php new file mode 100644 index 00000000..7a41406f --- /dev/null +++ b/tests/Unit/App/Dto/DiscountDtoTest.php @@ -0,0 +1,51 @@ +id)->toBe(42) + ->and($dto->type)->toBe(DiscountType::PERCENT) + ->and($dto->value)->toBe($value) + ->and($dto->is_old_price_displayed)->toBeTrue() + ->and($dto->date_start)->toEqual($dateStart) + ->and($dto->date_end)->toEqual($dateEnd) + ->and($dto->getRouteKey())->toBe(42) + ->and($dto->getRouteKeyName())->toBe('id') + ->and($dto->resolveRouteBinding(42))->toBeNull() + ->and($dto->resolveChildRouteBinding('child', 'val', 'field'))->toBeNull() + ->and($dto->toArray())->toBe([ + 'id' => 42, + 'type' => DiscountType::PERCENT->value(), + 'value' => 20, + 'is_old_price_displayed' => true, + 'date_start' => $dateStart, + 'date_end' => $dateEnd, + 'created_at' => null, + 'updated_at' => null, + ]); + }); +}); diff --git a/tests/Unit/App/Dto/DiscountProductDtoTest.php b/tests/Unit/App/Dto/DiscountProductDtoTest.php new file mode 100644 index 00000000..dc1db142 --- /dev/null +++ b/tests/Unit/App/Dto/DiscountProductDtoTest.php @@ -0,0 +1,33 @@ +id)->toBe($id) + ->and($dto->name)->toBe($name) + ->and($dto->toArray())->toBe([ + 'id' => $id, + 'name' => $name, + ]) + ->and($dto->jsonSerialize())->toBe([ + 'id' => $id, + 'name' => $name, + ]); + }); +});