refactor(bo): refactor DiscountsController to strict CQS pattern with actions, queries and DTOs

This commit is contained in:
Jérémy Munsch 2026-09-30 12:43:55 +02:00
parent f79f1e1494
commit 55ae6553d8
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
32 changed files with 1617 additions and 143 deletions

View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace App\Actions\Discounts;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Models\Discount;
use App\Models\Product;
use Illuminate\Support\Carbon;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Actions\Discounts\CreateDiscountInput, \App\Models\Discount>
*/
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<string> $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]);
}
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Actions\Discounts;
use App\Contracts\ActionInput;
use Domain\Enums\DiscountType;
use Domain\Models\ValueObjects\DatePeriod;
use Domain\Models\ValueObjects\DiscountValue;
use Webmozart\Assert\Assert;
final readonly class CreateDiscountInput implements ActionInput
{
/**
* @param array<string> $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);
}
}

View file

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Actions\Discounts;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Actions\Discounts\DeleteDiscountInput, bool>
*/
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();
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Actions\Discounts;
use App\Contracts\ActionInput;
use App\Models\Discount;
final readonly class DeleteDiscountInput implements ActionInput
{
public function __construct(
public Discount $discount,
) {
}
}

View file

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace App\Actions\Discounts;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Models\Discount;
use App\Models\Product;
use Illuminate\Support\Carbon;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Actions\Discounts\UpdateDiscountInput, \App\Models\Discount>
*/
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<string> $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]);
}
}
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Actions\Discounts;
use App\Contracts\ActionInput;
use App\Models\Discount;
use Domain\Enums\DiscountType;
use Domain\Models\ValueObjects\DatePeriod;
use Domain\Models\ValueObjects\DiscountValue;
use Webmozart\Assert\Assert;
final readonly class UpdateDiscountInput implements ActionInput
{
/**
* @param array<string> $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);
}
}

86
app/Dto/DiscountDto.php Normal file
View file

@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace App\Dto;
use App\Models\Discount;
use Domain\Enums\DiscountType;
use Domain\Models\ValueObjects\DiscountValue;
use Illuminate\Contracts\Routing\UrlRoutable;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Carbon;
/**
* @implements Arrayable<string, mixed>
*/
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<string, mixed>
*/
#[\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,
];
}
}

View file

@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Dto;
use App\Models\Product;
use Illuminate\Contracts\Support\Arrayable;
/**
* @implements Arrayable<string, string>
*/
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();
}
}

View file

@ -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<string> $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)),
]));
}
}

View file

@ -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<string> */
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<string,mixed> */
public function rules(): array
{

View file

@ -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;

View file

@ -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,

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace App\Queries\Discounts;
use App\Contracts\Query;
use App\Contracts\QueryInput;
use App\Dto\DiscountDto;
use App\Dto\DiscountProductDto;
use App\Models\Product;
use Domain\Enums\DiscountType;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Query<\App\Queries\Discounts\GetDiscountFormDataQueryInput, \App\Queries\Discounts\GetDiscountFormDataQueryOutput>
*/
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,
);
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Queries\Discounts;
use App\Contracts\QueryInput;
use App\Models\Discount;
final readonly class GetDiscountFormDataQueryInput implements QueryInput
{
public function __construct(
public ?Discount $discount = null,
) {
}
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Queries\Discounts;
use App\Dto\DiscountDto;
use App\Dto\DiscountProductDto;
use Domain\Enums\DiscountType;
use Illuminate\Support\Collection;
final readonly class GetDiscountFormDataQueryOutput
{
/**
* @param array<int, DiscountType> $discountTypes
* @param Collection<int, DiscountProductDto> $existingProds
* @param Collection<int, DiscountProductDto> $selectedProds
*/
public function __construct(
public ?DiscountDto $discount,
public array $discountTypes,
public Collection $existingProds,
public Collection $selectedProds,
) {
}
}

View file

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace App\Queries\Discounts;
use App\Contracts\Query;
use App\Contracts\QueryInput;
use App\Dto\DiscountDto;
use App\Models\Discount;
use App\Services\DataTableService;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Query<\App\Queries\Discounts\GetPaginatedDiscountsQueryInput, \Illuminate\Contracts\Pagination\LengthAwarePaginator<int, \App\Dto\DiscountDto>>
*/
final readonly class GetPaginatedDiscountsQuery implements Query
{
public function __construct(
private DataTableService $dataTable,
) {
}
/**
* @param \App\Queries\Discounts\GetPaginatedDiscountsQueryInput $input
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator<int, \App\Dto\DiscountDto>
*/
#[\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));
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Queries\Discounts;
use App\Contracts\QueryInput;
use Domain\Models\ValueObjects\Pagination;
final readonly class GetPaginatedDiscountsQueryInput implements QueryInput
{
public function __construct(
public Pagination $pagination,
) {
}
}

View file

@ -1,8 +1,8 @@
@php
/** @var \App\Models\Discount|null $discount */
/** @var \App\Models\Discount|\App\Dto\DiscountDto|null $discount */
if ($discount !== null && !($discount instanceof \App\Models\Discount)) {
throw new \UnexpectedValue('$discount shall be null or ' . \App\Models\Discount::class);
if ($discount !== null && !($discount instanceof \App\Models\Discount) && !($discount instanceof \App\Dto\DiscountDto)) {
throw new \UnexpectedValueException('$discount shall be null, ' . \App\Models\Discount::class . ', or ' . \App\Dto\DiscountDto::class);
}
@endphp

View file

@ -15,7 +15,7 @@
</div>
<div class="col-3">
<div class="input-group justify-content-end">
@can('create', \App\Models\Slide::class)
@can('create', \App\Models\Discount::class)
<a class="btn btn-primary" href="{{ route('bo.discounts.create') }}"
title="{{ Str::ucfirst(__('crud.actions.create')) }} {{ Str::ucfirst(trans_choice('models.classes.discounts', \INF)) }}"><i
class="fa-solid fa-square-plus"></i></a>

View file

@ -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));
});

View file

@ -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');
});
});

View file

@ -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');
});
});

View file

@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
namespace Tests\Integration\WithApp\App\Actions\Discounts;
use App\Actions\Discounts\CreateDiscount;
use App\Actions\Discounts\CreateDiscountInput;
use App\Contracts\ActionInput;
use App\Models\Discount;
use App\Models\Product;
use App\Models\Range;
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\Models\ValueObjects\DatePeriod;
use Domain\Models\ValueObjects\DiscountValue;
use Money\Currency;
use Money\Money;
describe('CreateDiscount action', function (): void {
beforeEach(function (): void {
$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();
});
$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);
});
});

View file

@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Tests\Integration\WithApp\App\Actions\Discounts;
use App\Actions\Discounts\DeleteDiscount;
use App\Actions\Discounts\DeleteDiscountInput;
use App\Contracts\ActionInput;
use App\Models\Discount;
use App\Models\Product;
use App\Models\Range;
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\Models\ValueObjects\DiscountValue;
use Money\Money;
describe('DeleteDiscount action', function (): void {
beforeEach(function (): void {
$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();
});
$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);
});
});

View file

@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace Tests\Integration\WithApp\App\Actions\Discounts;
use App\Actions\Discounts\UpdateDiscount;
use App\Actions\Discounts\UpdateDiscountInput;
use App\Contracts\ActionInput;
use App\Models\Discount;
use App\Models\Product;
use App\Models\Range;
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\Models\ValueObjects\DatePeriod;
use Domain\Models\ValueObjects\DiscountValue;
use Money\Money;
describe('UpdateDiscount action', function (): void {
beforeEach(function (): void {
$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();
});
$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);
});
});

View file

@ -0,0 +1,121 @@
<?php
declare(strict_types=1);
namespace Tests\Integration\WithApp\App\Queries\Discounts;
use App\Contracts\QueryInput;
use App\Dto\DiscountDto;
use App\Dto\DiscountProductDto;
use App\Models\Discount;
use App\Models\Product;
use App\Models\Range;
use App\Queries\Discounts\GetDiscountFormDataQuery;
use App\Queries\Discounts\GetDiscountFormDataQueryInput;
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\Models\ValueObjects\DiscountValue;
use Money\Money;
describe('GetDiscountFormDataQuery', function (): void {
beforeEach(function (): void {
$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();
});
$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);
});
});

View file

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace Tests\Integration\WithApp\App\Queries\Discounts;
use App\Contracts\QueryInput;
use App\Dto\DiscountDto;
use App\Models\Discount;
use App\Queries\Discounts\GetPaginatedDiscountsQuery;
use App\Queries\Discounts\GetPaginatedDiscountsQueryInput;
use App\Services\DataTableService;
use Domain\Enums\DiscountType;
use Domain\Models\ValueObjects\DiscountValue;
use Domain\Models\ValueObjects\Pagination;
describe('GetPaginatedDiscountsQuery', function (): void {
it('returns a paginator of DiscountDto instances', function (): void {
// GIVEN
$discount1 = new Discount();
$discount1->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);
});
});

View file

@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\App\Actions\Discounts;
use App\Actions\Discounts\CreateDiscountInput;
use Domain\Enums\DiscountType;
use Domain\Models\ValueObjects\DatePeriod;
use Domain\Models\ValueObjects\DiscountValue;
use InvalidArgumentException;
use Money\Currency;
use Money\Money;
describe('CreateDiscountInput', function (): void {
it('creates a valid CreateDiscountInput instance with percentage', function (): void {
// GIVEN
$type = DiscountType::PERCENT;
$value = DiscountValue::fromPercentage(20);
$period = new DatePeriod();
// WHEN
$input = new CreateDiscountInput(
type: $type,
value: $value,
is_old_price_displayed: true,
period: $period,
associatedProductsIds: ['018f-product-1', '018f-product-2'],
);
// THEN
expect($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(['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);
});
});

View file

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\App\Actions\Discounts;
use App\Actions\Discounts\DeleteDiscountInput;
use App\Models\Discount;
describe('DeleteDiscountInput', function (): void {
it('creates a valid DeleteDiscountInput instance', function (): void {
// GIVEN
$discount = new Discount();
// WHEN
$input = new DeleteDiscountInput(discount: $discount);
// THEN
expect($input->discount)->toBe($discount);
});
});

View file

@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\App\Actions\Discounts;
use App\Actions\Discounts\UpdateDiscountInput;
use App\Models\Discount;
use Domain\Enums\DiscountType;
use Domain\Models\ValueObjects\DatePeriod;
use Domain\Models\ValueObjects\DiscountValue;
use InvalidArgumentException;
use Money\Currency;
use Money\Money;
describe('UpdateDiscountInput', function (): void {
it('creates a valid UpdateDiscountInput instance with percentage', function (): void {
// GIVEN
$discount = new Discount();
$type = DiscountType::PERCENT;
$value = DiscountValue::fromPercentage(25);
$period = new DatePeriod();
// WHEN
$input = new UpdateDiscountInput(
discount: $discount,
type: $type,
value: $value,
is_old_price_displayed: true,
period: $period,
associatedProductsIds: ['prod-1', 'prod-2'],
);
// THEN
expect($input->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);
});
});

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\App\Dto;
use App\Dto\DiscountDto;
use Domain\Enums\DiscountType;
use Domain\Models\ValueObjects\DiscountValue;
use Illuminate\Support\Carbon;
describe('DiscountDto', function (): void {
it('creates a DTO from constructor and serializes to array', function (): void {
// GIVEN
$dateStart = Carbon::parse('2026-06-01 10:00:00');
$dateEnd = Carbon::parse('2026-06-30 20:00:00');
$value = DiscountValue::fromPercentage(20);
// WHEN
$dto = new DiscountDto(
id: 42,
type: DiscountType::PERCENT,
value: $value,
is_old_price_displayed: true,
date_start: $dateStart,
date_end: $dateEnd,
);
// THEN
expect($dto->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,
]);
});
});

View file

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\App\Dto;
use App\Dto\DiscountProductDto;
describe('DiscountProductDto', function (): void {
it('creates a DTO from constructor and serializes to array and json', function (): void {
// GIVEN
$id = '018f-product-uuid';
$name = 'Poulet Fermier';
// WHEN
$dto = new DiscountProductDto(
id: $id,
name: $name,
);
// THEN
expect($dto->id)->toBe($id)
->and($dto->name)->toBe($name)
->and($dto->toArray())->toBe([
'id' => $id,
'name' => $name,
])
->and($dto->jsonSerialize())->toBe([
'id' => $id,
'name' => $name,
]);
});
});