diff --git a/app/Actions/Common/ChangeModelOrderPosition.php b/app/Actions/Common/ChangeModelOrderPosition.php new file mode 100644 index 00000000..c19636c7 --- /dev/null +++ b/app/Actions/Common/ChangeModelOrderPosition.php @@ -0,0 +1,98 @@ + + */ +final class ChangeModelOrderPosition implements Action +{ + private const int MAX_ORDER_VALUE = 4294967295; + + /** + * @param \App\Actions\Common\ChangeModelOrderPositionInput $input + */ + #[\Override] + public function __invoke(ActionInput $input): bool + { + Assert::isInstanceOf($input, ChangeModelOrderPositionInput::class); + + $model = $input->model; + $currentOrder = $model->getOrder(); + $targetOrder = $input->targetOrder; + + if ($currentOrder === $targetOrder) { + return true; + } + + /** @var Builder $baseQuery */ + $baseQuery = method_exists($model, 'withTrashed') + // @phpstan-ignore method.notFound (withTrashed) + ? $model::query()->withTrashed() + : $model::query(); + + /** @var int|null $maxOrder */ + $maxOrder = (clone $baseQuery)->max('order'); + if ($maxOrder !== null && $targetOrder > $maxOrder) { + $targetOrder = (int) $maxOrder; + } + + if ($currentOrder === $targetOrder) { + return true; + } + + // Deactivate timestamps + $model->timestamps = false; + + // Step 1: Temporarily park the moving model at MAX_ORDER_VALUE + $model->setOrder(self::MAX_ORDER_VALUE); + $model->saveQuietly(); + + if ($targetOrder < $currentOrder) { + // Moving UP + /** @var \Illuminate\Database\Eloquent\Collection $itemsToShift */ + $itemsToShift = (clone $baseQuery) + ->where('order', '>=', $targetOrder) + ->where('order', '<', $currentOrder) + ->whereKeyNot($model->getKey()) + ->orderBy('order', 'desc') + ->get(); + + foreach ($itemsToShift as $item) { + $item->timestamps = false; + $item->setOrder($item->getOrder() + 1); + $item->saveQuietly(); + } + } else { + // Moving DOWN + /** @var \Illuminate\Database\Eloquent\Collection $itemsToShift */ + $itemsToShift = (clone $baseQuery) + ->where('order', '>', $currentOrder) + ->where('order', '<=', $targetOrder) + ->whereKeyNot($model->getKey()) + ->orderBy('order', 'asc') + ->get(); + + foreach ($itemsToShift as $item) { + $item->timestamps = false; + $item->setOrder($item->getOrder() - 1); + $item->saveQuietly(); + } + } + + // Step 2: Set the moving model to the target order + $model->setOrder($targetOrder); + $model->saveQuietly(); + + return true; + } +} diff --git a/app/Actions/Common/ChangeModelOrderPositionInput.php b/app/Actions/Common/ChangeModelOrderPositionInput.php new file mode 100644 index 00000000..897a6bcd --- /dev/null +++ b/app/Actions/Common/ChangeModelOrderPositionInput.php @@ -0,0 +1,22 @@ +model, Model::class); + Assert::isInstanceOf($this->model, ModelWithOrder::class); + Assert::greaterThanEq($this->targetOrder, 1); + } +} diff --git a/app/Http/Controllers/Bo/ProductsController.php b/app/Http/Controllers/Bo/ProductsController.php index 0e130bd3..5e5ed076 100644 --- a/app/Http/Controllers/Bo/ProductsController.php +++ b/app/Http/Controllers/Bo/ProductsController.php @@ -67,6 +67,7 @@ class ProductsController extends Controller implements MassActions 'brands' => $output->brands, 'ranges' => $output->ranges, 'tags' => $output->tags, + 'discounts' => $output->discounts, 'searchFields' => $output->searchFields, ]); } diff --git a/app/Http/Requests/Bo/ChangeSelectedOrderRequest.php b/app/Http/Requests/Bo/ChangeSelectedOrderRequest.php new file mode 100644 index 00000000..993ff37d --- /dev/null +++ b/app/Http/Requests/Bo/ChangeSelectedOrderRequest.php @@ -0,0 +1,42 @@ +authService->check(); + } + + /** + * @return array + */ + public function rules(): array + { + return [ + 'order' => ['required', 'integer', 'min:1'], + ]; + } + + public function toChangeModelOrderPositionInput(Model & ModelWithOrder $model): ChangeModelOrderPositionInput + { + return new ChangeModelOrderPositionInput( + model: $model, + targetOrder: $this->integer('order'), + ); + } +} diff --git a/app/Http/Requests/Bo/Products/IndexProductRequest.php b/app/Http/Requests/Bo/Products/IndexProductRequest.php index 0dc2f71a..a3b9f6b1 100644 --- a/app/Http/Requests/Bo/Products/IndexProductRequest.php +++ b/app/Http/Requests/Bo/Products/IndexProductRequest.php @@ -25,7 +25,7 @@ class IndexProductRequest extends FormRequest $tag = $this->resolveFilterValue('tag', $session); $range = $this->resolveFilterValue('range', $session); - $discount = $this->resolveBooleanFilter('discount', false, $session); + $discount = $this->resolveFilterValue('discount', $session); $star = $this->resolveBooleanFilter('star', $starred, $session); $search = $this->filled('search') ? $this->string('search')->value() : null; @@ -85,8 +85,7 @@ class IndexProductRequest extends FormRequest protected function prepareForValidation(): void { $this->merge([ - 'discount' => $this->boolean('discount'), - 'star' => $this->boolean('star'), + 'star' => $this->boolean('star'), ]); } @@ -95,7 +94,7 @@ class IndexProductRequest extends FormRequest { return [ - 'discount' => ['required', 'boolean'], + 'discount' => ['sometimes', 'nullable', 'string', 'max:255'], 'star' => ['required', 'boolean'], 'brand' => ['sometimes', 'nullable', 'string', 'min:3', 'max:255'], ]; @@ -105,7 +104,7 @@ class IndexProductRequest extends FormRequest public function attributes(): array { return [ - 'discount' => trans('crud.helpers.discounted'), + 'discount' => trans_choice('models.classes.discounts', 1), 'star' => trans('crud.helpers.starred'), 'description' => trans('validation.attributes.description'), ]; diff --git a/app/Http/Resources/Fo/Ajax/FilteredProductResource.php b/app/Http/Resources/Fo/Ajax/FilteredProductResource.php index 7518860d..af7cf6ee 100644 --- a/app/Http/Resources/Fo/Ajax/FilteredProductResource.php +++ b/app/Http/Resources/Fo/Ajax/FilteredProductResource.php @@ -50,8 +50,7 @@ class FilteredProductResource extends JsonResource MoneyHelper::serialized($discount) : null, 'is_available' => $productAvailabilityService->isOrderable($domainProduct), 'can_add_to_basket' => Gate::allows('addToBasket', $this->product), - 'showStrippedPrice' => $this->product->validDiscount() - ->value('is_old_price_displayed') ? true : false, + 'showStrippedPrice' => (bool) $this->product->validDiscount?->is_old_price_displayed, 'nutriscore' => $this->product->inco?->nutriscore?->value(), ]; } diff --git a/app/Policies/Backend/SettingPolicy.php b/app/Policies/Backend/SettingPolicy.php index 9ddc6274..ddf64159 100644 --- a/app/Policies/Backend/SettingPolicy.php +++ b/app/Policies/Backend/SettingPolicy.php @@ -8,25 +8,30 @@ use App\Dto\SettingDto; use App\Models\Customer; use App\Models\Setting; use App\Models\User; -use Domain\Enums\UserRole; class SettingPolicy { public function view(User | Customer $user, Setting | SettingDto | null $_ = null): bool { - if ($user instanceof Customer) { - return false; - } + // FIXME: The Arcadia refresh job dispatching is currently disabled and needs to be enabled when api will be available. + return false; - return $user->role->isAtLeastEqualsTo(UserRole::Admin); + // if ($user instanceof Customer) { + // return false; + // } + + // return $user->role->isAtLeastEqualsTo(UserRole::Admin); } public function update(User | Customer $user, Setting | SettingDto | null $_ = null): bool { - if ($user instanceof Customer) { - return false; - } + // FIXME: The Arcadia refresh job dispatching is currently disabled and needs to be enabled when api will be available. + return false; - return $user->role->isAtLeastEqualsTo(UserRole::Admin); + // if ($user instanceof Customer) { + // return false; + // } + + // return $user->role->isAtLeastEqualsTo(UserRole::Admin); } } diff --git a/app/Queries/Products/GetBoPaginatedProductsQuery.php b/app/Queries/Products/GetBoPaginatedProductsQuery.php index 416d8b6a..a1bc1c27 100644 --- a/app/Queries/Products/GetBoPaginatedProductsQuery.php +++ b/app/Queries/Products/GetBoPaginatedProductsQuery.php @@ -7,12 +7,14 @@ namespace App\Queries\Products; use App\Contracts\Query; use App\Contracts\QueryInput; use App\Dto\ProductDto; +use App\Models\Discount; use App\Models\Product; use App\Models\Range; use App\Models\Tag; use App\Services\DataTableService; use Domain\Enums\ProductBrand; use Illuminate\Contracts\Database\Query\Builder; +use Money\Formatter\IntlMoneyFormatter; use Webmozart\Assert\Assert; /** @@ -22,6 +24,7 @@ final readonly class GetBoPaginatedProductsQuery implements Query { public function __construct( private DataTableService $dataTable, + private IntlMoneyFormatter $moneyFormatter, ) { } @@ -53,8 +56,12 @@ final readonly class GetBoPaginatedProductsQuery implements Query $query->where('star', true); } - if ($input->discount) { - $query->whereHas('discount'); + if ($input->discount !== null && $input->discount !== '') { + if ($input->discount === '0') { + $query->whereHas('discount'); + } else { + $query->where('discount_id', $input->discount); + } } if (! empty($input->tag)) { @@ -67,13 +74,19 @@ final readonly class GetBoPaginatedProductsQuery implements Query $this->dataTable->sortQuery(Product::class, $query, ['inco']); - $paginator = $this->dataTable->paginateQuery($query, $input->pagination); - /** @var \Illuminate\Contracts\Pagination\LengthAwarePaginator $productsDtoPaginator */ + $paginator = $this->dataTable->paginateQuery($query, $input->pagination); + /** @var \Illuminate\Contracts\Pagination\LengthAwarePaginator $productsDtoPaginator */ $productsDtoPaginator = $paginator->through(fn (Product $product): ProductDto => ProductDto::fromModel($product)); $brands = ProductBrand::cases(); $ranges = Range::query()->pluck('name', 'id'); $tags = Tag::query()->pluck('label', 'id'); + $discounts = Discount::query() + ->orderByDesc('id') + ->get() + ->mapWithKeys(fn (Discount $d): array => [ + $d->id => $this->formatDiscountLabel($d), + ]); $searchFields = str(collect([ trans('validation.attributes.name'), trans('validation.custom.attributes.inco_id'), @@ -84,7 +97,27 @@ final readonly class GetBoPaginatedProductsQuery implements Query brands: $brands, ranges: $ranges, tags: $tags, + discounts: $discounts, searchFields: $searchFields, ); } + + private function formatDiscountLabel(Discount $discount): string + { + $formattedValue = $discount->value->isPercentage() + ? $discount->value->getPercentage() . ' %' + : $this->moneyFormatter->format($discount->value->getAmount()); + + $label = "#{$discount->id} - {$discount->type->label()} ({$formattedValue})"; + + if ($discount->date_start !== null && $discount->date_end !== null) { + $label .= " [{$discount->date_start->format('d/m/Y')} - {$discount->date_end->format('d/m/Y')}]"; + } elseif ($discount->date_start !== null) { + $label .= ' [' . __('from :date', ['date' => $discount->date_start->format('d/m/Y')]) . ']'; + } elseif ($discount->date_end !== null) { + $label .= ' [' . __('until :date', ['date' => $discount->date_end->format('d/m/Y')]) . ']'; + } + + return $label; + } } diff --git a/app/Queries/Products/GetBoPaginatedProductsQueryInput.php b/app/Queries/Products/GetBoPaginatedProductsQueryInput.php index 353d87f2..c6ceb52e 100644 --- a/app/Queries/Products/GetBoPaginatedProductsQueryInput.php +++ b/app/Queries/Products/GetBoPaginatedProductsQueryInput.php @@ -14,7 +14,7 @@ final readonly class GetBoPaginatedProductsQueryInput implements QueryInput public ?string $search = null, public ?string $brand = null, public bool $starred = false, - public bool $discount = false, + public ?string $discount = null, public ?string $tag = null, public ?string $range = null, ) { diff --git a/app/Queries/Products/GetBoPaginatedProductsQueryOutput.php b/app/Queries/Products/GetBoPaginatedProductsQueryOutput.php index 16a820e4..ad207949 100644 --- a/app/Queries/Products/GetBoPaginatedProductsQueryOutput.php +++ b/app/Queries/Products/GetBoPaginatedProductsQueryOutput.php @@ -16,12 +16,14 @@ final readonly class GetBoPaginatedProductsQueryOutput * @param list $brands * @param Collection $ranges * @param Collection $tags + * @param Collection $discounts */ public function __construct( public LengthAwarePaginator $products, public array $brands, public Collection $ranges, public Collection $tags, + public Collection $discounts, public string $searchFields, ) { } diff --git a/app/Traits/Controllers/ChangesModelOrder.php b/app/Traits/Controllers/ChangesModelOrder.php index fb2fe577..cb0b4b23 100644 --- a/app/Traits/Controllers/ChangesModelOrder.php +++ b/app/Traits/Controllers/ChangesModelOrder.php @@ -6,8 +6,10 @@ namespace App\Traits\Controllers; use App\Actions\Common\ChangeModelOrder; use App\Actions\Common\ChangeModelOrderInput; +use App\Actions\Common\ChangeModelOrderPosition; use App\Contracts\Executor; use App\Http\Requests\Bo\ChangeOrderRequest; +use App\Http\Requests\Bo\ChangeSelectedOrderRequest; use App\Interfaces\ModelWithOrder; use App\Services\FlashMessageService; use Illuminate\Database\Eloquent\Model; @@ -36,4 +38,27 @@ trait ChangesModelOrder return back(); } + + public function changeSelectedOrder( + Model & ModelWithOrder $model, + ChangeSelectedOrderRequest $request, + ChangeModelOrderPosition $action, + Executor $executor, + FlashMessageService $flashMessageService + ): RedirectResponse { + $changed = $executor->execute( + $action, + $request->toChangeModelOrderPositionInput($model) + ); + + if (! $changed) { + $flashMessageService->error(trans('crud.messages.order_not_changed')); + + return back(); + } + + $flashMessageService->success(trans('crud.messages.order_changed')); + + return back(); + } } diff --git a/domain/Models/ValueObjects/DiscountValue.php b/domain/Models/ValueObjects/DiscountValue.php index b151f572..ea49196b 100644 --- a/domain/Models/ValueObjects/DiscountValue.php +++ b/domain/Models/ValueObjects/DiscountValue.php @@ -8,6 +8,11 @@ use Domain\Enums\DiscountType; use Domain\Services\PricingService; use Money\Money; +/** + * Represents a product discount (either a percentage or a fixed amount). + * + * Business rule: All discounts apply to the piece (sold unit), regardless of the product's invoicing unit. + */ final readonly class DiscountValue { private function __construct( diff --git a/domain/Services/PricingService.php b/domain/Services/PricingService.php index b9e58e0c..6ff6ffba 100644 --- a/domain/Services/PricingService.php +++ b/domain/Services/PricingService.php @@ -18,14 +18,27 @@ class PricingService private const GRAMS_PER_KG = 1000; + /** + * Calculates all pricing values (base, discounted, per-kg, and discount rate) for a product. + * + * Business rules: + * - When a product is invoiced by the kilo (InvoicingUnit::KGM) and sold by the piece (SellUnit::PCE), + * $product->price is the reference price per kg HT, while $basePriceHt is the price of the piece HT. + * - All discounts (percentage or fixed amount) always apply to the piece (sold unit). + */ public function calculateForProduct(Product $product): ProductPricing { $basePriceHt = $this->priceHt($product); $basePriceTtc = $this->applyTax($basePriceHt, $product->tax_rate); + // * All discounts apply to the piece ($basePriceHt), capped at the piece price to prevent negative prices $discountAmountHt = $product->validDiscount?->calculateDiscountAmount($basePriceHt) ?? new Money(0, $basePriceHt->getCurrency()); + if ($discountAmountHt->greaterThan($basePriceHt)) { + $discountAmountHt = $basePriceHt; + } + $discountedPriceHt = $basePriceHt->subtract($discountAmountHt); $discountedPriceTtc = $this->applyTax($discountedPriceHt, $product->tax_rate); @@ -47,7 +60,7 @@ class PricingService private function priceHt(Product $product): Money { if ($product->invoicing_unit === InvoicingUnit::KGM && $product->sell_unit === SellUnit::PCE && $product->product_weight) { - // * Price per kg => price of the piece: price × grams ÷ 1000 (single rounding, no float) + // * Price per kg => price of the piece: price x grams / 1000 (single rounding, no float) return $product->price ->multiply($product->product_weight->toGrams()) ->divide(self::GRAMS_PER_KG, PricingService::ROUNDING); @@ -58,12 +71,40 @@ class PricingService private function calculatePriceKgTtc(Money $discountedPriceHt, Product $product): Money { + if ($product->invoicing_unit === InvoicingUnit::KGM) { + // * The product price is already a price per kg: it is the reference for the kg price + $discountAmountKgHt = $product->validDiscount?->calculateDiscountAmount($product->price) + ?? new Money(0, $product->price->getCurrency()); + + $grams = $product->product_weight?->toGrams() ?? 0; + + if ( + $product->validDiscount !== null + && ! $product->validDiscount->isPercentage() + && $product->sell_unit === SellUnit::PCE + && $grams > 0 + ) { + // * A fixed amount applies to the piece: bring it back to a per-kg amount + $discountAmountKgHt = $discountAmountKgHt + ->multiply(self::GRAMS_PER_KG) + ->divide($grams, self::ROUNDING); + } + + $discountedKgPriceHt = $product->price->subtract($discountAmountKgHt); + + if ($discountedKgPriceHt->isNegative()) { + $discountedKgPriceHt = new Money(0, $product->price->getCurrency()); + } + + return $this->applyTax($discountedKgPriceHt, $product->tax_rate); + } + $priceTtc = $this->applyTax($discountedPriceHt, $product->tax_rate); $grams = $product->product_weight?->toGrams() ?? 0; if ($grams > 0 && $product->status && $product->invoicing_unit === InvoicingUnit::PCE) { - // * Price of the piece => price per kg: price × 1000 ÷ grams (single rounding, no float) + // * Price of the piece => price per kg: price x 1000 / grams (single rounding, no float) return $priceTtc ->multiply(self::GRAMS_PER_KG) ->divide($grams, self::ROUNDING); diff --git a/infra/Adapters/Repositories/EloquentPickupExceptionRepository.php b/infra/Adapters/Repositories/EloquentPickupExceptionRepository.php index 696e1f53..ae9d8cfb 100644 --- a/infra/Adapters/Repositories/EloquentPickupExceptionRepository.php +++ b/infra/Adapters/Repositories/EloquentPickupExceptionRepository.php @@ -62,7 +62,7 @@ class EloquentPickupExceptionRepository implements PickupExceptionRepository ->where('date', '>', $period->getStartDate()->toImmutable()) ->where('date', '<=', $period->getEndDate()?->toImmutable()) ->get() - ->map(fn (PickupException $ex) => $this->toShopDomain($ex)) + ->map(fn (PickupException $ex) => $this->toShopDomain($ex, $ex->pivot)) ->all(); } diff --git a/lang/en.json b/lang/en.json index df22da51..dbecbcf4 100644 --- a/lang/en.json +++ b/lang/en.json @@ -46,6 +46,7 @@ "Agree": "Agree", "Aisles": "Aisles", "All aisles": "All aisles", + "All discounts": "All discounts", "All products have been selected.": "All products have been selected.", "All rights reserved.": "All rights reserved.", "Allergens": "Allergens", @@ -285,6 +286,7 @@ "Frequency": "Frequency", "Frequently asked questions.": "Frequently asked questions.", "from": "from", + "from :date": "from :date", "From date": "From date", "Gateway Timeout": "Gateway Timeout", "general conditions": "general conditions", @@ -730,6 +732,7 @@ "The answer": "The answer", "The brand associated with the product": "The brand associated with the product", "The customer account was not found.": "The customer account was not found.", + "The discount applies to the piece (sold unit).": "The discount applies to the piece (sold unit).", "The employee sync job has been dispatched": "The employee sync job has been dispatched", "The existing encrypted environment file is not in readable format. Use --force to overwrite it.": "The existing encrypted environment file is not in readable format. Use --force to overwrite it.", "The existing encryption key is required to update the encrypted environment file.": "The existing encryption key is required to update the encrypted environment file.", @@ -795,6 +798,7 @@ "Unprocessable Entity": "Unprocessable Entity", "Unsubscribe": "Unsubscribe", "Unsupported Media Type": "Unsupported Media Type", + "until :date": "until :date", "Up": "Up", "Update": "Update", "Update :name": "Update :name", @@ -868,5 +872,10 @@ "Your password has been changed. If you are not at the origin of this change, please contact us as soon as possible using the contact form or by contacting your manager.": "Your password has been changed. If you are not at the origin of this change, please contact us as soon as possible using the contact form or by contacting your manager.", "your_message": "your_message", "Zip code": "Zip code", - "Your search": "Your search" + "Your search": "Your search", + "Choose position": "Choose position", + "Move": "Move", + "Move down": "Move down", + "Move up": "Move up", + "New position": "New position" } diff --git a/lang/fr.json b/lang/fr.json index 3e1c47e9..ae85abe8 100644 --- a/lang/fr.json +++ b/lang/fr.json @@ -45,6 +45,7 @@ "Agree": "Accepter", "Aisles": "Rayons", "All aisles": "Tous les rayons", + "All discounts": "Toutes les promotions", "All products have been selected.": "Tous les produits ont été sélectionnés.", "All rights reserved.": "Tous droits réservés.", "Allergens": "Allergènes", @@ -282,6 +283,7 @@ "Frequency": "Fréquence", "Frequently asked questions.": "Foire aux questions fréquemment posées.", "from": "de", + "from :date": "du :date", "From date": "Du", "Gateway Timeout": "Temps d'attente de la passerelle dépassé", "general conditions": "conditions générales", @@ -445,7 +447,7 @@ "No pickup exception has been created for now.": "Aucune exception de retrait n'a été créée pour le moment.", "No picture available": "Aucune image disponible", "No product matches your search.": "Aucun produit ne correspond à votre recherche.", - "No replacement date configured": "Pas de jour de remplacemenet configuré", + "No replacement date configured": "Pas de jour de remplacement configuré", "No results found.": "Aucun résultat trouvé.", "No site configured. Click the button below to add a site.": "Aucun site configuré. Cliquez sur le bouton ci-dessous pour ajouter un site.", "No substitute days have been set up. No time slots will be generated for this week.": "Aucun jour de remplacement configuré. Aucun créneau ne sera généré pour cette semaine.", @@ -719,6 +721,7 @@ "The answer": "La réponse", "The brand associated with the product": "La marque associée au produit", "The customer account was not found.": "Le compte client n'est pas trouvé.", + "The discount applies to the piece (sold unit).": "La remise s'applique à la pièce (unité de vente).", "The employee sync job has been dispatched": "Le job de synchronisation des salariés a été lancé", "The existing encrypted environment file is not in readable format. Use --force to overwrite it.": "The existing encrypted environment file is not in readable format. Use --force to overwrite it.", "The existing encryption key is required to update the encrypted environment file.": "The existing encryption key is required to update the encrypted environment file.", @@ -782,6 +785,7 @@ "Unprocessable Entity": "Entité non traitable", "Unsubscribe": "Se désabonner", "Unsupported Media Type": "Type de média non supporté", + "until :date": "au :date", "Up": "Monter", "Update": "Mettre à jour", "Update :name": "Mettre à jour :name", @@ -855,5 +859,10 @@ "Your password has been changed. If you are not at the origin of this change, please contact us as soon as possible using the contact form or by contacting your manager.": "Votre mot de passe a été changé. Si vous n'êtes pas à l'origine de ceci, veuillez nous contacter au plus vite en utilisant le formulaire de contact ou en vous rapprochant de votre responsable.", "your_message": "Votre message", "Zip code": "Code postal", - "Your search": "Votre recherche" + "Your search": "Votre recherche", + "Choose position": "Choisir une position", + "Move": "Déplacer", + "Move down": "Descendre d'un cran", + "Move up": "Monter d'un cran", + "New position": "Nouvelle position" } diff --git a/resources/ts/bo/utilities/fontawesome.ts b/resources/ts/bo/utilities/fontawesome.ts index 8636dbc3..420d64b9 100644 --- a/resources/ts/bo/utilities/fontawesome.ts +++ b/resources/ts/bo/utilities/fontawesome.ts @@ -33,6 +33,7 @@ import { faHashtag, faHourglassEnd, faInfo, + faListOl, faListUl, faLocationDot, faLock, @@ -129,4 +130,7 @@ library.add(faArrowsRotate); library.add(faFileLines); library.add(faMagnifyingGlass); + +library.add(faListOl); + dom.watch(); diff --git a/resources/ts/fo/components/ProductsViewer/ProductCard.vue b/resources/ts/fo/components/ProductsViewer/ProductCard.vue index ffac76d3..1e201f2f 100644 --- a/resources/ts/fo/components/ProductsViewer/ProductCard.vue +++ b/resources/ts/fo/components/ProductsViewer/ProductCard.vue @@ -73,7 +73,7 @@ >/{{ product.sell_unit_label }} {{ __('Original price') }} :  @@ -143,6 +143,7 @@ interface FilteredProductProp { priceTtc: Money | null; priceKgTtc: Money | null; discountedPriceTtc: Money | null; + showStrippedPrice?: boolean; sell_unit_label?: string | null; nutriscore: Nutriscore | null; is_available: boolean; diff --git a/resources/ts/fo/repositories/product.repository.ts b/resources/ts/fo/repositories/product.repository.ts index 7ba5b7cf..591faadf 100644 --- a/resources/ts/fo/repositories/product.repository.ts +++ b/resources/ts/fo/repositories/product.repository.ts @@ -17,6 +17,7 @@ interface PaginatedProduct { priceTtc: Money | null; priceKgTtc: Money | null; discountedPriceTtc: Money | null; + showStrippedPrice: boolean; nutriscore: Nutriscore | null; is_available: boolean; can_add_to_basket: boolean; diff --git a/resources/ts/fo/schemas/models/product-model.zod.test.ts b/resources/ts/fo/schemas/models/product-model.zod.test.ts new file mode 100644 index 00000000..34a49ee9 --- /dev/null +++ b/resources/ts/fo/schemas/models/product-model.zod.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; + +import { productModelSchema } from "./product-model.zod"; + +describe("productModelSchema", () => { + const baseProductData = { + id: "a0000000-0000-4000-8000-000000000001", + name: "Terrine de Foie Gras", + slug: "terrine-de-foie-gras", + shortDescription: "Domaine de Lanvaux", + picture: "https://example.com/picture.jpg", + picture_title: "Terrine", + picture_alt: "Terrine", + weight_variable: false, + priceTtc: { amount: "1093", currency: "EUR", formatted: "€ 10.93" }, + priceKgTtc: { amount: "4372", currency: "EUR", formatted: "€ 43.72" }, + discountedPriceTtc: { amount: "993", currency: "EUR", formatted: "€ 9.93" }, + sell_unit_label: "pièce", + is_available: true, + can_add_to_basket: true, + nutriscore: null, + }; + + it("parses product with showStrippedPrice true", () => { + // GIVEN + const data = { + ...baseProductData, + showStrippedPrice: true, + }; + + // WHEN + const parsed = productModelSchema.parse(data); + + // THEN + expect(parsed.showStrippedPrice).toBe(true); + }); + + it("parses product with showStrippedPrice false", () => { + // GIVEN + const data = { + ...baseProductData, + showStrippedPrice: false, + }; + + // WHEN + const parsed = productModelSchema.parse(data); + + // THEN + expect(parsed.showStrippedPrice).toBe(false); + }); + + it("defaults showStrippedPrice to false when omitted", () => { + // GIVEN + const data = {...baseProductData,}; + + // WHEN + const parsed = productModelSchema.parse(data); + + // THEN + expect(parsed.showStrippedPrice).toBe(false); + }); +}); diff --git a/resources/ts/fo/schemas/models/product-model.zod.ts b/resources/ts/fo/schemas/models/product-model.zod.ts index d41665f5..d7d4cc84 100644 --- a/resources/ts/fo/schemas/models/product-model.zod.ts +++ b/resources/ts/fo/schemas/models/product-model.zod.ts @@ -16,6 +16,7 @@ export const productModelSchema = z.object({ priceTtc: moneySchema.nullable(), priceKgTtc: moneySchema.nullable(), discountedPriceTtc: moneySchema.nullable(), + showStrippedPrice: z.boolean().default(false), sell_unit_label: z.string().nullable().optional(), is_available: z.boolean(), can_add_to_basket: z.boolean(), diff --git a/resources/ts/fo/schemas/requests/product-filter.zod.ts b/resources/ts/fo/schemas/requests/product-filter.zod.ts index 9f498fce..ba7955b7 100644 --- a/resources/ts/fo/schemas/requests/product-filter.zod.ts +++ b/resources/ts/fo/schemas/requests/product-filter.zod.ts @@ -21,6 +21,7 @@ export const productsFilterResponseSchema = makePaginatedResourceSchema( priceTtc: moneySchema.nullable(), priceKgTtc: moneySchema.nullable(), discountedPriceTtc: moneySchema.nullable(), + showStrippedPrice: z.boolean().default(false), nutriscore: z.enum(Nutriscore).nullable() }) ); diff --git a/resources/ts/fo/services/filter-product.service.ts b/resources/ts/fo/services/filter-product.service.ts index 35cf970e..8bdea0f4 100644 --- a/resources/ts/fo/services/filter-product.service.ts +++ b/resources/ts/fo/services/filter-product.service.ts @@ -19,6 +19,7 @@ export interface ProductFiltered { priceTtc: Money | null; priceKgTtc: Money | null; discountedPriceTtc: Money | null; + showStrippedPrice: boolean; sell_unit_label?: string | null; nutriscore: Nutriscore | null; is_available: boolean; diff --git a/resources/ts/fo/stores/product-viewer.store.ts b/resources/ts/fo/stores/product-viewer.store.ts index 06868967..b42d0062 100644 --- a/resources/ts/fo/stores/product-viewer.store.ts +++ b/resources/ts/fo/stores/product-viewer.store.ts @@ -23,6 +23,7 @@ interface FilteredProduct { priceTtc: Money | null; priceKgTtc: Money | null; discountedPriceTtc: Money | null; + showStrippedPrice: boolean; sell_unit_label?: string | null; nutriscore: Nutriscore | null; is_available: boolean; diff --git a/resources/ts/fo/types/product.type.ts b/resources/ts/fo/types/product.type.ts index a25d8b33..03c2f26c 100644 --- a/resources/ts/fo/types/product.type.ts +++ b/resources/ts/fo/types/product.type.ts @@ -20,5 +20,6 @@ export interface Product { priceTtc: Money | null priceKgTtc: Money | null discountedPriceTtc: Money | null + showStrippedPrice?: boolean sell_unit_label?: string | null } diff --git a/resources/views/bo/discounts/form.blade.php b/resources/views/bo/discounts/form.blade.php index a83a14eb..85df1b12 100644 --- a/resources/views/bo/discounts/form.blade.php +++ b/resources/views/bo/discounts/form.blade.php @@ -31,13 +31,16 @@
{{ Str::ucfirst(__('validation.custom.attributes.discount_value')) }}* + + + {{-- INPUT MONTANT --}}
+ aria-describedby="discount-value-help" {{ $isAmount ? 'required' : 'disabled' }}> @currency()
@@ -45,11 +48,15 @@
+ max="100" aria-describedby="discount-value-help" {{ $isPercent ? 'required' : 'disabled' }}> %
- @include('bo.modules.input-error', ['inputName' => 'value']) + @include('bo.modules.input-error', [ + 'inputName' => 'value', + 'helperId' => 'discount-value-help', + 'helper' => __('The discount applies to the piece (sold unit).'), + ])
diff --git a/resources/views/bo/discounts/index-list.blade.php b/resources/views/bo/discounts/index-list.blade.php index 3e8d582a..03bf7894 100644 --- a/resources/views/bo/discounts/index-list.blade.php +++ b/resources/views/bo/discounts/index-list.blade.php @@ -32,7 +32,7 @@ href="{{ route('bo.products.index', [ 'search' => '', 'brand' => '', - 'discount' => 1, + 'discount' => $discount->id, 'tag' => '', 'range' => '', ]) }}" diff --git a/resources/views/bo/modules/change-order.blade.php b/resources/views/bo/modules/change-order.blade.php index 396c1033..32ed87b1 100644 --- a/resources/views/bo/modules/change-order.blade.php +++ b/resources/views/bo/modules/change-order.blade.php @@ -27,21 +27,49 @@ $showReset = !empty($searchQuery) || $hasCustomSort; @endphp @if (!$noOrder) - -
- @csrf - @method('PATCH') - - @if (!$first) - + +
+ #{{ $model->order }} + @if (isset($selectRoute)) + @endif - @if (!$last) - - @endif - +
+
+
+ @csrf + @method('PATCH') + + @if (!$first) + + @endif + @if (!$last) + + @endif +
+ +
+ @endif - diff --git a/resources/views/bo/products/index-filters.blade.php b/resources/views/bo/products/index-filters.blade.php index aad8a5e7..be7a38d9 100644 --- a/resources/views/bo/products/index-filters.blade.php +++ b/resources/views/bo/products/index-filters.blade.php @@ -52,16 +52,30 @@ -
+
{{-- DISCOUNT --}}
- -
- -
+ +
-
+
{{-- STAR --}}
@@ -75,8 +89,8 @@ 'brand' => '', 'tag' => '', 'range' => '', + 'discount' => '', 'star' => null, - 'discount' => null, ]) }}" title="{{ __('Reset filters') }}"> diff --git a/resources/views/bo/products/index-list.blade.php b/resources/views/bo/products/index-list.blade.php index 810f393e..26c212fa 100644 --- a/resources/views/bo/products/index-list.blade.php +++ b/resources/views/bo/products/index-list.blade.php @@ -75,6 +75,7 @@ @if (!request()->routeIs('bo.merch.starred')) @include('bo.modules.change-order', [ 'route' => 'bo.products.change-order', + 'selectRoute' => 'bo.products.change-selected-order', 'model' => $product, 'first' => $loop->first, 'last' => $loop->last, diff --git a/resources/views/bo/products/index.blade.php b/resources/views/bo/products/index.blade.php index 34502fad..cb00b4fd 100644 --- a/resources/views/bo/products/index.blade.php +++ b/resources/views/bo/products/index.blade.php @@ -37,7 +37,7 @@
@if (!request()->routeIs('bo.merch.starred')) @include('bo.modules.search-bar', compact('searchFields')) - @include('bo.products.index-filters', compact('brands', 'ranges')) + @include('bo.products.index-filters', compact('brands', 'ranges', 'tags', 'discounts')) @endif @if ($products->count() > \Domain\Enums\Pagination\ItemsPerPaginationEnum::five->value())
diff --git a/resources/views/bo/shops/pickup-exceptions.blade.php b/resources/views/bo/shops/pickup-exceptions.blade.php index 8ac06204..0422e11f 100644 --- a/resources/views/bo/shops/pickup-exceptions.blade.php +++ b/resources/views/bo/shops/pickup-exceptions.blade.php @@ -86,7 +86,6 @@ ); $noReplacement = - empty($associatedException?->pivot?->order_deadline_at) || empty($associatedException?->pivot?->replacement_date); $isCritical = $dto->missingSubsitute || $dto->passedDeadline; diff --git a/resources/views/fo/home-parts/sliders/discounts.blade.php b/resources/views/fo/home-parts/sliders/discounts.blade.php index 19a248e8..358e99c3 100644 --- a/resources/views/fo/home-parts/sliders/discounts.blade.php +++ b/resources/views/fo/home-parts/sliders/discounts.blade.php @@ -54,7 +54,7 @@ {{ __('Approximately') }}* @endif - + {{ __('Current price') }} :  @include('fo.modules.guarded-currency', [ 'money' => $productWithPricing->pricing->hasDiscount @@ -64,7 +64,7 @@ ]) - @if ($productWithPricing->product->validDiscount?->is_old_price_displayed) + @if ($productWithPricing->pricing->hasDiscount && $productWithPricing->product->validDiscount?->is_old_price_displayed) {{ __('Original price') }} :  @include('fo.modules.guarded-currency', [ diff --git a/resources/views/fo/pages/products/show-price-info.blade.php b/resources/views/fo/pages/products/show-price-info.blade.php index 36e5512c..8d25878a 100644 --- a/resources/views/fo/pages/products/show-price-info.blade.php +++ b/resources/views/fo/pages/products/show-price-info.blade.php @@ -7,7 +7,7 @@ @endif

- + {{ __('Current price') }} :  @include('fo.modules.guarded-currency', [ 'money' => $productWithPricing->pricing->hasDiscount @@ -17,7 +17,7 @@ ]) - @if ($productWithPricing->product->validDiscount?->is_old_price_displayed) + @if ($productWithPricing->pricing->hasDiscount && $productWithPricing->product->validDiscount?->is_old_price_displayed) {{ __('Original price') }} :  @include('fo.modules.guarded-currency', [ @@ -30,7 +30,7 @@

- {{ $productWithPricing->product->weight_variable ? __('Product sold by the kilo') : __('Price per kilo') }} : + {{ $productWithPricing->product->weight_variable ? '*' . __('Product sold by the kilo') : __('Price per kilo') }} : @include('fo.modules.guarded-currency', [ 'money' => $productWithPricing->pricing->priceKgTtc(), 'product' => $productWithPricing->product, diff --git a/routes/web-bo.php b/routes/web-bo.php index 4d1fc39b..a13170e2 100644 --- a/routes/web-bo.php +++ b/routes/web-bo.php @@ -78,6 +78,7 @@ Route::middleware(['auth:backend', 'has-role:Admin'])->group(function (): void { Route::post('/products/mass-actions', [ProductsController::class, 'massActions'])->name('products.mass-actions'); Route::patch('/products/{product}/toggle-status', [ProductsController::class, 'toggleStatus'])->name('products.toggle-status'); Route::patch('/products/{product}/toggle-star', [ProductsController::class, 'toggleStar'])->name('products.toggle-star'); + Route::patch('/products/{product}/change-selected-order', [ProductsController::class, 'changeSelectedOrder'])->name('products.change-selected-order'); Route::patch('/products/{product}/{action}', [ProductsController::class, 'changeOrder'])->name('products.change-order'); // * PRODUCTS INCO diff --git a/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php index c9648120..57b22010 100644 --- a/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/DiscountsControllerTest.php @@ -61,6 +61,11 @@ describe('DiscountsController', function (): void { it('can access index', function (): void { /** @var \Tests\TestCase $this */ // GIVEN + $discount = new Discount(); + $discount->type = DiscountType::PERCENT; + $discount->value = DiscountValue::fromPercentage(20); + $discount->is_old_price_displayed = true; + $discount->save(); // WHEN $response = $this->get('/bo/discounts'); @@ -68,6 +73,7 @@ describe('DiscountsController', function (): void { // THEN expect($response->status())->toBe(200); $response->assertViewIs('bo.discounts.index'); + $response->assertSee("discount={$discount->id}"); }); it('can access create', function (): void { diff --git a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php index faa68351..25793f4c 100644 --- a/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Bo/ProductsControllerTest.php @@ -3,16 +3,19 @@ declare(strict_types=1); use App\Models\Customer; +use App\Models\Discount; use App\Models\Product; use App\Models\Range; use App\Models\Tag; 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('ProductsController', function () { @@ -33,6 +36,106 @@ describe('ProductsController', function () { expect($response->status())->toBe(200); }); + it('can filter products by specific discount id and all discounts', function () { + // GIVEN + /** @var \Tests\TestCase $this */ + $discount1 = new Discount(); + $discount1->type = DiscountType::PERCENT; + $discount1->value = DiscountValue::fromPercentage(20); + $discount1->is_old_price_displayed = true; + $discount1->save(); + + $discount2 = new Discount(); + $discount2->type = DiscountType::AMOUNT; + $discount2->value = DiscountValue::fromAmount(Money::EUR(500)); + $discount2->is_old_price_displayed = false; + $discount2->save(); + + $range = new Range(); + $range->name = 'Range ' . uniqid(); + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $prod1 = new Product([ + 'range_id' => $range->id, + 'name' => 'Prod Discount 1 ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Test description', + 'status' => true, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $prod1->price = Money::EUR(1000); + $prod1->discount_id = $discount1->id; + $prod1->save(); + + $prod2 = new Product([ + 'range_id' => $range->id, + 'name' => 'Prod Discount 2 ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Test description', + 'status' => true, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $prod2->price = Money::EUR(1000); + $prod2->discount_id = $discount2->id; + $prod2->save(); + + $prod3 = new Product([ + 'range_id' => $range->id, + 'name' => 'Prod Regular 3 ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Test description', + 'status' => true, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $prod3->price = Money::EUR(1000); + $prod3->save(); + + // WHEN (filtering by specific discount1) + $response1 = $this->get("/bo/products?discount={$discount1->id}"); + + // THEN + $response1->assertOk(); + $response1->assertSee($prod1->name); + $response1->assertDontSee($prod2->name); + $response1->assertDontSee($prod3->name); + $response1->assertSee("value=\"{$discount1->id}\" selected", false); + + // WHEN (filtering by all discounts: discount=0) + $responseAll = $this->get('/bo/products?discount=0'); + + // THEN + $responseAll->assertOk(); + $responseAll->assertSee($prod1->name); + $responseAll->assertSee($prod2->name); + $responseAll->assertDontSee($prod3->name); + $responseAll->assertSee('value="0" selected', false); + }); + it('can access create', function () { // WHEN $response = $this->get('/bo/products/create'); @@ -366,6 +469,73 @@ describe('ProductsController', function () { expect($response->status())->toBe(302); }); + it('can change selected order to specific position', function (): void { + /** @var \Tests\TestCase $this */ + // GIVEN + $range = new Range(); + $range->name = 'Test Range ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 9999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $product1 = new Product([ + 'range_id' => $range->id, + 'name' => 'Test Product 1 ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Test description', + 'status' => true, + ]); + $product1->price = Money::EUR(1000); + $product1->short_description = 'Short test description'; + $product1->picture_alt = 'test alt'; + $product1->picture_title = 'test title'; + $product1->picture_large_alt = 'test alt'; + $product1->picture_large_title = 'test title'; + $product1->save(); + $product1->setOrder(1); + $product1->save(); + + $product2 = new Product([ + 'range_id' => $range->id, + 'name' => 'Test Product 2 ' . uniqid(), + 'brand' => ProductBrand::loue, + 'invoicing_unit' => InvoicingUnit::PCE, + 'sell_unit' => SellUnit::PCE, + 'order_unit' => OrderUnit::PCE, + 'tax_rate' => TaxRate::TVA_20, + 'description' => 'Test description', + 'status' => true, + ]); + $product2->price = Money::EUR(1000); + $product2->short_description = 'Short test description'; + $product2->picture_alt = 'test alt'; + $product2->picture_title = 'test title'; + $product2->picture_large_alt = 'test alt'; + $product2->picture_large_title = 'test title'; + $product2->save(); + $product2->setOrder(2); + $product2->save(); + + // WHEN + $response = $this->patch("/bo/products/{$product2->slug}/change-selected-order", [ + 'order' => 1, + ]); + + // THEN + $response->assertSessionHasNoErrors(); + $response->assertRedirect(); + $product1->refresh(); + $product2->refresh(); + expect($product2->getOrder())->toBe(1) + ->and($product1->getOrder())->toBe(2); + }); + describe('mass actions', function () { beforeEach(function (): void { /** @var \Tests\TestCase $this */ diff --git a/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php index efaaf3d3..c1e57e06 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Ajax/ProductsControllerTest.php @@ -2,10 +2,25 @@ declare(strict_types=1); +use App\Models\Customer; +use App\Models\Discount; use App\Models\Page; +use App\Models\Product; +use App\Models\Range; use Database\Seeders\ContentSeeder; +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 Domain\Models\ValueObjects\Email; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\View; +use Money\Money; +use Ramsey\Uuid\Uuid; +use Shared\ValueObjects\CrmHashcode; describe('ProductsController (Ajax)', function () { it('can filter products via ajax', function () { @@ -50,4 +65,133 @@ describe('ProductsController (Ajax)', function () { ], ]); }); + + it('returns showStrippedPrice false when discount is_old_price_displayed is false', function () { + // GIVEN + /** @var \Tests\TestCase $this */ + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + $customer = new Customer(); + $customer->email = new Email('test1@example.com'); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $range = new Range(); + $range->name = 'Gamme test sans ancien prix'; + $range->status = true; + $range->order = 1; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $discount = new Discount(); + $discount->type = DiscountType::AMOUNT; + $discount->value = DiscountValue::fromAmount(Money::EUR(100)); + $discount->is_old_price_displayed = false; + $discount->save(); + + $product = new Product([ + 'range_id' => $range->id, + 'name' => 'Produit Promo Sans Ancien Prix', + '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 = 1; + $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->discount_id = $discount->id; + $product->save(); + + // WHEN + $response = $this->getJson(route('ajax.products.filter', [ + 'search' => 'Produit Promo Sans Ancien Prix', + ])); + + // THEN + $response->assertOk(); + /** @var array> $data */ + $data = $response->json('data'); + expect($data)->not->toBeEmpty() + ->and($data[0]['showStrippedPrice'])->toBeFalse() + ->and($data[0]['discountedPriceTtc'])->not->toBeNull(); + }); + + it('returns showStrippedPrice true when discount is_old_price_displayed is true', function () { + // GIVEN + /** @var \Tests\TestCase $this */ + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + Cache::flush(); + $customer = new Customer(); + $customer->email = new Email('test2@example.com'); + $customer->hashcode = new CrmHashcode(Uuid::uuid4()); + $customer->save(); + $this->actingAs($customer, 'frontend'); + + $range = new Range(); + $range->name = 'Gamme test avec ancien prix'; + $range->status = true; + $range->order = 2; + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + $discount = new Discount(); + $discount->type = DiscountType::AMOUNT; + $discount->value = DiscountValue::fromAmount(Money::EUR(100)); + $discount->is_old_price_displayed = true; + $discount->save(); + + $product = new Product([ + 'range_id' => $range->id, + 'name' => 'Produit Promo Avec Ancien Prix', + '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 = 2; + $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->discount_id = $discount->id; + $product->save(); + + // WHEN + $response = $this->getJson(route('ajax.products.filter', [ + 'search' => 'Produit Promo Avec Ancien Prix', + ])); + + // THEN + $response->assertOk(); + /** @var array> $data */ + $data = $response->json('data'); + expect($data)->not->toBeEmpty() + ->and($data[0]['showStrippedPrice'])->toBeTrue() + ->and($data[0]['discountedPriceTtc'])->not->toBeNull(); + }); }); + diff --git a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php index b37909ea..be346894 100644 --- a/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php +++ b/tests/Feature/App/Http/Controllers/Fo/Pages/HomeControllerTest.php @@ -2,15 +2,18 @@ declare(strict_types=1); +use App\Models\Discount; use App\Models\Page; use App\Models\Product; use App\Models\Range; use App\Models\Slide; use Database\Seeders\ContentSeeder; +use Domain\Enums\DiscountType; use Domain\Enums\ProductBrand; use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; +use Domain\Models\ValueObjects\DiscountValue; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\View; use Money\Money; @@ -121,4 +124,90 @@ describe('HomeController', function () { $response->assertDontSee('id="hero-carousel"', false); $response->assertDontSee('Expired Promo'); }); + + it('displays promo prices in red for discounted star products on homepage', function () { + /** @var \Tests\TestCase $this */ + // GIVEN + $this->seed(ContentSeeder::class); + View::share('PageList', Page::getCached() + ->mapWithKeys(fn ($page) => [ + $page->slug->value() => $page, + ])); + + $range = new Range(); + $range->name = 'Boucherie'; + $range->slug = 'boucherie'; + $range->picture = 'ranges/boucherie.jpg'; + $range->picture_alt = 'Boucherie'; + $range->picture_title = 'Boucherie'; + $range->status = true; + $range->order = 1; + $range->save(); + + $discount = new Discount(); + $discount->type = DiscountType::PERCENT; + $discount->value = DiscountValue::fromPercentage(10); + $discount->is_old_price_displayed = false; + $discount->date_start = Carbon::yesterday(); + $discount->date_end = Carbon::tomorrow(); + $discount->save(); + + $promoProduct = new Product(); + $promoProduct->id = (string) Uuid::uuid7(); + $promoProduct->name = 'Foie Gras Promo'; + $promoProduct->brand = ProductBrand::loue; + $promoProduct->slug = 'foie-gras-promo'; + $promoProduct->description = 'Foie Gras en promo'; + $promoProduct->picture_alt = 'Foie Gras Promo'; + $promoProduct->picture_title = 'Foie Gras Promo'; + $promoProduct->picture_large_alt = 'Foie Gras Promo'; + $promoProduct->picture_large_title = 'Foie Gras Promo'; + $promoProduct->price = Money::EUR(2000); + $promoProduct->invoicing_unit = InvoicingUnit::PCE; + $promoProduct->sell_unit = SellUnit::PCE; + $promoProduct->tax_rate = TaxRate::TVA_5_5; + $promoProduct->stock = 10; + $promoProduct->range_id = $range->id; + $promoProduct->order = 1; + $promoProduct->star = true; + $promoProduct->status = true; + $promoProduct->discount_id = $discount->id; + $promoProduct->save(); + + $regularProduct = new Product(); + $regularProduct->id = (string) Uuid::uuid7(); + $regularProduct->name = 'Poulet Standard'; + $regularProduct->brand = ProductBrand::loue; + $regularProduct->slug = 'poulet-standard'; + $regularProduct->description = 'Poulet standard sans promo'; + $regularProduct->picture_alt = 'Poulet Standard'; + $regularProduct->picture_title = 'Poulet Standard'; + $regularProduct->picture_large_alt = 'Poulet Standard'; + $regularProduct->picture_large_title = 'Poulet Standard'; + $regularProduct->price = Money::EUR(1500); + $regularProduct->invoicing_unit = InvoicingUnit::PCE; + $regularProduct->sell_unit = SellUnit::PCE; + $regularProduct->tax_rate = TaxRate::TVA_5_5; + $regularProduct->stock = 10; + $regularProduct->range_id = $range->id; + $regularProduct->order = 2; + $regularProduct->star = true; + $regularProduct->status = true; + $regularProduct->discount_id = null; + $regularProduct->save(); + + // WHEN + $response = $this->get('/'); + + // THEN + $response->assertOk(); + $content = $response->getContent(); + expect($content)->toContain('Foie Gras Promo') + ->and($content)->toContain('Poulet Standard'); + + // Promo product price span has text-danger class + expect($content)->toMatch('/Foie Gras Promo.*?/s') + // Regular product price span does NOT have text-danger class + ->and($content)->toMatch('/Poulet Standard.*?/s'); + }); }); diff --git a/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php b/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php index 2b48ec22..30325936 100644 --- a/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php +++ b/tests/Feature/App/Http/Requests/Bo/Products/IndexProductRequestTest.php @@ -59,4 +59,27 @@ describe('IndexProductRequest', function () { // THEN expect(true)->toBeTrue(); }); + + it('resolves discount filter correctly in toGetBoPaginatedProductsQueryInput', function () { + // GIVEN + $authService = mock(AppAdminAuthService::class); + $request = new IndexProductRequest($authService); + $request->initialize(['discount' => '0']); + + // WHEN + $input = $request->toGetBoPaginatedProductsQueryInput(); + + // THEN + expect($input->discount)->toBe('0'); + + // GIVEN + $requestWithId = new IndexProductRequest($authService); + $requestWithId->initialize(['discount' => '42']); + + // WHEN + $inputWithId = $requestWithId->toGetBoPaginatedProductsQueryInput(); + + // THEN + expect($inputWithId->discount)->toBe('42'); + }); }); diff --git a/tests/Feature/Bo/Settings/SettingsControllerTest.php b/tests/Feature/Bo/Settings/SettingsControllerTest.php index a9636a4d..3c9b2fba 100644 --- a/tests/Feature/Bo/Settings/SettingsControllerTest.php +++ b/tests/Feature/Bo/Settings/SettingsControllerTest.php @@ -16,9 +16,10 @@ describe('SettingsController', function (): void { $response = $this->actingAs($user, 'backend')->get($route); // THEN - $response->assertOk() - ->assertViewIs('bo.settings.edit') - ->assertViewHas('setting'); + $response->assertForbidden(); + // $response->assertOk() + // ->assertViewIs('bo.settings.edit') + // ->assertViewHas('setting'); }); it('updates employee sites with array input and redirects', function (): void { @@ -34,11 +35,12 @@ describe('SettingsController', function (): void { $response = $this->actingAs($user, 'backend')->put($route, $formData); // THEN - $response->assertRedirect(route('bo.settings.edit')) - ->assertSessionHas('success'); + $response->assertForbidden(); + // $response->assertRedirect(route('bo.settings.edit')) + // ->assertSessionHas('success'); - $setting = Setting::getSingleton(); - expect($setting->employee_sites)->toBe(['PA', 'LY', 'NA']); + // $setting = Setting::getSingleton(); + // expect($setting->employee_sites)->toBe(['PA', 'LY', 'NA']); }); it('updates employee sites with comma string input and redirects', function (): void { @@ -54,11 +56,12 @@ describe('SettingsController', function (): void { $response = $this->actingAs($user, 'backend')->put($route, $formData); // THEN - $response->assertRedirect(route('bo.settings.edit')) - ->assertSessionHas('success'); + $response->assertForbidden(); + // $response->assertRedirect(route('bo.settings.edit')) + // ->assertSessionHas('success'); - $setting = Setting::getSingleton(); - expect($setting->employee_sites)->toBe(['PA', 'LY', 'NA']); + // $setting = Setting::getSingleton(); + // expect($setting->employee_sites)->toBe(['PA', 'LY', 'NA']); }); it('rejects invalid site code formats', function (): void { diff --git a/tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderPositionTest.php b/tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderPositionTest.php new file mode 100644 index 00000000..4776e195 --- /dev/null +++ b/tests/Integration/WithApp/App/Actions/Common/ChangeModelOrderPositionTest.php @@ -0,0 +1,134 @@ +create(); + $tag1->setOrder(1); + $tag1->save(); + + $tag2 = Tag::factory()->create(); + $tag2->setOrder(2); + $tag2->save(); + + $tag3 = Tag::factory()->create(); + $tag3->setOrder(3); + $tag3->save(); + + $action = new ChangeModelOrderPosition(); + $input = new ChangeModelOrderPositionInput($tag3, 1); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeTrue(); + + $fresh1 = Tag::query()->find($tag1->id); + $fresh2 = Tag::query()->find($tag2->id); + $fresh3 = Tag::query()->find($tag3->id); + + expect($fresh3?->getOrder())->toBe(1) + ->and($fresh1?->getOrder())->toBe(2) + ->and($fresh2?->getOrder())->toBe(3); + }); + + it('shifts orders when moving a model down to target position', function (): void { + // GIVEN + $tag1 = Tag::factory()->create(); + $tag1->setOrder(1); + $tag1->save(); + + $tag2 = Tag::factory()->create(); + $tag2->setOrder(2); + $tag2->save(); + + $tag3 = Tag::factory()->create(); + $tag3->setOrder(3); + $tag3->save(); + + $action = new ChangeModelOrderPosition(); + $input = new ChangeModelOrderPositionInput($tag1, 3); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeTrue(); + + $fresh1 = Tag::query()->find($tag1->id); + $fresh2 = Tag::query()->find($tag2->id); + $fresh3 = Tag::query()->find($tag3->id); + + expect($fresh2?->getOrder())->toBe(1) + ->and($fresh3?->getOrder())->toBe(2) + ->and($fresh1?->getOrder())->toBe(3); + }); + + it('returns true without modification when target order is identical to current order', function (): void { + // GIVEN + $tag = Tag::factory()->create(); + $tag->setOrder(2); + $tag->save(); + + $action = new ChangeModelOrderPosition(); + $input = new ChangeModelOrderPositionInput($tag, 2); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeTrue(); + $fresh = Tag::query()->find($tag->id); + expect($fresh?->getOrder())->toBe(2); + }); + + it('clamps target order to maximum existing order when target exceeds max', function (): void { + // GIVEN + $tag1 = Tag::factory()->create(); + $tag1->setOrder(1); + $tag1->save(); + + $tag2 = Tag::factory()->create(); + $tag2->setOrder(2); + $tag2->save(); + + $action = new ChangeModelOrderPosition(); + $input = new ChangeModelOrderPositionInput($tag1, 100); + + // WHEN + $result = $action($input); + + // THEN + expect($result)->toBeTrue(); + + $fresh1 = Tag::query()->find($tag1->id); + $fresh2 = Tag::query()->find($tag2->id); + + expect($fresh2?->getOrder())->toBe(1) + ->and($fresh1?->getOrder())->toBe(2); + }); + + it('throws when an invalid input is passed', function (): void { + // GIVEN + $action = new ChangeModelOrderPosition(); + $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/Products/GetBoPaginatedProductsQueryTest.php b/tests/Integration/WithApp/App/Queries/Products/GetBoPaginatedProductsQueryTest.php new file mode 100644 index 00000000..6fd5ecd3 --- /dev/null +++ b/tests/Integration/WithApp/App/Queries/Products/GetBoPaginatedProductsQueryTest.php @@ -0,0 +1,116 @@ +name = 'Gamme ' . uniqid(); + $range->status = true; + $range->order = random_int(1, 9999); + $range->picture_alt = 'alt'; + $range->picture_title = 'title'; + $range->save(); + + return $range; + }; + + $createProduct = function (string $name, Range $range, ?int $discountId = null): 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, + 'picture_alt' => 'alt', + 'picture_title' => 'title', + 'picture_large_alt' => 'alt', + 'picture_large_title' => 'title', + ]); + $product->order = random_int(1, 999999); + $product->price = Money::EUR(1000); + $product->discount_id = $discountId; + $product->save(); + + return $product; + }; + + it('returns discounts collection and filters by specific discount or all discounts', function () use ($createRange, $createProduct): void { + // GIVEN + $discount1 = new Discount(); + $discount1->type = DiscountType::PERCENT; + $discount1->value = DiscountValue::fromPercentage(20); + $discount1->is_old_price_displayed = true; + $discount1->save(); + + $discount2 = new Discount(); + $discount2->type = DiscountType::AMOUNT; + $discount2->value = DiscountValue::fromAmount(Money::EUR(500)); + $discount2->is_old_price_displayed = false; + $discount2->save(); + + $range = $createRange(); + $prod1 = $createProduct('Prod with Discount 1', $range, $discount1->id); + $prod2 = $createProduct('Prod with Discount 2', $range, $discount2->id); + $prod3 = $createProduct('Prod without Discount', $range, null); + + $query = app(GetBoPaginatedProductsQuery::class); + $pagination = Pagination::ofPage(new PageNumber(1), new PageSize(10)); + + // WHEN: no filter + $outputAll = $query(new GetBoPaginatedProductsQueryInput(pagination: $pagination)); + + // THEN + expect($outputAll->discounts->count())->toBeGreaterThanOrEqual(2) + ->and($outputAll->discounts->has($discount1->id))->toBeTrue() + ->and($outputAll->discounts->get($discount1->id))->toContain("#{$discount1->id} - Pourcentage (20 %)") + ->and($outputAll->products->total())->toBeGreaterThanOrEqual(3); + + // WHEN: filter by specific discount 1 + $outputDiscount1 = $query(new GetBoPaginatedProductsQueryInput( + pagination: $pagination, + discount: (string) $discount1->id, + )); + + // THEN + $ids1 = collect($outputDiscount1->products->items())->pluck('id')->all(); + expect($ids1)->toContain($prod1->id) + ->and($ids1)->not->toContain($prod2->id) + ->and($ids1)->not->toContain($prod3->id); + + // WHEN: filter by all discounts (discount: '0') + $outputDiscountAll = $query(new GetBoPaginatedProductsQueryInput( + pagination: $pagination, + discount: '0', + )); + + // THEN + $idsAll = collect($outputDiscountAll->products->items())->pluck('id')->all(); + expect($idsAll)->toContain($prod1->id) + ->and($idsAll)->toContain($prod2->id) + ->and($idsAll)->not->toContain($prod3->id); + }); +}); diff --git a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php index 25480153..0718e9db 100644 --- a/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php +++ b/tests/Integration/WithApp/Infra/Adapters/Repositories/EloquentPickupExceptionRepositoryTest.php @@ -77,6 +77,8 @@ it('retrieves exceptions within a period for a shop', function () { DB::table('shop_pickup_exception')->insert([ 'shop_id' => $shop->id, 'pickup_exception_id' => $ex1->id, + 'replacement_date' => '2023-01-11', + 'order_deadline_at' => '2023-01-09 10:00:00', ]); $shopId = new ShopId($shopUuid); @@ -90,7 +92,9 @@ it('retrieves exceptions within a period for a shop', function () { // THEN expect($result)->toHaveCount(1) ->and($result[0])->toBeInstanceOf(ShopPickupOverride::class) - ->and($result[0]->exception->id->value->toString())->toBe($exUuid->toString()); + ->and($result[0]->exception->id->value->toString())->toBe($exUuid->toString()) + ->and($result[0]->replacementDate?->format('Y-m-d'))->toBe('2023-01-11') + ->and($result[0]->orderDeadlineAt?->format('Y-m-d H:i:s'))->toBe('2023-01-09 10:00:00'); }); it('retrieves all exceptions', function () { diff --git a/tests/Unit/App/Actions/Common/ChangeModelOrderPositionInputTest.php b/tests/Unit/App/Actions/Common/ChangeModelOrderPositionInputTest.php new file mode 100644 index 00000000..ed3aadf2 --- /dev/null +++ b/tests/Unit/App/Actions/Common/ChangeModelOrderPositionInputTest.php @@ -0,0 +1,50 @@ +model)->toBe($mock) + ->and($input->targetOrder)->toBe(5); + }); + + it('throws when target order is less than 1', function (): void { + // GIVEN + $mock = new class () extends Model implements ModelWithOrder + { + public function getOrder(): int + { + return 1; + } + + public function setOrder(int $order): void + { + } + }; + + // WHEN & THEN + expect(fn () => new ChangeModelOrderPositionInput(model: $mock, targetOrder: 0)) + ->toThrow(\InvalidArgumentException::class); + }); +}); diff --git a/tests/Unit/Domain/Services/PricingServiceTest.php b/tests/Unit/Domain/Services/PricingServiceTest.php index 70963236..9536924b 100644 --- a/tests/Unit/Domain/Services/PricingServiceTest.php +++ b/tests/Unit/Domain/Services/PricingServiceTest.php @@ -17,6 +17,21 @@ use Money\Currency; use Money\Money; use Ramsey\Uuid\Uuid; +/** + * @param array{ + * id?: \Domain\Models\ValueObjects\Entities\ProductId, + * price?: \Money\Money, + * tax_rate?: \Domain\Enums\TaxRate, + * product_weight?: \Domain\Models\ValueObjects\ProductWeight|null, + * invoicing_unit?: \Domain\Enums\Units\InvoicingUnit, + * sell_unit?: \Domain\Enums\SellUnit, + * validDiscount?: \Domain\Models\ValueObjects\DiscountValue|null, + * status?: bool, + * orderable_start?: \Carbon\CarbonImmutable|null, + * orderable_end?: \Carbon\CarbonImmutable|null, + * hasInco?: bool, + * } $attributes + */ function createBaseProduct(array $attributes = []): Product { $currency = new Currency('EUR'); @@ -44,7 +59,7 @@ function createBaseProduct(array $attributes = []): Product product_weight: $data['product_weight'], invoicing_unit: $data['invoicing_unit'], sell_unit: $data['sell_unit'], - validDiscount: $data['validDiscount'] ? clone $data['validDiscount'] : null, + validDiscount: $data['validDiscount'] instanceof DiscountValue ? clone $data['validDiscount'] : null, status: $data['status'], orderable_start: $data['orderable_start'], orderable_end: $data['orderable_end'], @@ -231,4 +246,117 @@ describe(PricingService::class, function (): void { // THEN expect($result->discountRate->basisPoints())->toBe(0); }); + + it('calculates the price per KG TTC for a product invoiced by KGM and sold by PCE', function (): void { + // GIVEN + $currency = new Currency('EUR'); + $product = createBaseProduct([ + 'price' => new Money(865, $currency), // 8.65 €/kg + 'tax_rate' => TaxRate::TVA_5_5, + 'invoicing_unit' => InvoicingUnit::KGM, + 'sell_unit' => SellUnit::PCE, + 'product_weight' => createWeight(360), // 360g + 'status' => true, + ]); + + $service = new PricingService(); + + // WHEN + $result = $service->calculateForProduct($product); + + // THEN + expect($result->basePriceHt()->getAmount())->toBe('312') + ->and($result->basePriceTtc()->getAmount())->toBe('330') + ->and($result->priceKgTtc()->getAmount())->toBe('913'); + }); + + it('calculates the price per KG TTC for a product invoiced by KGM with percentage discount', function (): void { + // GIVEN + $currency = new Currency('EUR'); + $discount = createDiscount( + amount: new Money(0, $currency), + isPercentage: true, + percentageRate: 10.0 + ); + + $product = createBaseProduct([ + 'price' => new Money(865, $currency), // 8.65 €/kg + 'tax_rate' => TaxRate::TVA_5_5, + 'invoicing_unit' => InvoicingUnit::KGM, + 'sell_unit' => SellUnit::PCE, + 'product_weight' => createWeight(360), // 360g + 'validDiscount' => $discount, + 'status' => true, + ]); + + $service = new PricingService(); + + // WHEN + $result = $service->calculateForProduct($product); + + // THEN + expect($result->discountedPriceHt()->getAmount())->toBe('280') + ->and($result->discountedPriceTtc()->getAmount())->toBe('296') + ->and($result->priceKgTtc()->getAmount())->toBe('821'); + }); + + it('calculates the price per KG TTC for a product invoiced by KGM with fixed amount discount', function (): void { + // GIVEN + $currency = new Currency('EUR'); + $discount = createDiscount( + amount: new Money(50, $currency), + isPercentage: false + ); + + $product = createBaseProduct([ + 'price' => new Money(865, $currency), // 8.65 €/kg + 'tax_rate' => TaxRate::TVA_5_5, + 'invoicing_unit' => InvoicingUnit::KGM, + 'sell_unit' => SellUnit::PCE, + 'product_weight' => createWeight(360), + 'validDiscount' => $discount, + 'status' => true, + ]); + + $service = new PricingService(); + + // WHEN + $result = $service->calculateForProduct($product); + + // THEN + // 50 cts off a 360 g piece => 139 cts off per kg (rounded up): (865 - 139) HT x 1.055 + expect($result->discountedPriceTtc()->getAmount())->toBe('277') + ->and($result->priceKgTtc()->getAmount())->toBe('766'); + }); + + it('caps the discount at the piece price when a fixed discount exceeds the piece price', function (): void { + // GIVEN + $currency = new Currency('EUR'); + $discount = createDiscount( + amount: new Money(500, $currency), // 5.00 € discount on a 3.12 € piece + isPercentage: false + ); + + $product = createBaseProduct([ + 'price' => new Money(865, $currency), // 8.65 €/kg => 3.12 € HT for 360g + 'tax_rate' => TaxRate::TVA_5_5, + 'invoicing_unit' => InvoicingUnit::KGM, + 'sell_unit' => SellUnit::PCE, + 'product_weight' => createWeight(360), + 'validDiscount' => $discount, + 'status' => true, + ]); + + $service = new PricingService(); + + // WHEN + $result = $service->calculateForProduct($product); + + // THEN + expect($result->discountAmountHt()->getAmount())->toBe('312') + ->and($result->discountedPriceHt()->getAmount())->toBe('0') + ->and($result->discountedPriceTtc()->getAmount())->toBe('0') + ->and($result->priceKgTtc()->getAmount())->toBe('0') + ->and($result->discountRate->basisPoints())->toBe(10000); + }); });