Merge branch 'develop' into trunk

This commit is contained in:
Jérémy Munsch 2026-10-29 17:06:40 +01:00
commit 62363253ce
No known key found for this signature in database
GPG key ID: 2AAECDA6B7330F91
46 changed files with 1355 additions and 75 deletions

View file

@ -0,0 +1,98 @@
<?php
declare(strict_types=1);
namespace App\Actions\Common;
use App\Contracts\Action;
use App\Contracts\ActionInput;
use App\Interfaces\ModelWithOrder;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Webmozart\Assert\Assert;
/**
* @implements \App\Contracts\Action<\App\Actions\Common\ChangeModelOrderPositionInput, bool>
*/
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<Model&ModelWithOrder> $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<int, Model&ModelWithOrder> $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<int, Model&ModelWithOrder> $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;
}
}

View file

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Actions\Common;
use App\Contracts\ActionInput;
use App\Interfaces\ModelWithOrder;
use Illuminate\Database\Eloquent\Model;
use Webmozart\Assert\Assert;
final readonly class ChangeModelOrderPositionInput implements ActionInput
{
public function __construct(
public Model & ModelWithOrder $model,
public int $targetOrder,
) {
Assert::isInstanceOf($this->model, Model::class);
Assert::isInstanceOf($this->model, ModelWithOrder::class);
Assert::greaterThanEq($this->targetOrder, 1);
}
}

View file

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

View file

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Bo;
use App\Actions\Common\ChangeModelOrderPositionInput;
use App\Interfaces\ModelWithOrder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Http\FormRequest;
use Infrastructure\Adapters\Services\AppAdminAuthService;
class ChangeSelectedOrderRequest extends FormRequest
{
public function __construct(
private readonly AppAdminAuthService $authService
) {
}
public function authorize(): bool
{
return $this->authService->check();
}
/**
* @return array<string, mixed>
*/
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'),
);
}
}

View file

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

View file

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

View file

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

View file

@ -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<int, ProductDto> $productsDtoPaginator */
$paginator = $this->dataTable->paginateQuery($query, $input->pagination);
/** @var \Illuminate\Contracts\Pagination\LengthAwarePaginator<array-key, \App\Dto\ProductDto> $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;
}
}

View file

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

View file

@ -16,12 +16,14 @@ final readonly class GetBoPaginatedProductsQueryOutput
* @param list<ProductBrand> $brands
* @param Collection<int|string, mixed> $ranges
* @param Collection<int|string, mixed> $tags
* @param Collection<int, string> $discounts
*/
public function __construct(
public LengthAwarePaginator $products,
public array $brands,
public Collection $ranges,
public Collection $tags,
public Collection $discounts,
public string $searchFields,
) {
}

View file

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

View file

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

View file

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

View file

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

View file

@ -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"
}

View file

@ -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"
}

View file

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

View file

@ -73,7 +73,7 @@
>/{{ product.sell_unit_label }}</span>
<small
v-if="product.discountedPriceTtc"
v-if="product.discountedPriceTtc && product.showStrippedPrice"
class="text-muted text-decoration-line-through ms-2"
>
<span class="visually-hidden">{{ __('Original price') }}&nbsp;:&nbsp;</span>
@ -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;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -20,5 +20,6 @@ export interface Product {
priceTtc: Money | null
priceKgTtc: Money | null
discountedPriceTtc: Money | null
showStrippedPrice?: boolean
sell_unit_label?: string | null
}

View file

@ -31,13 +31,16 @@
<div class="col-12 col-md-6 form-group">
<span class="col-form-label">
<b>{{ Str::ucfirst(__('validation.custom.attributes.discount_value')) }}*</b>
<span data-bs-toggle="tooltip" title="{{ __('The discount applies to the piece (sold unit).') }}">
<i class="fas fa-question-circle"></i>
</span>
</span>
{{-- INPUT MONTANT --}}
<div class="input-group {{ $isAmount ? '' : 'd-none' }} mb-3" id="wrapper-discount-amount">
<input class="form-control" id="discount-value-amount" name="value" data-money-input type="number"
value="{{ $isAmount ? old('value', $discount->value?->value()->getAmount() ?? '') : '' }}" step="0.01" min="0"
{{ $isAmount ? 'required' : 'disabled' }}>
aria-describedby="discount-value-help" {{ $isAmount ? 'required' : 'disabled' }}>
<span class="input-group-text">@currency()</span>
</div>
@ -45,11 +48,15 @@
<div class="input-group {{ $isPercent ? '' : 'd-none' }} mb-3" id="wrapper-discount-percent">
<input class="form-control" id="discount-value-percent" name="value" type="number"
value="{{ $isPercent ? old('value', $discount->value?->value() ?? '') : '' }}" step="1" min="0"
max="100" {{ $isPercent ? 'required' : 'disabled' }}>
max="100" aria-describedby="discount-value-help" {{ $isPercent ? 'required' : 'disabled' }}>
<span class="input-group-text">%</span>
</div>
@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).'),
])
</div>
</div>

View file

@ -32,7 +32,7 @@
href="{{ route('bo.products.index', [
'search' => '',
'brand' => '',
'discount' => 1,
'discount' => $discount->id,
'tag' => '',
'range' => '',
]) }}"

View file

@ -27,21 +27,49 @@
$showReset = !empty($searchQuery) || $hasCustomSort;
@endphp
@if (!$noOrder)
<td>
<form method="POST">
@csrf
@method('PATCH')
<input name="action" type="hidden" value="down">
@if (!$first)
<button class="btn btn-link text-decoration-none" formaction="{{ route($route, [$model, 'action' => 'up']) }}" type="submit">
<i class="icon-size fas fa-arrow-alt-circle-up fa-2x" name="down_up"></i>
</button>
<td class="text-nowrap align-middle">
<div class="d-flex align-items-center justify-content-center mb-2 gap-1">
<span class="fw-bold text-muted small me-1">#{{ $model->order }}</span>
@if (isset($selectRoute))
<div class="dropdown d-inline-block ms-1">
<button class="btn btn-sm btn-outline-secondary px-1 py-0" data-bs-toggle="dropdown" type="button"
title="{{ __('Choose position') }}" aria-expanded="false">
<i class="fa-solid fa-list-ol"></i>
</button>
<div class="dropdown-menu dropdown-menu-end p-3 shadow" style="min-width: 180px;">
<form action="{{ route($selectRoute, $model) }}" method="POST">
@csrf
@method('PATCH')
<div class="mb-2">
<label class="form-label small fw-bold mb-1" for="order-pos-{{ $model->id }}">{{ __('New position') }}</label>
<input class="form-control form-control-sm" id="order-pos-{{ $model->id }}" name="order" type="number"
value="{{ $model->order }}" min="1" required>
</div>
<button class="btn btn-sm btn-primary w-100" type="submit">{{ __('Move') }}</button>
</form>
</div>
</div>
@endif
@if (!$last)
<button class="btn btn-link text-decoration-none" formaction="{{ route($route, [$model, 'action' => 'down']) }}" type="submit">
<i class="icon-size fas fa-arrow-alt-circle-down fa-2x" name="down_arrow"></i>
</button>
@endif
</form>
</div>
<div class="d-flex align-items-center justify-content-center gap-1">
<form class="d-inline" method="POST">
@csrf
@method('PATCH')
<input name="action" type="hidden" value="down">
@if (!$first)
<button class="btn btn-link text-decoration-none p-0" formaction="{{ route($route, [$model, 'action' => 'up']) }}" type="submit"
title="{{ __('Move up') }}">
<i class="icon-size fas fa-arrow-alt-circle-up fa-2x" name="down_up"></i>
</button>
@endif
@if (!$last)
<button class="btn btn-link text-decoration-none p-0" formaction="{{ route($route, [$model, 'action' => 'down']) }}"
type="submit" title="{{ __('Move down') }}">
<i class="icon-size fas fa-arrow-alt-circle-down fa-2x" name="down_arrow"></i>
</button>
@endif
</form>
</div>
</td>
@endif
</td>

View file

@ -52,16 +52,30 @@
</select>
</div>
</div>
<div class="col-xl-3 mb-3">
<div class="col-xl-6 mb-3">
{{-- DISCOUNT --}}
<div class="input-group">
<label class="input-group-text" for="filter-form-discount">{{ __('crud.helpers.discounted') }}</label>
<div class="input-group-text">
<input class="form-check-input" id="filter-form-discount" name="discount" type="checkbox" @checked(Session::get('products.filter.discount'))>
</div>
<label class="input-group-text" for="filter-form-discount">
{{ __('Filter by :value', [
'value' => trans_choice('models.classes.discounts', 1),
]) }}
</label>
<select class="form-select" id="filter-form-discount" name="discount">
<option value="" @selected(!Session::has('products.filter.discount') || Session::get('products.filter.discount') === null || Session::get('products.filter.discount') === '')>
{{ __('Select') . ' ' . trans_choice('models.classes.discounts', 1) }}
</option>
<option value="0" @selected(Session::get('products.filter.discount') === '0')>
{{ __('All discounts') }}
</option>
@foreach ($discounts as $id => $discountLabel)
<option value="{{ $id }}" @selected(Session::get('products.filter.discount') === strval($id))>
{{ $discountLabel }}
</option>
@endforeach
</select>
</div>
</div>
<div class="col-xl-3 mb-3">
<div class="col-xl-6 mb-3">
{{-- STAR --}}
<div class="d-flex flex-row">
<div class="input-group">
@ -75,8 +89,8 @@
'brand' => '',
'tag' => '',
'range' => '',
'discount' => '',
'star' => null,
'discount' => null,
]) }}"
title="{{ __('Reset filters') }}">
<i class="fa-solid fa-rotate-left"></i></a>

View file

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

View file

@ -37,7 +37,7 @@
<div class="card-body">
@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())
<div class="row justify-content-center">

View file

@ -86,7 +86,6 @@
);
$noReplacement =
empty($associatedException?->pivot?->order_deadline_at) ||
empty($associatedException?->pivot?->replacement_date);
$isCritical = $dto->missingSubsitute || $dto->passedDeadline;

View file

@ -54,7 +54,7 @@
<span class="text-muted small d-block mb-1">{{ __('Approximately') }}*</span>
@endif
<span class="fw-semibold h4 @if ($productWithPricing->product->validDiscount?->is_old_price_displayed) text-danger @endif">
<span class="fw-semibold h4 @if ($productWithPricing->pricing->hasDiscount) text-danger @endif">
<span class="visually-hidden">{{ __('Current price') }}&nbsp;:&nbsp;</span>
@include('fo.modules.guarded-currency', [
'money' => $productWithPricing->pricing->hasDiscount
@ -64,7 +64,7 @@
])
</span>
@if ($productWithPricing->product->validDiscount?->is_old_price_displayed)
@if ($productWithPricing->pricing->hasDiscount && $productWithPricing->product->validDiscount?->is_old_price_displayed)
<small class="text-muted text-decoration-line-through ms-2">
<span class="visually-hidden">{{ __('Original price') }}&nbsp;:&nbsp;</span>
@include('fo.modules.guarded-currency', [

View file

@ -7,7 +7,7 @@
@endif
</p>
<p class="m-0">
<span class="@if ($productWithPricing->product->validDiscount?->is_old_price_displayed) text-danger @else text-dark @endif fw-bold h3 align-middle">
<span class="@if ($productWithPricing->pricing->hasDiscount) text-danger @else text-dark @endif fw-bold h3 align-middle">
<span class="visually-hidden">{{ __('Current price') }}&nbsp;:&nbsp;</span>
@include('fo.modules.guarded-currency', [
'money' => $productWithPricing->pricing->hasDiscount
@ -17,7 +17,7 @@
])
</span>
@if ($productWithPricing->product->validDiscount?->is_old_price_displayed)
@if ($productWithPricing->pricing->hasDiscount && $productWithPricing->product->validDiscount?->is_old_price_displayed)
<span class="text-muted text-decoration-line-through small ms-2 align-middle">
<span class="visually-hidden">{{ __('Original price') }}&nbsp;:&nbsp;</span>
@include('fo.modules.guarded-currency', [
@ -30,7 +30,7 @@
</p>
<p class="small fst-italic text-muted">
<span>{{ $productWithPricing->product->weight_variable ? __('Product sold by the kilo') : __('Price per kilo') }}</span> :
<span>{{ $productWithPricing->product->weight_variable ? '*' . __('Product sold by the kilo') : __('Price per kilo') }}</span> :
@include('fo.modules.guarded-currency', [
'money' => $productWithPricing->pricing->priceKgTtc(),
'product' => $productWithPricing->product,

View file

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

View file

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

View file

@ -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 */

View file

@ -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<int, array<string, mixed>> $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<int, array<string, mixed>> $data */
$data = $response->json('data');
expect($data)->not->toBeEmpty()
->and($data[0]['showStrippedPrice'])->toBeTrue()
->and($data[0]['discountedPriceTtc'])->not->toBeNull();
});
});

View file

@ -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.*?<span class="fw-semibold h4\s+text-danger\s*">/s')
// Regular product price span does NOT have text-danger class
->and($content)->toMatch('/Poulet Standard.*?<span class="fw-semibold h4\s*">/s');
});
});

View file

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

View file

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

View file

@ -0,0 +1,134 @@
<?php
declare(strict_types=1);
use App\Actions\Common\ChangeModelOrderPosition;
use App\Actions\Common\ChangeModelOrderPositionInput;
use App\Contracts\ActionInput;
use App\Models\Tag;
describe('ChangeModelOrderPosition action', function (): void {
it('shifts orders when moving a model up 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($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);
});
});

View file

@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace Tests\Integration\WithApp\App\Queries\Products;
use App\Models\Discount;
use App\Models\Product;
use App\Models\Range;
use App\Queries\Products\GetBoPaginatedProductsQuery;
use App\Queries\Products\GetBoPaginatedProductsQueryInput;
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;
use Shared\Pagination\PageNumber;
use Shared\Pagination\PageSize;
use Shared\Pagination\Pagination;
describe('GetBoPaginatedProductsQuery', function (): void {
$createRange = function (): Range {
$range = new Range();
$range->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);
});
});

View file

@ -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 () {

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
use App\Actions\Common\ChangeModelOrderPositionInput;
use App\Interfaces\ModelWithOrder;
use Illuminate\Database\Eloquent\Model;
describe('ChangeModelOrderPositionInput', function (): void {
it('can be instantiated with a model implementing ModelWithOrder and a valid target order', function (): void {
// GIVEN
$mock = new class () extends Model implements ModelWithOrder
{
public function getOrder(): int
{
return 1;
}
public function setOrder(int $order): void
{
}
};
// WHEN
$input = new ChangeModelOrderPositionInput(model: $mock, targetOrder: 5);
// THEN
expect($input->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);
});
});

View file

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