364 lines
12 KiB
PHP
364 lines
12 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Domain\Services;
|
|
|
|
use Carbon\CarbonImmutable;
|
|
use Carbon\CarbonInterface;
|
|
use Domain\Builders\OrderBuilder;
|
|
use Domain\Builders\OrderBuilderCompleted;
|
|
use Domain\Builders\OrderBuilderWithBasket;
|
|
use Domain\Exceptions\OrderTunnel\BasketPriceChangedException;
|
|
use Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException;
|
|
use Domain\Exceptions\OrderTunnel\InactiveShopperException;
|
|
use Domain\Exceptions\OrderTunnel\MissingOrderBuilderException;
|
|
use Domain\Exceptions\OrderTunnel\OrderLimitExceededException;
|
|
use Domain\Exceptions\OrderTunnel\RegateExportFailedException;
|
|
use Domain\Exceptions\OrderTunnel\UnorderableProductException;
|
|
use Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException;
|
|
use Domain\Models\Entities\Basket;
|
|
use Domain\Models\Entities\Order;
|
|
use Domain\Models\Entities\Shop;
|
|
use Domain\Models\Entities\Shopper;
|
|
use Domain\Models\ValueObjects\BasketProduct;
|
|
use Domain\Models\ValueObjects\Entities\OrderId;
|
|
use Domain\Models\ValueObjects\Entities\ShopperId;
|
|
use Domain\Models\ValueObjects\PickupTimeSlot;
|
|
use Domain\Policies\CustomerOrderLimitPolicy;
|
|
use Domain\Ports\Repositories\OrderRepository;
|
|
use Domain\Ports\Repositories\ProductRepository;
|
|
use Domain\Ports\Repositories\ShopperRepository;
|
|
use Domain\Ports\Repositories\ShopRepository;
|
|
use Domain\Ports\Services\EmployeeStatisticsService;
|
|
use Domain\Ports\Services\OrderBuilderSessionManager;
|
|
use Domain\Ports\Services\RegateService;
|
|
use Domain\Ports\Services\TunnelAttemptTrackerService;
|
|
use Shared\DDD\DomainEventDispatcher;
|
|
|
|
class OrderTunnelService
|
|
{
|
|
private const TIMESLOTS_DAY_TARGET = 28;
|
|
|
|
public function __construct(
|
|
private readonly DomainEventDispatcher $eventDispatcher,
|
|
private readonly ShopperService $shopperService,
|
|
private readonly OrderBuilderSessionManager $orderBuilderSessionManager,
|
|
private readonly PickupSchedulingService $pickupService,
|
|
private readonly OrderRepository $orderRepository,
|
|
private readonly ProductRepository $productRepository,
|
|
private readonly CustomerOrderLimitPolicy $orderLimitPolicy,
|
|
private readonly ShopRepository $shopRepository,
|
|
private readonly ShopperRepository $shopperRepository,
|
|
private readonly OrderService $orderService,
|
|
private readonly EmployeeStatisticsService $employeeStatisticsService,
|
|
private readonly RegateService $regateService,
|
|
private readonly TunnelAttemptTrackerService $tunnelAttemptTracker,
|
|
) {
|
|
}
|
|
|
|
public function canAccessBooking(): bool
|
|
{
|
|
$builder = $this->orderBuilderSessionManager->get();
|
|
|
|
return $builder instanceof OrderBuilderWithBasket
|
|
&& $builder->getBasket()->countItems() > 0;
|
|
}
|
|
|
|
public function canAccessConfirmation(): bool
|
|
{
|
|
$builder = $this->orderBuilderSessionManager->get();
|
|
|
|
return $builder instanceof OrderBuilderCompleted
|
|
&& $builder->getBasket()->countItems() > 0;
|
|
}
|
|
|
|
/**
|
|
* Resolve the shop assigned to a customer.
|
|
*
|
|
* @throws \UnexpectedValueException If no shop can be resolved.
|
|
*/
|
|
public function getShopForCustomer(ShopperId $customerId): Shop
|
|
{
|
|
return $this->shopperService->getShopFor($customerId)
|
|
?? throw new \UnexpectedValueException(
|
|
"No shop found for customer '{$customerId->value}'"
|
|
);
|
|
}
|
|
|
|
/** @return array<PickupTimeSlot> */
|
|
public function getAvailableTimeSlots(Shop $shop): array
|
|
{
|
|
return $this->pickupService->getTimeSlotsFor(
|
|
$shop,
|
|
$this->getTimeslotsUntil()
|
|
);
|
|
}
|
|
|
|
public function initializeFromBasket(Basket $basket, ShopperId $customerId): void
|
|
{
|
|
$builder = OrderBuilder::fromBasket($basket, $customerId);
|
|
|
|
$this->orderBuilderSessionManager->save($builder);
|
|
$this->tunnelAttemptTracker->recordEntry($customerId);
|
|
}
|
|
|
|
/**
|
|
* @throws \Domain\Exceptions\OrderTunnel\MissingOrderBuilderException
|
|
*/
|
|
public function getBuilderFromBasketOrFail(): OrderBuilderWithBasket
|
|
{
|
|
$builder = $this->orderBuilderSessionManager->get();
|
|
|
|
if (! $builder instanceof OrderBuilderWithBasket || $builder->getBasket()->countItems() === 0) {
|
|
throw new MissingOrderBuilderException();
|
|
}
|
|
|
|
return $builder;
|
|
}
|
|
|
|
/**
|
|
* @throws \Domain\Exceptions\OrderTunnel\MissingOrderBuilderException
|
|
*/
|
|
public function getBuilderCompletedOrFail(): OrderBuilderCompleted
|
|
{
|
|
$builder = $this->orderBuilderSessionManager->get();
|
|
|
|
if (! $builder instanceof OrderBuilderCompleted || $builder->getBasket()->countItems() === 0) {
|
|
throw new MissingOrderBuilderException();
|
|
}
|
|
|
|
return $builder;
|
|
}
|
|
|
|
/**
|
|
* Validate that the selected date matches an available slot and apply it to the builder.
|
|
*
|
|
* @param array<PickupTimeSlot> $availableSlots
|
|
*/
|
|
public function applyTimeSlot(
|
|
OrderBuilderWithBasket $builder,
|
|
Shop $shop,
|
|
CarbonInterface $selectedDate,
|
|
array $availableSlots
|
|
): ?PickupTimeSlot {
|
|
$matchedSlot = null;
|
|
foreach ($availableSlots as $ts) {
|
|
if ($selectedDate->isSameDay($ts->getAt())) {
|
|
$matchedSlot = $ts;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if ($matchedSlot === null) {
|
|
return null;
|
|
}
|
|
|
|
$completed = $builder->withPickupTimeSlot($shop->id(), $matchedSlot);
|
|
|
|
$this->orderBuilderSessionManager->save($completed);
|
|
|
|
return $matchedSlot;
|
|
}
|
|
|
|
/**
|
|
* Step 1 of order confirmation: validates basket, limits, shopper and slot,
|
|
* then persists the order in WAITING state without dispatching external notifications.
|
|
*
|
|
* @throws WeeklyLimitExceededException
|
|
* @throws OrderLimitExceededException
|
|
* @throws ExpiredPickupTimeSlotException
|
|
* @throws BasketPriceChangedException
|
|
* @throws UnorderableProductException
|
|
* @throws InactiveShopperException
|
|
*/
|
|
public function placePendingOrder(OrderBuilderCompleted $builder): Order
|
|
{
|
|
$order = $this->validateAndCreateOrder($builder, pending: true);
|
|
|
|
$this->orderRepository->persist($order);
|
|
|
|
return $order;
|
|
}
|
|
|
|
/**
|
|
* Step 2a (outside DB transaction): exports the pending order to Regate via SMTP.
|
|
*
|
|
* @throws RegateExportFailedException
|
|
*/
|
|
public function exportOrderToRegate(OrderId $orderId): void
|
|
{
|
|
$order = $this->orderRepository->find($orderId);
|
|
|
|
if (! $order) {
|
|
throw new \DomainException("Order with id '{$orderId->value}' not found.");
|
|
}
|
|
|
|
$placedEvent = $order->toPlacedEvent();
|
|
|
|
$this->regateService->processOrder(
|
|
$order->reference,
|
|
$order->employee->matricule,
|
|
CarbonImmutable::instance($order->pickupTimeSlot->getAt()),
|
|
$placedEvent->lines,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Step 2b (on Regate success): validates the order and dispatches AnOrderHasBeenPlaced.
|
|
*/
|
|
public function confirmPlacedOrder(OrderId $orderId): Order
|
|
{
|
|
$order = $this->orderService->validateOrder($orderId);
|
|
|
|
$this->tunnelAttemptTracker->markConverted($order->id());
|
|
$this->eventDispatcher->dispatch($order->toPlacedEvent());
|
|
|
|
return $order;
|
|
}
|
|
|
|
/**
|
|
* Step 2c (on Regate failure): marks the PENDING order as FAILED without emptying the basket.
|
|
*/
|
|
public function failPendingOrder(OrderId $orderId): void
|
|
{
|
|
$this->orderService->failOrder($orderId);
|
|
}
|
|
|
|
/**
|
|
* @throws WeeklyLimitExceededException
|
|
* @throws OrderLimitExceededException
|
|
* @throws ExpiredPickupTimeSlotException
|
|
* @throws BasketPriceChangedException
|
|
* @throws UnorderableProductException
|
|
* @throws InactiveShopperException
|
|
* @throws RegateExportFailedException
|
|
*/
|
|
public function finalizeOrder(OrderBuilderCompleted $builder): Order
|
|
{
|
|
$order = $this->validateAndCreateOrder($builder, pending: false);
|
|
|
|
$this->orderRepository->persist($order);
|
|
|
|
$placedEvent = $order->toPlacedEvent();
|
|
|
|
$this->regateService->processOrder(
|
|
$order->reference,
|
|
$order->employee->matricule,
|
|
CarbonImmutable::instance($order->pickupTimeSlot->getAt()),
|
|
$placedEvent->lines,
|
|
);
|
|
|
|
$this->eventDispatcher->dispatch($placedEvent);
|
|
|
|
return $order;
|
|
}
|
|
|
|
private function validateAndCreateOrder(OrderBuilderCompleted $builder, bool $pending): Order
|
|
{
|
|
$shopperId = $builder->getShopperId();
|
|
$basket = $this->revalidateBasket($builder->getBasket());
|
|
$pickupTimeSlot = $builder->getPickupTimeSlot();
|
|
$shopId = $builder->getShopId();
|
|
$shopper = $this->shopperRepository->getByIdOrFail($shopperId);
|
|
|
|
if (! $shopper->isActive()) {
|
|
throw new InactiveShopperException();
|
|
}
|
|
|
|
$this->assertBasketAmountWithinLimit($basket);
|
|
$this->assertBasketWeeklyAmountWithinLimitFor(
|
|
$shopper,
|
|
$basket,
|
|
$pickupTimeSlot->getAt()
|
|
);
|
|
|
|
$shop = $this->shopRepository->find($shopId);
|
|
if (! $shop) {
|
|
throw new \DomainException("Shop with id '{$shopId->value}' not found.");
|
|
}
|
|
|
|
$this->assertPickupTimeSlotIsAvailable($shop, $pickupTimeSlot);
|
|
|
|
return $pending
|
|
? $this->orderService->createPendingOrderFromBasket($basket, $pickupTimeSlot, $shopper, $shop)
|
|
: $this->orderService->createOrderFromBasket($basket, $pickupTimeSlot, $shopper, $shop);
|
|
}
|
|
|
|
/** @throws \Domain\Exceptions\OrderTunnel\OrderLimitExceededException */
|
|
public function assertBasketAmountWithinLimit(Basket $basket): void
|
|
{
|
|
$this->orderLimitPolicy->assertCanPlaceOrder($basket->totalTaxIncluded());
|
|
}
|
|
|
|
/** @throws \Domain\Exceptions\OrderTunnel\WeeklyLimitExceededException */
|
|
public function assertBasketWeeklyAmountWithinLimitFor(
|
|
Shopper $shopper,
|
|
Basket $withBasket,
|
|
\DateTimeInterface $atDate
|
|
): void {
|
|
$startOfWeek = CarbonImmutable::instance($atDate)->startOfWeek(CarbonInterface::MONDAY);
|
|
$endOfWeek = CarbonImmutable::instance($atDate)->endOfWeek(CarbonInterface::SUNDAY);
|
|
|
|
$weekTotal = $this->employeeStatisticsService->getWeeklyTotalForEmployee(
|
|
$shopper->matricule,
|
|
$startOfWeek,
|
|
$endOfWeek
|
|
);
|
|
|
|
$this->orderLimitPolicy->assertCanPlaceWeeklyOrder($withBasket->totalTaxIncluded(), $weekTotal);
|
|
}
|
|
|
|
private function revalidateBasket(Basket $basket): Basket
|
|
{
|
|
$refreshedItems = [];
|
|
$priceChanged = false;
|
|
|
|
foreach ($basket->items() as $item) {
|
|
$refreshed = $this->productRepository->getBasketProduct($item->id, $item->qty);
|
|
|
|
if ($this->hasItemPricingChanged($item, $refreshed)) {
|
|
$priceChanged = true;
|
|
}
|
|
|
|
$refreshedItems[] = $refreshed;
|
|
}
|
|
|
|
$refreshedBasket = new Basket($basket->id, $refreshedItems);
|
|
|
|
if ($priceChanged || ! $refreshedBasket->totalTaxIncluded()->equals($basket->totalTaxIncluded())) {
|
|
throw new BasketPriceChangedException($refreshedBasket);
|
|
}
|
|
|
|
return $refreshedBasket;
|
|
}
|
|
|
|
private function hasItemPricingChanged(BasketProduct $original, BasketProduct $refreshed): bool
|
|
{
|
|
return ! $refreshed->unitPriceHt->equals($original->unitPriceHt)
|
|
|| ! $refreshed->unitDiscount->equals($original->unitDiscount)
|
|
|| $refreshed->taxRate !== $original->taxRate
|
|
|| ! $refreshed->totalTtc()->equals($original->totalTtc());
|
|
}
|
|
|
|
/**
|
|
* @throws \Domain\Exceptions\OrderTunnel\ExpiredPickupTimeSlotException
|
|
*/
|
|
private function assertPickupTimeSlotIsAvailable(Shop $shop, PickupTimeSlot $pickupTimeSlot): void
|
|
{
|
|
$availableSlots = $this->getAvailableTimeSlots($shop);
|
|
|
|
foreach ($availableSlots as $slot) {
|
|
if (CarbonImmutable::instance($pickupTimeSlot->getAt())->isSameDay($slot->getAt())) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
throw new ExpiredPickupTimeSlotException();
|
|
}
|
|
|
|
private function getTimeslotsUntil(): CarbonInterface
|
|
{
|
|
return CarbonImmutable::now()->addDays(self::TIMESLOTS_DAY_TARGET);
|
|
}
|
|
}
|