diff --git a/app/Actions/Common/ChangeModelOrder.php b/app/Actions/Common/ChangeModelOrder.php index a44fa440..509417cb 100644 --- a/app/Actions/Common/ChangeModelOrder.php +++ b/app/Actions/Common/ChangeModelOrder.php @@ -7,7 +7,9 @@ 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 Illuminate\Database\Eloquent\SoftDeletes; use SortDirection; use Webmozart\Assert\Assert; @@ -30,8 +32,17 @@ final class ChangeModelOrder implements Action $goUp = $input->direction === SortDirection::Ascending; $currentOrder = $model->getOrder(); + $usesSoftDeletes = in_array(SoftDeletes::class, class_uses_recursive($model), true) + || method_exists($model, 'trashed'); + + /** @var Builder $baseQuery */ + $baseQuery = $usesSoftDeletes + // @phpstan-ignore method.notFound (withTrashed) + ? $model::query()->withTrashed() + : $model::query(); + /** @var (Model&ModelWithOrder)|null $adjacentModel */ - $adjacentModel = $model::query() + $adjacentModel = $baseQuery ->where('order', $goUp ? '<' : '>', $currentOrder) ->orderBy('order', $goUp ? SortDirection::Descending : SortDirection::Ascending) ->first(); diff --git a/app/Actions/Common/ChangeModelOrderPosition.php b/app/Actions/Common/ChangeModelOrderPosition.php index c19636c7..a9f8ffaa 100644 --- a/app/Actions/Common/ChangeModelOrderPosition.php +++ b/app/Actions/Common/ChangeModelOrderPosition.php @@ -9,6 +9,7 @@ use App\Contracts\ActionInput; use App\Interfaces\ModelWithOrder; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\SoftDeletes; use Webmozart\Assert\Assert; /** @@ -34,8 +35,11 @@ final class ChangeModelOrderPosition implements Action return true; } + $usesSoftDeletes = in_array(SoftDeletes::class, class_uses_recursive($model), true) + || method_exists($model, 'trashed'); + /** @var Builder $baseQuery */ - $baseQuery = method_exists($model, 'withTrashed') + $baseQuery = $usesSoftDeletes // @phpstan-ignore method.notFound (withTrashed) ? $model::query()->withTrashed() : $model::query(); diff --git a/app/Casts/OrderLineProductCast.php b/app/Casts/OrderLineProductCast.php index f98abc38..916c5e2f 100644 --- a/app/Casts/OrderLineProductCast.php +++ b/app/Casts/OrderLineProductCast.php @@ -35,6 +35,13 @@ class OrderLineProductCast implements CastsAttributes $data = Arr::wrap(json_decode($value, true)); + $taxRate = Arr::get($data, 'tax_rate'); + $taxRate = is_numeric($taxRate) ? (float) $taxRate : null; + + if (is_null($taxRate)) { + throw new \InvalidArgumentException('The tax rate cannot be null.'); + } + return new OrderLineProduct( incoId: new IncoId(Arr::integer($data, 'inco_id')), originalId: new ProductId(Uuid::fromString( @@ -50,14 +57,8 @@ class OrderLineProductCast implements CastsAttributes price: new MoneyCast()->get($model, 'price', Arr::get($data, 'price'), []), discountedPrice: new MoneyCast()->get($model, 'discounted_price', Arr::get($data, 'discounted_price'), []), priceKgTtc: new MoneyCast()->get($model, 'price_kg_ttc', Arr::get($data, 'price_kg_ttc'), []), - taxRate: match ((float) Arr::float($data, 'tax_rate')) { - TaxRate::TVA_20->percent() => TaxRate::TVA_20, - TaxRate::TVA_5_5->percent() => TaxRate::TVA_5_5, - default => throw new \UnexpectedValueException( - 'Unhandled tax' - ) - }, - picture: Arr::string($data, 'picture', null), + taxRate: TaxRate::fromPercent($taxRate), + picture: is_string($picture = Arr::get($data, 'picture')) ? $picture : null, ); } diff --git a/app/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequest.php b/app/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequest.php index 6bd994ac..8072f7e8 100644 --- a/app/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequest.php +++ b/app/Http/Requests/Bo/Shops/UpdateShopPickupExceptionsRequest.php @@ -103,18 +103,6 @@ class UpdateShopPickupExceptionsRequest extends FormRequest ]; } - /** @return array */ - #[\Override] - public function messages(): array - { - return [ - 'pickup-exceptions.*.uuid' => 'La fermeture exceptionnelle sélectionnée n\'est pas un identifiant valide.', - 'pickup-exceptions.*.exists' => 'La fermeture exceptionnelle sélectionnée n\'existe pas.', - 'order_deadline_at.*.before' => 'La date limite de commande doit être strictement antérieure au jour de remplacement.', - 'replacement_date.*.required_with' => 'Le jour de remplacement est obligatoire lorsqu\'une date limite de commande est définie.', - ]; - } - /** * @return array */ diff --git a/app/Http/Resources/Fo/Ajax/FilteredProductResource.php b/app/Http/Resources/Fo/Ajax/FilteredProductResource.php index c8a47ff5..e46f5207 100644 --- a/app/Http/Resources/Fo/Ajax/FilteredProductResource.php +++ b/app/Http/Resources/Fo/Ajax/FilteredProductResource.php @@ -6,8 +6,6 @@ namespace App\Http\Resources\Fo\Ajax; use App\Lib\Helpers\MoneyHelper; use App\Models\Product; -use Domain\Services\PricingService; -use Domain\Services\ProductAvailabilityService; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\Facades\Gate; @@ -23,12 +21,10 @@ class FilteredProductResource extends JsonResource #[\Override] public function toArray(Request $request): array { - $productRepository = resolve(EloquentProductRepository::class); - $productAvailabilityService = resolve(ProductAvailabilityService::class); - $pricingService = resolve(PricingService::class); + $productRepository = resolve(EloquentProductRepository::class); $domainProduct = $productRepository->toEntity($this->product); - $productPricing = $pricingService->calculateForProduct($domainProduct); + $productPricing = $domainProduct->pricing(); $discount = $productPricing->hasDiscount ? $productPricing->discountedPriceTtc() : null; return [ @@ -48,7 +44,7 @@ class FilteredProductResource extends JsonResource MoneyHelper::serialized($productPricing->priceKgTtc()) : null, 'discountedPriceTtc' => Gate::allows('viewPrices', $this->product) ? MoneyHelper::serialized($discount) : null, - 'is_available' => $productAvailabilityService->isOrderable($domainProduct), + 'is_available' => $domainProduct->isOrderable(), 'can_add_to_basket' => Gate::allows('addToBasket', $this->product), 'showStrippedPrice' => (bool) $this->product->validDiscount?->is_old_price_displayed, 'nutriscore' => $this->product->inco?->nutriscore?->value(), diff --git a/app/Models/Discount.php b/app/Models/Discount.php index 5c561d63..2d3bb81d 100644 --- a/app/Models/Discount.php +++ b/app/Models/Discount.php @@ -54,8 +54,12 @@ class Discount extends Model protected function scopePublished(Builder $query): Builder { return $query - ->where('date_start', '<=', Date::now()) - ->where('date_end', '>=', Date::now()); + ->where(function (Builder $q): void { + $q->whereNull('date_start')->orWhere('date_start', '<=', Date::now()); + }) + ->where(function (Builder $q): void { + $q->whereNull('date_end')->orWhere('date_end', '>=', Date::now()); + }); } /** @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\Product,$this> */ diff --git a/app/Policies/Backend/ProductPolicy.php b/app/Policies/Backend/ProductPolicy.php index d0d73744..9d039b53 100644 --- a/app/Policies/Backend/ProductPolicy.php +++ b/app/Policies/Backend/ProductPolicy.php @@ -11,13 +11,11 @@ use App\Models\User; use Domain\Enums\UserRole; use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Ports\Repositories\ProductRepository; -use Domain\Services\ProductAvailabilityService; use Ramsey\Uuid\Uuid; class ProductPolicy { public function __construct( - private readonly ProductAvailabilityService $productService, private readonly ProductRepository $productRepository ) { } @@ -129,6 +127,6 @@ class ProductPolicy $domainProduct = $this->productRepository->find($productId); - return $domainProduct && $this->productService->isPublished($domainProduct); + return $domainProduct && $domainProduct->isPublished(); } } diff --git a/app/Policies/Frontend/BasketPolicy.php b/app/Policies/Frontend/BasketPolicy.php index 061ebc3f..9e7570dc 100644 --- a/app/Policies/Frontend/BasketPolicy.php +++ b/app/Policies/Frontend/BasketPolicy.php @@ -7,12 +7,12 @@ namespace App\Policies\Frontend; use App\Models\Customer; use App\Models\User; use Domain\Models\ValueObjects\BasketProduct; -use Domain\Services\ProductAvailabilityService; +use Domain\Ports\Repositories\ProductRepository; class BasketPolicy { public function __construct( - private readonly ProductAvailabilityService $productService + private readonly ProductRepository $productRepository ) { } @@ -27,6 +27,8 @@ class BasketPolicy return false; } - return $this->productService->isBasketProductPublished($product); + $domainProduct = $this->productRepository->find($product->id); + + return $domainProduct && $domainProduct->isPublished(); } } diff --git a/app/Policies/Frontend/ProductPolicy.php b/app/Policies/Frontend/ProductPolicy.php index 5c3b0da4..3e22e638 100644 --- a/app/Policies/Frontend/ProductPolicy.php +++ b/app/Policies/Frontend/ProductPolicy.php @@ -8,12 +8,10 @@ use App\Models\Customer; use App\Models\Product; use App\Models\User; use Domain\Ports\Repositories\ProductRepository; -use Domain\Services\ProductAvailabilityService; class ProductPolicy { public function __construct( - private readonly ProductAvailabilityService $productService, private readonly ProductRepository $productRepository ) { } @@ -22,14 +20,14 @@ class ProductPolicy { $domainProduct = $this->productRepository->find($product->getId()); - return $domainProduct && $this->productService->isPublished($domainProduct); + return $domainProduct && $domainProduct->isPublished(); } public function addToBasket(null | User | Customer $_, Product $product): bool { $domainProduct = $this->productRepository->find($product->getId()); - return $domainProduct && $this->productService->isOrderable($domainProduct); + return $domainProduct && $domainProduct->isOrderable(); } public function viewPrices(null | User | Customer $_, Product $product): bool @@ -40,6 +38,6 @@ class ProductPolicy $domainProduct = $this->productRepository->find($product->getId()); - return $domainProduct && $this->productService->isPublished($domainProduct); + return $domainProduct && $domainProduct->isPublished(); } } diff --git a/app/Providers/MoneyServiceProvider.php b/app/Providers/MoneyServiceProvider.php index 474938ff..6ed2bee5 100644 --- a/app/Providers/MoneyServiceProvider.php +++ b/app/Providers/MoneyServiceProvider.php @@ -66,9 +66,7 @@ class MoneyServiceProvider extends ServiceProvider */ public function boot() { - if (! $this->app->runningInConsole()) { - $this->sharetoView(); - } + $this->sharetoView(); } private function sharetoView(): void diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index 30c4b819..bc93b955 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -14,7 +14,6 @@ use App\Models\Range; use App\Models\Slide; use App\Models\Tag; use Domain\Ports\Repositories\ProductRepository; -use Domain\Services\PricingService; use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Foundation\Http\Middleware\PreventRequestForgery; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; @@ -142,7 +141,6 @@ class RouteServiceProvider extends ServiceProvider private function resolvePublishedProductWithPricing(string $value): ProductWithPricingDto { $domainProductRepository = resolve(ProductRepository::class); - $pricingService = resolve(PricingService::class); $product = Product::query() ->where('slug', $value) ->published() @@ -155,7 +153,7 @@ class RouteServiceProvider extends ServiceProvider $product->load(['inco', 'validDiscount', 'products']); $domainProduct = $domainProductRepository->find($product->getId()); - $pricing = $domainProduct ? $pricingService->calculateForProduct($domainProduct) : null; + $pricing = $domainProduct?->pricing(); if (! $pricing) { throw new NotFoundHttpException(); diff --git a/app/Providers/ViewServiceProvider.php b/app/Providers/ViewServiceProvider.php index 34a37868..3c10a3da 100644 --- a/app/Providers/ViewServiceProvider.php +++ b/app/Providers/ViewServiceProvider.php @@ -7,7 +7,6 @@ namespace App\Providers; use App\Models\Page; use App\Models\Product; use App\Services\EmployeeSyncService; -use Domain\Services\ProductAvailabilityService; use Illuminate\Pagination\Paginator; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\View; @@ -23,12 +22,13 @@ class ViewServiceProvider extends ServiceProvider */ public function boot(EloquentProductRepository $productRepository) { + $this->setUpBladeMacros($productRepository); + if ($this->app->runningInConsole() && ! $this->app->runningUnitTests()) { return; } $this->setupPaginator(); - $this->setUpBladeMacros($productRepository); } private function setupPaginator(): void @@ -54,8 +54,7 @@ class ViewServiceProvider extends ServiceProvider { Blade::if( 'orderable', - fn (Product $product) => resolve(ProductAvailabilityService::class) - ->isOrderable($productRepository->toEntity($product)) + fn (Product $product) => $productRepository->toEntity($product)->isOrderable() ); } } diff --git a/app/Queries/Products/GetPaginatedProductsQuery.php b/app/Queries/Products/GetPaginatedProductsQuery.php index d29a806d..2e58785d 100644 --- a/app/Queries/Products/GetPaginatedProductsQuery.php +++ b/app/Queries/Products/GetPaginatedProductsQuery.php @@ -11,7 +11,6 @@ use App\Dto\ProductWithPricingDto; use App\Models\Product; use App\Services\DataTableService; use Domain\Ports\Repositories\ProductRepository; -use Domain\Services\PricingService; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Webmozart\Assert\Assert; @@ -26,7 +25,6 @@ final readonly class GetPaginatedProductsQuery implements Query public function __construct( private DataTableService $dataTable, private ProductRepository $domainProductRepository, - private PricingService $pricingService, ) { } @@ -61,7 +59,7 @@ final readonly class GetPaginatedProductsQuery implements Query $result = $paginator->through(function (Product $product): ProductWithPricingDto { $domainProduct = $this->domainProductRepository->find($product->getId()); Assert::notNull($domainProduct, "Domain product not found for ID {$product->id}"); - $pricing = $this->pricingService->calculateForProduct($domainProduct); + $pricing = $domainProduct->pricing(); return new ProductWithPricingDto( product: $product, diff --git a/domain/Enums/TaxRate.php b/domain/Enums/TaxRate.php index 917c674b..6aef67a3 100644 --- a/domain/Enums/TaxRate.php +++ b/domain/Enums/TaxRate.php @@ -4,7 +4,7 @@ declare(strict_types=1); namespace Domain\Enums; -use Domain\Services\PricingService; +use Domain\Models\Entities\Product; use Money\Money; use Shared\Enums\BaseEnum; @@ -34,6 +34,17 @@ enum TaxRate: int }; } + public static function fromPercent(float $percent): self + { + return match ($percent) { + self::TVA_20->percent() => self::TVA_20, + self::TVA_5_5->percent() => self::TVA_5_5, + default => self::tryFrom((int) $percent) ?? throw new \UnexpectedValueException( + sprintf('Unhandled tax rate: %s', $percent) + ), + }; + } + public function rate(): float { return $this->percent() / 100; @@ -54,6 +65,6 @@ enum TaxRate: int public function applyTo(Money $price): Money { - return $price->multiply($this->multiplier(), PricingService::ROUNDING); + return $price->multiply($this->multiplier(), Product::ROUNDING); } } diff --git a/domain/Enums/Units/OrderUnit.php b/domain/Enums/Units/OrderUnit.php index bf5584ee..6851cb0e 100644 --- a/domain/Enums/Units/OrderUnit.php +++ b/domain/Enums/Units/OrderUnit.php @@ -15,6 +15,15 @@ enum OrderUnit: string case KGM = 'KGM'; case COLIS = 'COLIS'; + public function toRegateCode(): string + { + return match ($this) { + self::COLIS => 'UEA', + self::KGM => 'KGM', + self::PCE => 'UB', + }; + } + /** * Optionnal labels definition * diff --git a/domain/Events/Dto/OrderPlacedLine.php b/domain/Events/Dto/OrderPlacedLine.php index 2def730f..8815d8fd 100644 --- a/domain/Events/Dto/OrderPlacedLine.php +++ b/domain/Events/Dto/OrderPlacedLine.php @@ -6,6 +6,7 @@ namespace Domain\Events\Dto; use Domain\Enums\Units\OrderUnit; use Domain\Models\ValueObjects\IncoId; +use Domain\Models\ValueObjects\OrderLine; use Money\Money; final readonly class OrderPlacedLine @@ -23,4 +24,17 @@ final readonly class OrderPlacedLine throw new \DomainException('Quantity must be greater than 0'); } } + + public static function fromOrderLine(OrderLine $line): self + { + return new self( + productName: $line->product->name, + productIncoId: clone $line->product->incoId, + productWeightIsVariable: $line->product->weight->isVariable, + productPriceKgTtc: clone $line->product->priceKgTtc, + productOrderUnit: $line->product->orderUnit, + quantity: $line->quantity, + totalTtc: clone $line->totalTtc + ); + } } diff --git a/domain/Events/Dto/OrderPlacedShop.php b/domain/Events/Dto/OrderPlacedShop.php index c27a0b45..6f6f93b7 100644 --- a/domain/Events/Dto/OrderPlacedShop.php +++ b/domain/Events/Dto/OrderPlacedShop.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace Domain\Events\Dto; +use Domain\Models\ValueObjects\DeliveryAddress; + final readonly class OrderPlacedShop { public function __construct( @@ -25,4 +27,14 @@ final readonly class OrderPlacedShop throw new \DomainException('Shop city is required'); } } + + public static function fromDeliveryAddress(DeliveryAddress $address): self + { + return new self( + name: $address->name, + address: $address->address, + postcode: $address->postcode, + city: $address->city, + ); + } } diff --git a/domain/Models/Entities/Order.php b/domain/Models/Entities/Order.php index 6cbba01c..6156e564 100644 --- a/domain/Models/Entities/Order.php +++ b/domain/Models/Entities/Order.php @@ -4,7 +4,12 @@ declare(strict_types=1); namespace Domain\Models\Entities; +use Carbon\CarbonImmutable; use Domain\Enums\OrderStatus; +use Domain\Events\AnOrderHasBeenPlaced; +use Domain\Events\Dto\OrderPlacedLine; +use Domain\Events\Dto\OrderPlacedShop; +use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\DeliveryAddress; use Domain\Models\ValueObjects\Entities\OrderId; use Domain\Models\ValueObjects\Entities\ShopId; @@ -65,4 +70,47 @@ final class Order implements Entity $this->status = OrderStatus::CANCELED; } + + public static function fromBasket( + OrderId $id, + OrderReference $reference, + Basket $basket, + PickupTimeSlot $pickupTimeSlot, + Shopper $shopper, + Shop $shop + ): self { + $lines = array_map( + fn (BasketProduct $item) => OrderLine::fromBasketProduct($item), + array_values($basket->items()) + ); + + return new self( + id: $id, + shopId: clone $shop->id(), + reference: $reference, + employee: OrderEmployee::fromShopper($shopper), + deliveryAddress: DeliveryAddress::fromShop($shop), + pickupTimeSlot: clone $pickupTimeSlot, + status: OrderStatus::VALIDATED, + total: clone $basket->totalTaxIncluded(), + lines: $lines + ); + } + + public function toPlacedEvent(): AnOrderHasBeenPlaced + { + return new AnOrderHasBeenPlaced( + orderId: $this->id(), + reference: $this->reference, + totalTtc: $this->getTotal(), + byMatricule: $this->employee->matricule, + employee: clone $this->employee, + shop: OrderPlacedShop::fromDeliveryAddress($this->deliveryAddress), + pickupDay: CarbonImmutable::instance($this->pickupTimeSlot->getAt()), + lines: array_map( + fn (OrderLine $line) => OrderPlacedLine::fromOrderLine($line), + $this->lines + ) + ); + } } diff --git a/domain/Models/Entities/PickupExceptionOnDate.php b/domain/Models/Entities/PickupExceptionOnDate.php index 8611c0f3..225eae08 100644 --- a/domain/Models/Entities/PickupExceptionOnDate.php +++ b/domain/Models/Entities/PickupExceptionOnDate.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Domain\Models\Entities; use Carbon\CarbonInterface; +use Carbon\WeekDay; use Domain\Enums\RepeatFrequency; use Domain\Models\ValueObjects\Entities\PickupExceptionId; use Shared\DDD\Entity; @@ -27,4 +28,9 @@ final readonly class PickupExceptionOnDate implements Entity { return $this->id; } + + public function isPickupDay(WeekDay $pickupDay = WeekDay::Friday): bool + { + return $this->date->isDayOfWeek($pickupDay->value); + } } diff --git a/domain/Models/Entities/Product.php b/domain/Models/Entities/Product.php index 974e903c..f73a2994 100644 --- a/domain/Models/Entities/Product.php +++ b/domain/Models/Entities/Product.php @@ -5,11 +5,14 @@ declare(strict_types=1); namespace Domain\Models\Entities; use Carbon\CarbonImmutable; +use Carbon\CarbonInterface; use Domain\Enums\SellUnit; use Domain\Enums\TaxRate; use Domain\Enums\Units\InvoicingUnit; +use Domain\Models\ValueObjects\DiscountRate; use Domain\Models\ValueObjects\DiscountValue; use Domain\Models\ValueObjects\Entities\ProductId; +use Domain\Models\ValueObjects\ProductPricing; use Domain\Models\ValueObjects\ProductWeight; use Money\Money; use Shared\DDD\Entity; @@ -17,6 +20,10 @@ use Shared\DDD\Entity; /** @implements \Shared\DDD\Entity<\Domain\Models\ValueObjects\Entities\ProductId> */ final readonly class Product implements Entity { + public const int ROUNDING = Money::ROUND_UP; + + private const int GRAMS_PER_KG = 1000; + public function __construct( private ProductId $id, public Money $price, @@ -37,4 +44,145 @@ final readonly class Product implements Entity { return $this->id; } + + public function canBeOrderOn(?CarbonInterface $date = null): bool + { + $target = $date ?? CarbonImmutable::now(); + + if ($this->orderable_start && $target < $this->orderable_start) { + return false; + } + if ($this->orderable_end && $target > $this->orderable_end) { + return false; + } + + return $this->status && $this->hasInco; + } + + public function isOrderable(?CarbonInterface $date = null): bool + { + return $this->canBeOrderOn($date); + } + + public function isPublished(): bool + { + return $this->status; + } + + public function hasInco(): bool + { + return $this->hasInco; + } + + public function hasDiscount(): bool + { + return $this->validDiscount !== null; + } + + public function basePriceHt(): Money + { + if ($this->invoicing_unit === InvoicingUnit::KGM && $this->sell_unit === SellUnit::PCE && $this->product_weight) { + // * Price per kg => price of the piece: price x grams / 1000 (single rounding, no float) + return $this->price + ->multiply($this->product_weight->toGrams()) + ->divide(self::GRAMS_PER_KG, self::ROUNDING); + } + + return $this->price; + } + + public function basePriceTtc(): Money + { + return $this->tax_rate->applyTo($this->basePriceHt()); + } + + public function discountAmountHt(): Money + { + $basePriceHt = $this->basePriceHt(); + $discountAmount = $this->validDiscount?->calculateDiscountAmount($basePriceHt) + ?? new Money(0, $basePriceHt->getCurrency()); + + if ($discountAmount->greaterThan($basePriceHt)) { + return $basePriceHt; + } + + return $discountAmount; + } + + public function discountedPriceHt(): Money + { + return $this->basePriceHt()->subtract($this->discountAmountHt()); + } + + public function discountedPriceTtc(): Money + { + return $this->tax_rate->applyTo($this->discountedPriceHt()); + } + + public function priceKgTtc(): Money + { + if ($this->invoicing_unit === InvoicingUnit::KGM) { + // * The product price is already a price per kg: it is the reference for the kg price + $discountAmountKgHt = $this->validDiscount?->calculateDiscountAmount($this->price) + ?? new Money(0, $this->price->getCurrency()); + + $grams = $this->product_weight?->toGrams() ?? 0; + + if ( + $this->validDiscount !== null + && ! $this->validDiscount->isPercentage() + && $this->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 = $this->price->subtract($discountAmountKgHt); + + if ($discountedKgPriceHt->isNegative()) { + $discountedKgPriceHt = new Money(0, $this->price->getCurrency()); + } + + return $this->tax_rate->applyTo($discountedKgPriceHt); + } + + $priceTtc = $this->discountedPriceTtc(); + $grams = $this->product_weight?->toGrams() ?? 0; + + // NOTE: If the product is not published or not sold by piece, we don't need to convert the price to per kg + if ($grams > 0 && $this->status && $this->invoicing_unit === InvoicingUnit::PCE) { + // * 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); + } + + return $priceTtc; + } + + public function discountRate(): DiscountRate + { + if ($this->validDiscount?->isPercentage()) { + return DiscountRate::fromPercentage($this->validDiscount->getPercentage()); + } + + return DiscountRate::fromAmounts($this->discountAmountHt(), $this->basePriceHt()); + } + + public function pricing(): ProductPricing + { + return new ProductPricing( + basePriceHt: $this->basePriceHt(), + basePriceTtc: $this->basePriceTtc(), + discountAmountHt: $this->discountAmountHt(), + discountedPriceHt: $this->discountedPriceHt(), + discountedPriceTtc: $this->discountedPriceTtc(), + priceKgTtc: $this->priceKgTtc(), + discountRate: $this->discountRate(), + hasDiscount: $this->hasDiscount() + ); + } } diff --git a/domain/Models/ValueObjects/BasketProduct.php b/domain/Models/ValueObjects/BasketProduct.php index 33eec4fa..390b6e6b 100644 --- a/domain/Models/ValueObjects/BasketProduct.php +++ b/domain/Models/ValueObjects/BasketProduct.php @@ -7,8 +7,8 @@ namespace Domain\Models\ValueObjects; use Domain\Enums\ProductBrand; use Domain\Enums\TaxRate; use Domain\Enums\Units\OrderUnit; +use Domain\Models\Entities\Product; use Domain\Models\ValueObjects\Entities\ProductId; -use Domain\Services\PricingService; use Money\Money; final readonly class BasketProduct @@ -58,22 +58,29 @@ final readonly class BasketProduct return $this->unitPriceHt; } + public function unitPriceDiscounted(): Money + { + return $this->unitPriceHt->subtract($this->unitDiscount); + } + + public function unitTax(): Money + { + return $this->unitTtc()->subtract($this->unitPriceDiscounted()); + } + public function unitTtc(): Money { - $unitPriceDiscounted = $this->unitPriceHt->subtract($this->unitDiscount); - - // applyTo renvoie déjà le montant TTC (900 + 180 = 1080) - return $this->taxRate->applyTo($unitPriceDiscounted); + return $this->taxRate->applyTo($this->unitPriceDiscounted()); } public function discountTotal(): Money { - return $this->unitDiscount->multiply($this->qty, PricingService::ROUNDING); + return $this->unitDiscount->multiply($this->qty, Product::ROUNDING); } public function priceTotalHt(): Money { - return $this->unitPriceHt->multiply($this->qty, PricingService::ROUNDING); + return $this->unitPriceHt->multiply($this->qty, Product::ROUNDING); } public function subtotalHt(): Money diff --git a/domain/Models/ValueObjects/DeliveryAddress.php b/domain/Models/ValueObjects/DeliveryAddress.php index 34b0a34f..885fc7fa 100644 --- a/domain/Models/ValueObjects/DeliveryAddress.php +++ b/domain/Models/ValueObjects/DeliveryAddress.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects; +use Domain\Models\Entities\Shop; + final readonly class DeliveryAddress { public function __construct( @@ -18,6 +20,19 @@ final readonly class DeliveryAddress $this->validate(); } + public static function fromShop(Shop $shop): self + { + return new self( + name: $shop->name, + address: $shop->address, + postcode: $shop->postcode, + city: $shop->city, + phone: $shop->phone, + latitude: $shop->latitude, + longitude: $shop->longitude + ); + } + private function validate(): void { if (trim($this->name) === '') { diff --git a/domain/Models/ValueObjects/DiscountValue.php b/domain/Models/ValueObjects/DiscountValue.php index ea49196b..55cf2a10 100644 --- a/domain/Models/ValueObjects/DiscountValue.php +++ b/domain/Models/ValueObjects/DiscountValue.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects; use Domain\Enums\DiscountType; -use Domain\Services\PricingService; +use Domain\Models\Entities\Product; use Money\Money; /** @@ -118,6 +118,6 @@ final readonly class DiscountValue $rate = $this->getPercentageRate(); - return $basePrice->multiply((string) $rate, PricingService::ROUNDING); + return $basePrice->multiply((string) $rate, Product::ROUNDING); } } diff --git a/domain/Models/ValueObjects/OrderEmployee.php b/domain/Models/ValueObjects/OrderEmployee.php index e1313963..53bff56a 100644 --- a/domain/Models/ValueObjects/OrderEmployee.php +++ b/domain/Models/ValueObjects/OrderEmployee.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects; +use Domain\Models\Entities\Shopper; + final readonly class OrderEmployee { public function __construct( @@ -18,6 +20,18 @@ final readonly class OrderEmployee $this->assertNotEmpty('lastname', $lastname); } + public static function fromShopper(Shopper $shopper): self + { + return new self( + matricule: clone $shopper->matricule, + firstname: $shopper->prenom, + lastname: $shopper->nom, + facility: $shopper->etablissement, + site: $shopper->site, + service: $shopper->service + ); + } + private function assertNotEmpty(string $attribute, string $value): void { if (empty(trim($value))) { diff --git a/domain/Models/ValueObjects/OrderLine.php b/domain/Models/ValueObjects/OrderLine.php index 3fd47283..d2d27b49 100644 --- a/domain/Models/ValueObjects/OrderLine.php +++ b/domain/Models/ValueObjects/OrderLine.php @@ -51,4 +51,19 @@ final readonly class OrderLine throw new \DomainException('Total TTC must be non-negative'); } } + + public static function fromBasketProduct(BasketProduct $item): self + { + return new self( + product: OrderLineProduct::fromBasketProduct($item), + quantity: $item->qty, + unitPriceHt: clone $item->unitPriceHt, + unitDiscount: clone $item->unitDiscount, + unitTax: clone $item->unitTax(), + totalHt: clone $item->subtotalHt(), + totalDiscount: clone $item->discountTotal(), + totalTax: clone $item->taxTotal(), + totalTtc: clone $item->totalTtc() + ); + } } diff --git a/domain/Models/ValueObjects/OrderLineProduct.php b/domain/Models/ValueObjects/OrderLineProduct.php index c2168548..a8ab97fc 100644 --- a/domain/Models/ValueObjects/OrderLineProduct.php +++ b/domain/Models/ValueObjects/OrderLineProduct.php @@ -44,4 +44,21 @@ final readonly class OrderLineProduct throw new \DomainException('Price per kg TTC has to be positive'); } } + + public static function fromBasketProduct(BasketProduct $item): self + { + return new self( + incoId: $item->incoId ?? throw new \DomainException('incoId cannot be null for an order'), + originalId: $item->id, + name: $item->name, + weight: new ProductWeight($item->weightGrams, $item->weightVariable), + brand: $item->brand ?? ProductBrand::none, + orderUnit: $item->orderUnit, + price: clone $item->unitPriceHt, + discountedPrice: $item->unitPriceDiscounted(), + priceKgTtc: clone $item->priceKgTtc, + taxRate: $item->taxRate, + picture: $item->picture + ); + } } diff --git a/domain/Models/ValueObjects/ShopPickupOverride.php b/domain/Models/ValueObjects/ShopPickupOverride.php index 1c51a36f..a9cc41fe 100644 --- a/domain/Models/ValueObjects/ShopPickupOverride.php +++ b/domain/Models/ValueObjects/ShopPickupOverride.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Domain\Models\ValueObjects; +use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Domain\Models\Entities\PickupExceptionOnDate; @@ -20,4 +21,21 @@ final readonly class ShopPickupOverride ); } } + + public function hasReplacement(): bool + { + return $this->replacementDate !== null; + } + + public function effectiveDeadline(CarbonInterface $defaultDeadline): CarbonImmutable + { + return $this->orderDeadlineAt !== null + ? CarbonImmutable::createFromInterface($this->orderDeadlineAt) + : CarbonImmutable::createFromInterface($defaultDeadline); + } + + public function isDeadlinePassed(CarbonInterface $now, CarbonInterface $defaultDeadline): bool + { + return $now->greaterThan($this->effectiveDeadline($defaultDeadline)); + } } diff --git a/domain/Services/OrderService.php b/domain/Services/OrderService.php index c33c95b2..a0736665 100644 --- a/domain/Services/OrderService.php +++ b/domain/Services/OrderService.php @@ -4,20 +4,13 @@ declare(strict_types=1); namespace Domain\Services; -use Domain\Enums\OrderStatus; -use Domain\Enums\ProductBrand; use Domain\Models\Entities\Basket; use Domain\Models\Entities\Order; use Domain\Models\Entities\Shop; use Domain\Models\Entities\Shopper; -use Domain\Models\ValueObjects\DeliveryAddress; use Domain\Models\ValueObjects\Entities\OrderId; -use Domain\Models\ValueObjects\OrderEmployee; -use Domain\Models\ValueObjects\OrderLine; -use Domain\Models\ValueObjects\OrderLineProduct; use Domain\Models\ValueObjects\OrderReference; use Domain\Models\ValueObjects\PickupTimeSlot; -use Domain\Models\ValueObjects\ProductWeight; use Domain\Ports\Repositories\OrderRepository; use Ramsey\Uuid\Uuid; @@ -34,62 +27,13 @@ class OrderService Shopper $shopper, Shop $shop ): Order { - $lines = []; - foreach ($basket->items() as $item) { - $orderLineProduct = new OrderLineProduct( - incoId: $item->incoId ?? throw new \DomainException('incoId cannot be null for an order'), - originalId: $item->id, - name: $item->name, - weight: new ProductWeight($item->weightGrams, $item->weightVariable), - brand: $item->brand ?? ProductBrand::none, - orderUnit: $item->orderUnit, - price: clone $item->unitPriceHt, - discountedPrice: $item->unitPriceHt->subtract($item->unitDiscount), - priceKgTtc: clone $item->priceKgTtc, - taxRate: $item->taxRate, - picture: $item->picture - ); - - $lines[] = new OrderLine( - product: $orderLineProduct, - quantity: $item->qty, - unitPriceHt: clone $item->unitPriceHt, - unitDiscount: clone $item->unitDiscount, - unitTax: clone $item->taxRate - ->applyTo($item->unitPriceHt - ->subtract($item->unitDiscount)) - ->subtract($item->unitPriceHt - ->subtract($item->unitDiscount)), - totalHt: clone $item->subtotalHt(), - totalDiscount: clone $item->discountTotal(), - totalTax: clone $item->taxTotal(), - totalTtc: clone $item->totalTtc() - ); - } - - return new Order( + return Order::fromBasket( id: $this->newOrderId(), - shopId: clone $shop->id(), reference: $this->newReference(), - employee: new OrderEmployee( - matricule: clone $shopper->matricule, - firstname: $shopper->prenom, - lastname: $shopper->nom, - facility: $shopper->etablissement, - site: $shopper->site, - service: $shopper->service - ), - deliveryAddress: new DeliveryAddress( - name: $shop->name, - address: $shop->address, - postcode: $shop->postcode, - city: $shop->city, - phone: $shop->phone - ), - pickupTimeSlot: clone $pickupTimeSlot, - status: OrderStatus::VALIDATED, - total: clone $basket->totalTaxIncluded(), - lines: $lines + basket: $basket, + pickupTimeSlot: $pickupTimeSlot, + shopper: $shopper, + shop: $shop ); } diff --git a/domain/Services/OrderTunnelService.php b/domain/Services/OrderTunnelService.php index 7fcb7cef..0a149fae 100644 --- a/domain/Services/OrderTunnelService.php +++ b/domain/Services/OrderTunnelService.php @@ -10,9 +10,6 @@ use Domain\Builders\OrderBuilder; use Domain\Builders\OrderBuilderCompleted; use Domain\Builders\OrderBuilderWithBasket; use Domain\Enums\OrderTunnelStep; -use Domain\Events\AnOrderHasBeenPlaced; -use Domain\Events\Dto\OrderPlacedLine; -use Domain\Events\Dto\OrderPlacedShop; use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException; use Domain\Exceptions\OrderTunnel\OrderLimitExceededException; use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException; @@ -21,7 +18,6 @@ use Domain\Models\Entities\Order; use Domain\Models\Entities\Shop; use Domain\Models\Entities\Shopper; use Domain\Models\ValueObjects\Entities\ShopperId; -use Domain\Models\ValueObjects\OrderLine; use Domain\Models\ValueObjects\PickupTimeSlot; use Domain\Policies\CustomerOrderLimitPolicy; use Domain\Ports\Repositories\OrderRepository; @@ -219,8 +215,7 @@ class OrderTunnelService $this->orderRepository->persist($order); - $event = $this->mapNewOrderEvent($order); - $this->eventDispatcher->dispatch($event); + $this->eventDispatcher->dispatch($order->toPlacedEvent()); $this->basketService->empty(); $this->orderBuilderSessionManager->clear(); @@ -233,39 +228,4 @@ class OrderTunnelService { return CarbonImmutable::now()->addDays(self::TIMESLOTS_DAY_TARGET); } - - private function mapNewOrderEvent(Order $order): AnOrderHasBeenPlaced - { - return new AnOrderHasBeenPlaced( - orderId: $order->id(), - byMatricule: $order->employee->matricule, - employee: clone $order->employee, - reference: $order->reference, - totalTtc: $order->getTotal(), - shop: new OrderPlacedShop( - name: $order->deliveryAddress->name, - address: $order->deliveryAddress->address, - postcode: $order->deliveryAddress->postcode, - city: $order->deliveryAddress->city - ), - pickupDay: CarbonImmutable::instance($order->pickupTimeSlot->getAt()), - lines: array_map( - [$this, 'mapToPlaceOrderLine'], - $order->getLines() - ) - ); - } - - private function mapToPlaceOrderLine(OrderLine $line): OrderPlacedLine - { - return new OrderPlacedLine( - productName: $line->product->name, - productIncoId: clone $line->product->incoId, - productWeightIsVariable: $line->product->weight->isVariable, - productPriceKgTtc: clone $line->product->priceKgTtc, - productOrderUnit: $line->product->orderUnit, - quantity: $line->quantity, - totalTtc: clone $line->totalTtc - ); - } } diff --git a/domain/Services/PickupSchedulingService.php b/domain/Services/PickupSchedulingService.php index 4a316bed..7367c59d 100644 --- a/domain/Services/PickupSchedulingService.php +++ b/domain/Services/PickupSchedulingService.php @@ -71,11 +71,6 @@ class PickupSchedulingService return CarbonPeriod::create($defaultDeadLine, $pickupDate->endOfDay()); } - public function isPickupDay(PickupExceptionOnDate $exception): bool - { - return $exception->date->isDayOfWeek(self::PICKUP_DAY->value); - } - /** @return \Domain\Models\ValueObjects\EditablePickupExceptionForShop[] */ public function getEditablePickupExceptionsFor(Shop $shop): array { @@ -85,24 +80,23 @@ class PickupSchedulingService return array_map(function (PickupExceptionOnDate $pickupException) use ($shopExceptions) { $associated = null; foreach ($shopExceptions as $shopEx) { - if ($shopEx->exception->id->value === $pickupException->id->value) { + if ($shopEx->exception->id->equals($pickupException->id)) { $associated = $shopEx; break; } } - $isChecked = $associated !== null; - - $isPickupDay = $this->isPickupDay($pickupException); - $deadline = $associated?->orderDeadlineAt - ? CarbonImmutable::createFromInterface($associated->orderDeadlineAt) - : $this->getDefaultDeadline(CarbonImmutable::createFromInterface($pickupException->date)); + $isChecked = $associated !== null; + $isPickupDay = $pickupException->isPickupDay(self::PICKUP_DAY); + $defaultDeadline = $this->getDefaultDeadline($pickupException->date); + $isBlocked = $associated !== null && ! $associated->hasReplacement(); + $isPastDeadline = $associated !== null && $associated->isDeadlinePassed($this->getNow(), $defaultDeadline); return new EditablePickupExceptionForShop( $pickupException, $isPickupDay, - $isChecked && $isPickupDay && $associated->replacementDate === null, - $isChecked && $isPickupDay && $this->getNow()->greaterThan($deadline) + $isChecked && $isPickupDay && $isBlocked, + $isChecked && $isPickupDay && $isPastDeadline ); }, $allExceptions); } @@ -160,23 +154,15 @@ class PickupSchedulingService protected function getTimeSlotForException(ShopPickupOverride $shopPickupException): ?PickupTimeSlot { - $replacement = $shopPickupException->replacementDate; - - // ? Is there a substitute date configured ? - if ($replacement === null) { - // * Blocked week: exception active but no replacement provided + if (! $shopPickupException->hasReplacement() || $shopPickupException->replacementDate === null) { return null; } - // ? Is there an order deadline ? - $deadline = $shopPickupException->orderDeadlineAt - // * Use exception deadline. - ? CarbonImmutable::createFromInterface($shopPickupException->orderDeadlineAt) - // * Use default deadline. - : $this->getDefaultDeadline(CarbonImmutable::createFromInterface($shopPickupException->exception->date)); + $defaultDeadline = $this->getDefaultDeadline(CarbonImmutable::createFromInterface($shopPickupException->exception->date)); + $deadline = $shopPickupException->effectiveDeadline($defaultDeadline); return $this->isBefore($deadline) - ? $this->createTimeSlot($replacement->toImmutable()) + ? $this->createTimeSlot($shopPickupException->replacementDate->toImmutable()) : null; } diff --git a/domain/Services/PricingService.php b/domain/Services/PricingService.php deleted file mode 100644 index 6ff6ffba..00000000 --- a/domain/Services/PricingService.php +++ /dev/null @@ -1,131 +0,0 @@ -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); - - $priceKgTtc = $this->calculatePriceKgTtc($discountedPriceHt, $product); - $discountRate = $this->calculateDiscountRate($basePriceHt, $discountAmountHt, $product); - - return new ProductPricing( - basePriceHt: $basePriceHt, - basePriceTtc: $basePriceTtc, - discountAmountHt: $discountAmountHt, - discountedPriceHt: $discountedPriceHt, - discountedPriceTtc: $discountedPriceTtc, - priceKgTtc: $priceKgTtc, - discountRate: $discountRate, - hasDiscount: $product->validDiscount !== null - ); - } - - 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 x grams / 1000 (single rounding, no float) - return $product->price - ->multiply($product->product_weight->toGrams()) - ->divide(self::GRAMS_PER_KG, PricingService::ROUNDING); - } - - return $product->price; - } - - 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 x 1000 / grams (single rounding, no float) - return $priceTtc - ->multiply(self::GRAMS_PER_KG) - ->divide($grams, self::ROUNDING); - } - - return $priceTtc; - } - - private function applyTax(Money $price, TaxRate $taxRate): Money - { - return $taxRate->applyTo($price); - } - - private function calculateDiscountRate(Money $priceHt, Money $discountAmount, Product $product): DiscountRate - { - $discount = $product->validDiscount; - - if ($discount?->isPercentage()) { - return DiscountRate::fromPercentage($discount->getPercentage()); - } - - return DiscountRate::fromAmounts($discountAmount, $priceHt); - } -} diff --git a/domain/Services/ProductAvailabilityService.php b/domain/Services/ProductAvailabilityService.php deleted file mode 100644 index 62de956b..00000000 --- a/domain/Services/ProductAvailabilityService.php +++ /dev/null @@ -1,50 +0,0 @@ -orderable_start || $now->gt($product->orderable_start); - $end = ! $product->orderable_end || $now->lt($product->orderable_end); - $isOrderable = $start && $end; - - return $isOrderable && $product->status && $this->isAssociatedWithInco($product); - } - - public function isPublished(Product $product): bool - { - return $product->status; - } - - public function isBasketProductPublished(BasketProduct $basketProduct): bool - { - $product = $this->productRepository->find($basketProduct->id); - - if (! $product) { - // NOTE: Don't throw an exception here, as the product may have been deleted after being added to the basket - return false; - } - - return $this->isPublished($product); - } - - public function isAssociatedWithInco(Product $product): bool - { - return $product->hasInco; - } -} diff --git a/domain/Services/RegateService.php b/domain/Services/RegateService.php index 214f526a..96758aad 100644 --- a/domain/Services/RegateService.php +++ b/domain/Services/RegateService.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Domain\Services; use Carbon\CarbonImmutable; -use Domain\Enums\Units\OrderUnit as UnitsOrderUnit; use Domain\Events\Dto\RegateOrderCsvGenerated; use Domain\Models\ValueObjects\Matricule; use Domain\Models\ValueObjects\OrderReference; @@ -54,7 +53,7 @@ class RegateService (string) $line->productIncoId->value, 'commande ferme', (string) $line->productOrderUnit->value, - $this->maptoRegateUnit($line->productOrderUnit), + $line->productOrderUnit->toRegateCode(), '', $pickupDay->format('d/m/Y'), (string) $line->quantity, @@ -77,13 +76,4 @@ class RegateService new RegateOrderCsvGenerated($csvContent, $fileName) ); } - - private function maptoRegateUnit(UnitsOrderUnit $unit): string - { - return match ($unit) { - UnitsOrderUnit::COLIS => 'UEA', - UnitsOrderUnit::KGM => 'KGM', - UnitsOrderUnit::PCE => 'UB', - }; - } } diff --git a/domain/Services/ShopperService.php b/domain/Services/ShopperService.php index a5354255..ec12f9f6 100644 --- a/domain/Services/ShopperService.php +++ b/domain/Services/ShopperService.php @@ -36,11 +36,7 @@ class ShopperService { $shopper = $this->getShopperFor($shopperId); - if ($shopper === null) { - return null; - } - - return $this->resolveShopForEmployee($shopper); + return $shopper !== null ? $this->resolveShopForEmployee($shopper) : null; } public function resolveShopForEmployee(Shopper $shopper): Shop @@ -72,12 +68,6 @@ class ShopperService public function canCustomerPassOrdersApp(ShopperId $shopperId): bool { - $shopper = $this->getShopperFor($shopperId); - - if ($shopper === null) { - return false; - } - - return $shopper->isActive(); + return $this->getShopperFor($shopperId)?->isActive() ?? false; } } diff --git a/infra/Adapters/Repositories/EloquentProductRepository.php b/infra/Adapters/Repositories/EloquentProductRepository.php index c4cbb3e8..10e3884b 100644 --- a/infra/Adapters/Repositories/EloquentProductRepository.php +++ b/infra/Adapters/Repositories/EloquentProductRepository.php @@ -11,17 +11,11 @@ use Domain\Models\Entities\Product as DomainProduct; use Domain\Models\ValueObjects\BasketProduct; use Domain\Models\ValueObjects\Entities\ProductId; use Domain\Ports\Repositories\ProductRepository; -use Domain\Services\PricingService; use Illuminate\Support\Carbon; use Ramsey\Uuid\Uuid; class EloquentProductRepository implements ProductRepository { - public function __construct( - private readonly PricingService $pricingService - ) { - } - #[\Override] public function find(ProductId $id): ?DomainProduct { @@ -72,11 +66,12 @@ class EloquentProductRepository implements ProductRepository public function getBasketProduct(ProductId $id, int $qty): BasketProduct { $product = Product::query() + ->with(['inco', 'validDiscount']) ->where('id', $id->value) ->firstOrFail(); $domainProduct = $this->toEntity($product); - $pricing = $this->pricingService->calculateForProduct($domainProduct); + $pricing = $domainProduct->pricing(); return new BasketProduct( id: $id, diff --git a/lang/en.json b/lang/en.json index dbecbcf4..32a019bd 100644 --- a/lang/en.json +++ b/lang/en.json @@ -97,7 +97,7 @@ "Basket has been cleared": "Basket has been cleared", "Basket Summary": "Basket Summary", "Before proceeding, please check your email for a verification link.": "Before proceeding, please check your email for a verification link.", - "Bloqued week": "Bloqued week", + "Blocked week": "Blocked week", "Booking": "Booking", "Brand": "Brand", "Breadcrumb": "Breadcrumb", diff --git a/lang/fr.json b/lang/fr.json index ae85abe8..cf44c934 100644 --- a/lang/fr.json +++ b/lang/fr.json @@ -96,7 +96,7 @@ "Basket has been cleared": "Le panier a été vidé", "Basket Summary": "Récapitulatif de votre panier", "Before proceeding, please check your email for a verification link.": "Avant de continuer, merci de vérifier votre e-mail contenant un lien de vérification.", - "Bloqued week": "Semaine bloquée", + "Blocked week": "Semaine bloquée", "Booking": "Réservation", "Brand": "Marque", "Breadcrumb": "Fil d'Ariane", diff --git a/resources/views/bo/faqs/index-list.blade.php b/resources/views/bo/faqs/index-list.blade.php index 2aad3138..7de825bc 100644 --- a/resources/views/bo/faqs/index-list.blade.php +++ b/resources/views/bo/faqs/index-list.blade.php @@ -21,6 +21,8 @@ 'model' => $faq, 'first' => $loop->first, 'last' => $loop->last, + 'isFirstPage' => $faqs->onFirstPage(), + 'isLastPage' => !$faqs->hasMorePages(), ])
diff --git a/resources/views/bo/modules/change-order.blade.php b/resources/views/bo/modules/change-order.blade.php index 32ed87b1..4976f3e3 100644 --- a/resources/views/bo/modules/change-order.blade.php +++ b/resources/views/bo/modules/change-order.blade.php @@ -3,6 +3,24 @@ /** @var \Illuminate\Database\Eloquent\Model $model */ /** @var bool $first */ /** @var bool $last */ + /** @var bool $isFirstPage */ + /** @var bool $isLastPage */ + + if (!isset($first) || !is_bool($first)) { + throw new \InvalidArgumentException('The $first variable must be set and must be a boolean.'); + } + + if (!isset($last) || !is_bool($last)) { + throw new \InvalidArgumentException('The $last variable must be set and must be a boolean.'); + } + + if (!isset($isFirstPage) || !is_bool($isFirstPage)) { + throw new \InvalidArgumentException('The $isFirstPage variable must be set and must be a boolean.'); + } + + if (!isset($isLastPage) || !is_bool($isLastPage)) { + throw new \InvalidArgumentException('The $isLastPage variable must be set and must be a boolean.'); + } // * Route vars $routeName = request()->route()?->getName() ?? 'noroute'; @@ -25,6 +43,9 @@ // * Reset button $hasCustomSort = ($currentSortCol && $currentSortCol !== 'order') || ($currentSortCol === 'order' && $currentSortWay === 'desc'); $showReset = !empty($searchQuery) || $hasCustomSort; + + $isFirst = $first && $isFirstPage; + $isLast = $last && $isLastPage; @endphp @if (!$noOrder) @@ -56,13 +77,13 @@ @csrf @method('PATCH') - @if (!$first) + @if (!$isFirst) @endif - @if (!$last) + @if (!$isLast)