diff --git a/Classes/Controller/Backend/Order/AbstractStatusController.php b/Classes/Controller/Backend/Order/AbstractStatusController.php index a251e62a..90f95747 100644 --- a/Classes/Controller/Backend/Order/AbstractStatusController.php +++ b/Classes/Controller/Backend/Order/AbstractStatusController.php @@ -88,6 +88,11 @@ protected function changeStatus(AbstractService $service, string $status, string '', ContextualFeedbackSeverity::WARNING ), + StatusChangeOutcome::NotAllowed => $this->addFlashMessage( + self::translate($labelPrefix . 'not_allowed', [$status]), + '', + ContextualFeedbackSeverity::WARNING + ), }; // e.g. an email which could not be sent, the status is changed anyway diff --git a/Classes/Domain/Order/Fulfillment/OrderItemLock.php b/Classes/Domain/Order/Fulfillment/OrderItemLock.php new file mode 100644 index 00000000..16aeb6e0 --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/OrderItemLock.php @@ -0,0 +1,82 @@ +connectionPool->getConnectionForTable(self::ORDER_ITEM_TABLE_NAME); + if (!$connection->isTransactionActive()) { + throw new LogicException('The order can only be locked within a transaction.', 1795600001); + } + + if ($connection->getDatabasePlatform() instanceof SQLitePlatform) { + // SQLite does not support SELECT ... FOR UPDATE, a write locks the database until the commit + $affectedRows = $connection->executeStatement( + 'UPDATE ' . $connection->quoteIdentifier(self::ORDER_ITEM_TABLE_NAME) + . ' SET ' . $connection->quoteIdentifier('uid') . ' = ' . $connection->quoteIdentifier('uid') + . ' WHERE ' . $connection->quoteIdentifier('uid') . ' = ?', + [$orderItemUid], + [Connection::PARAM_INT] + ); + if ($affectedRows === 0) { + throw self::createOrderNotFoundException($orderItemUid); + } + + return; + } + + $queryBuilder = $connection->createQueryBuilder(); + $queryBuilder->getRestrictions()->removeAll(); + $queryBuilder + ->select('uid') + ->from(self::ORDER_ITEM_TABLE_NAME) + ->where( + $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($orderItemUid, Connection::PARAM_INT)) + ) + ; + $queryBuilder->getConcreteQueryBuilder()->forUpdate(); + + if ($queryBuilder->executeQuery()->fetchOne() === false) { + throw self::createOrderNotFoundException($orderItemUid); + } + } + + private static function createOrderNotFoundException(int $orderItemUid): InvalidArgumentException + { + return new InvalidArgumentException('The order item ' . $orderItemUid . ' does not exist.', 1795600002); + } +} diff --git a/Classes/Domain/Order/Fulfillment/OrderProductQuantities.php b/Classes/Domain/Order/Fulfillment/OrderProductQuantities.php new file mode 100644 index 00000000..0579433b --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/OrderProductQuantities.php @@ -0,0 +1,93 @@ + + */ +final readonly class OrderProductQuantities implements Countable, IteratorAggregate +{ + /** + * @var array + */ + private array $quantitiesByOrderProductUid; + + public function __construct(OrderProductQuantity ...$orderProductQuantities) + { + $quantitiesByOrderProductUid = []; + foreach ($orderProductQuantities as $orderProductQuantity) { + $quantitiesByOrderProductUid[$orderProductQuantity->orderProductUid] = $orderProductQuantity; + } + $this->quantitiesByOrderProductUid = $quantitiesByOrderProductUid; + } + + public function findByOrderProductUid(int $orderProductUid): ?OrderProductQuantity + { + return $this->quantitiesByOrderProductUid[$orderProductUid] ?? null; + } + + public function hasShippableProducts(): bool + { + return $this->getShippableQuantities() !== []; + } + + public function isAnythingShipped(): bool + { + foreach ($this->getShippableQuantities() as $orderProductQuantity) { + if ($orderProductQuantity->shippedCount > 0) { + return true; + } + } + + return false; + } + + public function isEverythingShipped(): bool + { + foreach ($this->getShippableQuantities() as $orderProductQuantity) { + if (!$orderProductQuantity->isCompletelyShipped()) { + return false; + } + } + + return $this->hasShippableProducts(); + } + + /** + * @return ArrayIterator + */ + public function getIterator(): ArrayIterator + { + return new ArrayIterator($this->quantitiesByOrderProductUid); + } + + public function count(): int + { + return count($this->quantitiesByOrderProductUid); + } + + /** + * @return list + */ + private function getShippableQuantities(): array + { + return array_values(array_filter( + $this->quantitiesByOrderProductUid, + static fn (OrderProductQuantity $orderProductQuantity): bool => $orderProductQuantity->isShippable + && $orderProductQuantity->orderedCount > 0 + )); + } +} diff --git a/Classes/Domain/Order/Fulfillment/OrderProductQuantity.php b/Classes/Domain/Order/Fulfillment/OrderProductQuantity.php new file mode 100644 index 00000000..36c19fe4 --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/OrderProductQuantity.php @@ -0,0 +1,38 @@ +isShippable) { + return 0; + } + + return max(0, $this->orderedCount - $this->countInUncanceledShipments); + } + + public function isCompletelyShipped(): bool + { + return $this->shippedCount >= $this->orderedCount; + } +} diff --git a/Classes/Domain/Order/Fulfillment/OrderProductQuantityCalculator.php b/Classes/Domain/Order/Fulfillment/OrderProductQuantityCalculator.php new file mode 100644 index 00000000..b6f614d0 --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/OrderProductQuantityCalculator.php @@ -0,0 +1,91 @@ +shipmentRepository->findByOrderItem($orderItemUid) as $shipment) { + if ($shipment->status === ShipmentStatus::CANCELED) { + continue; + } + $isShipped = in_array($shipment->status, self::SHIPPED_STATUSES, true); + foreach ($shipment->products as $shipmentProduct) { + $orderProductUid = $shipmentProduct->orderProductUid; + $countInUncanceledShipmentsByOrderProductUid[$orderProductUid] + = ($countInUncanceledShipmentsByOrderProductUid[$orderProductUid] ?? 0) + $shipmentProduct->count; + if ($isShipped) { + $shippedCountByOrderProductUid[$orderProductUid] + = ($shippedCountByOrderProductUid[$orderProductUid] ?? 0) + $shipmentProduct->count; + } + } + } + + return new OrderProductQuantities(...array_map( + static function (array $orderProductRow) use ($countInUncanceledShipmentsByOrderProductUid, $shippedCountByOrderProductUid): OrderProductQuantity { + $orderProductUid = self::toInt($orderProductRow['uid'] ?? 0); + + return new OrderProductQuantity( + orderProductUid: $orderProductUid, + isShippable: (bool) self::toInt($orderProductRow['shippable'] ?? 0), + orderedCount: self::toInt($orderProductRow['count'] ?? 0), + countInUncanceledShipments: $countInUncanceledShipmentsByOrderProductUid[$orderProductUid] ?? 0, + shippedCount: $shippedCountByOrderProductUid[$orderProductUid] ?? 0, + ); + }, + $this->findOrderProductRows($orderItemUid) + )); + } + + /** + * @return list> + */ + private function findOrderProductRows(int $orderItemUid): array + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable(self::ORDER_PRODUCT_TABLE_NAME); + + return $queryBuilder + ->select('uid', 'count', 'shippable') + ->from(self::ORDER_PRODUCT_TABLE_NAME) + ->where( + $queryBuilder->expr()->eq('item', $queryBuilder->createNamedParameter($orderItemUid, Connection::PARAM_INT)) + ) + ->orderBy('uid', 'ASC') + ->executeQuery() + ->fetchAllAssociative() + ; + } + + private static function toInt(mixed $value): int + { + return is_numeric($value) ? (int) $value : 0; + } +} diff --git a/Classes/Domain/Order/Fulfillment/OrderShippingStatusUpdater.php b/Classes/Domain/Order/Fulfillment/OrderShippingStatusUpdater.php new file mode 100644 index 00000000..cfe4abda --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/OrderShippingStatusUpdater.php @@ -0,0 +1,67 @@ +itemRepository->findByUid($orderItemUid); + $shipping = $orderItem instanceof Item ? $orderItem->getShipping() : null; + if ($shipping === null) { + return null; + } + + $orderProductQuantities = $this->orderProductQuantityCalculator->calculateForOrderItem($orderItemUid); + $storedStatus = $shipping->getStatus(); + $derivedStatus = ShippingStatusDerivation::derive($storedStatus, $orderProductQuantities); + if ($derivedStatus === $storedStatus) { + return null; + } + + $result = $this->statusChangeService->change($shipping, $derivedStatus, $storedStatus, $initiator, $request, $source); + if ($result->outcome !== StatusChangeOutcome::Stale || $result->storedStatus === null) { + return $result; + } + + // the loaded order is outdated, e.g. the status was changed in the same request before + $derivedStatus = ShippingStatusDerivation::derive($result->storedStatus, $orderProductQuantities); + if ($derivedStatus === $result->storedStatus) { + return null; + } + + return $this->statusChangeService->change($shipping, $derivedStatus, $result->storedStatus, $initiator, $request, $source); + } +} diff --git a/Classes/Domain/Order/Fulfillment/Shipment.php b/Classes/Domain/Order/Fulfillment/Shipment.php index aa971a52..36e9279b 100644 --- a/Classes/Domain/Order/Fulfillment/Shipment.php +++ b/Classes/Domain/Order/Fulfillment/Shipment.php @@ -38,4 +38,25 @@ public function __construct( public int $uid = 0, ) { } + + public function getOrderChangeSubject(): string + { + return 'shipment:' . $this->uid; + } + + public function withStatus(string $status): self + { + return new self( + $this->orderItemUid, + $status, + $this->products, + $this->carrier, + $this->trackingNumber, + $this->trackingUrl, + $this->shippedDate, + $this->note, + $this->isReplacement, + $this->uid, + ); + } } diff --git a/Classes/Domain/Order/Fulfillment/ShipmentCreationOutcome.php b/Classes/Domain/Order/Fulfillment/ShipmentCreationOutcome.php new file mode 100644 index 00000000..02c10bd6 --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/ShipmentCreationOutcome.php @@ -0,0 +1,19 @@ + + */ + public array $exceededOrderProductUids = [], + public ?StatusChangeResult $shippingStatusChange = null, + ) { + } + + public function isCreated(): bool + { + return $this->outcome === ShipmentCreationOutcome::Created; + } +} diff --git a/Classes/Domain/Order/Fulfillment/ShipmentCreationService.php b/Classes/Domain/Order/Fulfillment/ShipmentCreationService.php new file mode 100644 index 00000000..f6bec133 --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/ShipmentCreationService.php @@ -0,0 +1,170 @@ +assertCanBeCreated($shipment); + $source = $this->statusTransition->resolveSource($request, $source); + + $result = $this->connectionPool->getConnectionForTable(self::ORDER_ITEM_TABLE_NAME)->transactional( + function () use ($shipment, $source, $initiator): ShipmentCreationResult { + $this->orderItemLock->lock($shipment->orderItemUid); + + $exceededOrderProductUids = $this->findExceededOrderProductUids($shipment); + if ($exceededOrderProductUids !== []) { + return new ShipmentCreationResult( + ShipmentCreationOutcome::QuantityExceeded, + exceededOrderProductUids: $exceededOrderProductUids + ); + } + + $storedShipment = $this->shipmentRepository->findByUid($this->shipmentRepository->add($shipment)) + ?? throw new RuntimeException('The stored shipment could not be found.', 1795600013); + $orderChange = new OrderChange( + orderItem: $shipment->orderItemUid, + type: OrderChangeType::SHIPMENT_STATUS, + oldValue: '', + newValue: $shipment->status, + date: $this->statusTransition->getNow(), + source: $source, + backendUser: $this->statusTransition->getBackendUserUid(), + initiator: $initiator, + subject: $storedShipment->getOrderChangeSubject(), + data: [ + 'products' => array_map( + static fn (ShipmentProduct $shipmentProduct): array => [ + 'orderProduct' => $shipmentProduct->orderProductUid, + 'count' => $shipmentProduct->count, + ], + $storedShipment->products + ), + ], + ); + + return new ShipmentCreationResult( + ShipmentCreationOutcome::Created, + $storedShipment, + $orderChange->withUid($this->orderChangeRepository->add($orderChange)) + ); + } + ); + + if (!$result->isCreated()) { + return $result; + } + + return new ShipmentCreationResult( + $result->outcome, + $result->shipment, + $result->orderChange, + shippingStatusChange: $this->orderShippingStatusUpdater->changeToDerivedStatus($shipment->orderItemUid, $initiator, $request, $source), + ); + } + + private function assertCanBeCreated(Shipment $shipment): void + { + if ($shipment->uid !== 0) { + throw new InvalidArgumentException('The shipment ' . $shipment->uid . ' is stored already.', 1795600010); + } + if ( + $shipment->status === ShipmentStatus::CANCELED + || !$this->orderStatusRegistry->hasStatus(ServiceType::Shipment, $shipment->status) + ) { + throw new InvalidArgumentException('A shipment can not be created with the status "' . $shipment->status . '".', 1795600011); + } + if ($shipment->products === []) { + throw new InvalidArgumentException('A shipment needs at least one product.', 1795600012); + } + foreach ($shipment->products as $shipmentProduct) { + if ($shipmentProduct->count <= 0) { + throw new InvalidArgumentException( + 'The count of the ordered product ' . $shipmentProduct->orderProductUid . ' must be greater than 0.', + 1795600014 + ); + } + } + } + + /** + * @return list + */ + private function findExceededOrderProductUids(Shipment $shipment): array + { + $orderProductQuantities = $this->orderProductQuantityCalculator->calculateForOrderItem($shipment->orderItemUid); + + $exceededOrderProductUids = []; + foreach (self::sumCountsByOrderProductUid($shipment) as $orderProductUid => $count) { + $orderProductQuantity = $orderProductQuantities->findByOrderProductUid($orderProductUid) ?? throw new InvalidArgumentException( + 'The ordered product ' . $orderProductUid . ' does not belong to the order item ' . $shipment->orderItemUid . '.', + 1795600015 + ); + if (!$orderProductQuantity->isShippable) { + throw new InvalidArgumentException('The ordered product ' . $orderProductUid . ' is not shippable.', 1795600016); + } + if ($count > $orderProductQuantity->getCountAvailableForShipment()) { + $exceededOrderProductUids[] = $orderProductUid; + } + } + + return $exceededOrderProductUids; + } + + /** + * @return array + */ + private static function sumCountsByOrderProductUid(Shipment $shipment): array + { + $countsByOrderProductUid = []; + foreach ($shipment->products as $shipmentProduct) { + $countsByOrderProductUid[$shipmentProduct->orderProductUid] + = ($countsByOrderProductUid[$shipmentProduct->orderProductUid] ?? 0) + $shipmentProduct->count; + } + + return $countsByOrderProductUid; + } +} diff --git a/Classes/Domain/Order/Fulfillment/ShipmentRepository.php b/Classes/Domain/Order/Fulfillment/ShipmentRepository.php index 8663c702..8e6b55ae 100644 --- a/Classes/Domain/Order/Fulfillment/ShipmentRepository.php +++ b/Classes/Domain/Order/Fulfillment/ShipmentRepository.php @@ -106,6 +106,45 @@ static function (Connection $connection) use ($shipment, $orderItemPid, $timesta ); } + public function changeStatusIfExpected(int $shipmentUid, string $fromStatus, string $toStatus, DateTimeImmutable $date): bool + { + $affectedRows = $this->connectionPool->getConnectionForTable(self::ORDER_SHIPMENT_TABLE_NAME)->update( + self::ORDER_SHIPMENT_TABLE_NAME, + [ + 'status' => $toStatus, + 'tstamp' => $date->getTimestamp(), + ], + [ + 'uid' => $shipmentUid, + 'status' => $fromStatus, + 'deleted' => 0, + ], + [ + 'tstamp' => Connection::PARAM_INT, + 'uid' => Connection::PARAM_INT, + 'deleted' => Connection::PARAM_INT, + ] + ); + + return $affectedRows > 0; + } + + public function findStatusByShipmentUid(int $shipmentUid): ?string + { + $queryBuilder = $this->connectionPool->getQueryBuilderForTable(self::ORDER_SHIPMENT_TABLE_NAME); + $status = $queryBuilder + ->select('status') + ->from(self::ORDER_SHIPMENT_TABLE_NAME) + ->where( + $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($shipmentUid, Connection::PARAM_INT)) + ) + ->executeQuery() + ->fetchOne() + ; + + return is_string($status) ? $status : null; + } + public function findByUid(int $shipmentUid): ?Shipment { $queryBuilder = $this->connectionPool->getQueryBuilderForTable(self::ORDER_SHIPMENT_TABLE_NAME); diff --git a/Classes/Domain/Order/Fulfillment/ShipmentStatusChangeResult.php b/Classes/Domain/Order/Fulfillment/ShipmentStatusChangeResult.php new file mode 100644 index 00000000..224c0220 --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/ShipmentStatusChangeResult.php @@ -0,0 +1,28 @@ +shipmentStatusChange->isChanged(); + } +} diff --git a/Classes/Domain/Order/Fulfillment/ShipmentStatusChangeService.php b/Classes/Domain/Order/Fulfillment/ShipmentStatusChangeService.php new file mode 100644 index 00000000..ff02aa6b --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/ShipmentStatusChangeService.php @@ -0,0 +1,128 @@ +statusTransition->resolveSource($request, $source); + + if ($shipment->uid === 0) { + throw new InvalidArgumentException('The status can only be changed for stored shipments.', 1795600020); + } + + if (!$this->orderStatusRegistry->hasStatus(ServiceType::Shipment, $toStatus)) { + return new ShipmentStatusChangeResult(new StatusChangeResult(StatusChangeOutcome::UnknownStatus)); + } + + if ($toStatus === $fromStatus) { + return new ShipmentStatusChangeResult(new StatusChangeResult(StatusChangeOutcome::Unchanged)); + } + + if (!self::isTransitionAllowed($fromStatus, $toStatus)) { + return new ShipmentStatusChangeResult(new StatusChangeResult(StatusChangeOutcome::NotAllowed)); + } + + $backendUserUid = $this->statusTransition->getBackendUserUid(); + $beforeShipmentStatusChangeEvent = new BeforeShipmentStatusChangeEvent( + $shipment, + $fromStatus, + $toStatus, + $source, + $initiator, + $backendUserUid + ); + $this->eventDispatcher->dispatch($beforeShipmentStatusChangeEvent); + if ($beforeShipmentStatusChangeEvent->isVetoed()) { + return new ShipmentStatusChangeResult( + new StatusChangeResult(StatusChangeOutcome::Vetoed, vetoReason: $beforeShipmentStatusChangeEvent->getVetoReason()) + ); + } + + $result = $this->statusTransition->apply( + new OrderChange( + orderItem: $shipment->orderItemUid, + type: OrderChangeType::SHIPMENT_STATUS, + oldValue: $fromStatus, + newValue: $toStatus, + date: $this->statusTransition->getNow(), + source: $source, + backendUser: $backendUserUid, + initiator: $initiator, + subject: $shipment->getOrderChangeSubject(), + ), + fn (string $fromStatus, string $toStatus, DateTimeImmutable $date): bool => $this->shipmentRepository->changeStatusIfExpected($shipment->uid, $fromStatus, $toStatus, $date), + fn (): ?string => $this->shipmentRepository->findStatusByShipmentUid($shipment->uid), + ); + + if ($result->orderChange === null) { + return new ShipmentStatusChangeResult($result); + } + + // after the transaction, listeners may take time, e.g. to send an email + $afterShipmentStatusChangeEvent = new AfterShipmentStatusChangeEvent($shipment->withStatus($toStatus), $result->orderChange); + $this->eventDispatcher->dispatch($afterShipmentStatusChangeEvent); + if ($afterShipmentStatusChangeEvent->getErrors() !== []) { + $result = new StatusChangeResult($result->outcome, $result->orderChange, errors: $afterShipmentStatusChangeEvent->getErrors()); + } + + return new ShipmentStatusChangeResult( + $result, + $this->orderShippingStatusUpdater->changeToDerivedStatus($shipment->orderItemUid, $initiator, $request, $source) + ); + } + + private static function isTransitionAllowed(string $fromStatus, string $toStatus): bool + { + if ($fromStatus === ShipmentStatus::CANCELED) { + return false; + } + + return $toStatus !== ShipmentStatus::CANCELED || !in_array($fromStatus, self::NOT_CANCELABLE_STATUSES, true); + } +} diff --git a/Classes/Domain/Order/Fulfillment/ShippingStatusDerivation.php b/Classes/Domain/Order/Fulfillment/ShippingStatusDerivation.php new file mode 100644 index 00000000..a0244604 --- /dev/null +++ b/Classes/Domain/Order/Fulfillment/ShippingStatusDerivation.php @@ -0,0 +1,33 @@ +hasShippableProducts() => ShippingStatus::NOT_REQUIRED, + $orderProductQuantities->isEverythingShipped() => ShippingStatus::SHIPPED, + $orderProductQuantities->isAnythingShipped() => ShippingStatus::PARTIALLY_SHIPPED, + in_array($storedStatus, self::STATUSES_DERIVED_FROM_SHIPMENTS, true) => ShippingStatus::IN_PROCESS, + default => $storedStatus, + }; + } +} diff --git a/Classes/Domain/Order/History/OrderChangeType.php b/Classes/Domain/Order/History/OrderChangeType.php index d1a14b3e..86652b39 100644 --- a/Classes/Domain/Order/History/OrderChangeType.php +++ b/Classes/Domain/Order/History/OrderChangeType.php @@ -20,4 +20,6 @@ final class OrderChangeType public const PAYMENT_STATUS = 'payment_status'; public const SHIPPING_STATUS = 'shipping_status'; + + public const SHIPMENT_STATUS = 'shipment_status'; } diff --git a/Classes/Domain/Order/History/OrderHistoryService.php b/Classes/Domain/Order/History/OrderHistoryService.php index e3b532f6..8ce7f396 100644 --- a/Classes/Domain/Order/History/OrderHistoryService.php +++ b/Classes/Domain/Order/History/OrderHistoryService.php @@ -53,6 +53,7 @@ private function getValueLabel(string $type, string $value): string $serviceType = match ($type) { OrderChangeType::PAYMENT_STATUS => ServiceType::Payment, OrderChangeType::SHIPPING_STATUS => ServiceType::Shipping, + OrderChangeType::SHIPMENT_STATUS => ServiceType::Shipment, default => null, }; if ($serviceType === null) { diff --git a/Classes/Domain/Order/Status/StatusChangeOutcome.php b/Classes/Domain/Order/Status/StatusChangeOutcome.php index 2e11d833..4d3ed696 100644 --- a/Classes/Domain/Order/Status/StatusChangeOutcome.php +++ b/Classes/Domain/Order/Status/StatusChangeOutcome.php @@ -42,4 +42,6 @@ enum StatusChangeOutcome * changed, see StatusChangeResult::$vetoReason. */ case Vetoed; + + case NotAllowed; } diff --git a/Classes/Domain/Order/Status/StatusChangeService.php b/Classes/Domain/Order/Status/StatusChangeService.php index 6007e4a0..c8e1335d 100644 --- a/Classes/Domain/Order/Status/StatusChangeService.php +++ b/Classes/Domain/Order/Status/StatusChangeService.php @@ -16,7 +16,6 @@ use Extcode\Cart\Domain\Model\Order\Payment; use Extcode\Cart\Domain\Model\Order\Shipping; use Extcode\Cart\Domain\Order\History\OrderChange; -use Extcode\Cart\Domain\Order\History\OrderChangeRepository; use Extcode\Cart\Domain\Order\History\OrderChangeSource; use Extcode\Cart\Domain\Order\History\OrderChangeType; use Extcode\Cart\Event\Order\AfterStatusChangeEvent; @@ -24,7 +23,6 @@ use InvalidArgumentException; use Psr\EventDispatcher\EventDispatcherInterface; use Psr\Http\Message\ServerRequestInterface; -use TYPO3\CMS\Core\Context\Context; use TYPO3\CMS\Core\Database\Connection; use TYPO3\CMS\Core\Database\ConnectionPool; @@ -44,8 +42,7 @@ public function __construct( private ConnectionPool $connectionPool, private OrderStatusRegistry $orderStatusRegistry, - private OrderChangeRepository $orderChangeRepository, - private Context $context, + private StatusTransition $statusTransition, private EventDispatcherInterface $eventDispatcher, ) { } @@ -70,10 +67,7 @@ public function change( ?ServerRequestInterface $request = null, ?OrderChangeSource $source = null ): StatusChangeResult { - if ($source === null) { - $request ??= $GLOBALS['TYPO3_REQUEST'] ?? null; - $source = OrderChangeSource::fromRequest($request instanceof ServerRequestInterface ? $request : null); - } + $source = $this->statusTransition->resolveSource($request, $source); [$serviceType, $changeType] = self::getServiceTypeAndChangeType($service); $serviceUid = $service->getUid(); @@ -86,12 +80,12 @@ public function change( if (!$this->orderStatusRegistry->hasStatus($serviceType, $toStatus)) { return new StatusChangeResult(StatusChangeOutcome::UnknownStatus); } + if ($toStatus === $fromStatus) { return new StatusChangeResult(StatusChangeOutcome::Unchanged); } - $backendUser = $this->getBackendUserUid(); - + $backendUserUid = $this->statusTransition->getBackendUserUid(); $beforeStatusChangeEvent = new BeforeStatusChangeEvent( $orderItem, $service, @@ -100,7 +94,7 @@ public function change( $toStatus, $source, $initiator, - $backendUser + $backendUserUid ); $this->eventDispatcher->dispatch($beforeStatusChangeEvent); if ($beforeStatusChangeEvent->isVetoed()) { @@ -108,53 +102,24 @@ public function change( } $table = 'tx_cart_domain_model_order_' . $serviceType->value; - $connection = $this->connectionPool->getConnectionForTable($table); - $orderChange = new OrderChange( - orderItem: $orderItemUid, - type: $changeType, - oldValue: $fromStatus, - newValue: $toStatus, - date: $this->getNow(), - source: $source, - backendUser: $backendUser, - initiator: $initiator, - ); - - $result = $connection->transactional( - function (Connection $connection) use ($table, $serviceUid, $toStatus, $fromStatus, $orderChange): StatusChangeResult { - $affectedRows = $connection->update( - $table, - [ - 'status' => $toStatus, - 'tstamp' => $orderChange->date->getTimestamp(), - ], - [ - 'uid' => $serviceUid, - 'status' => $fromStatus, - ], - [ - 'tstamp' => Connection::PARAM_INT, - 'uid' => Connection::PARAM_INT, - ] - ); - - if ($affectedRows === 0) { - $storedStatus = $this->getStoredStatus($table, $serviceUid); - - return $storedStatus === $toStatus - ? new StatusChangeResult(StatusChangeOutcome::Unchanged) - : new StatusChangeResult(StatusChangeOutcome::Stale, storedStatus: $storedStatus); - } - - return new StatusChangeResult( - StatusChangeOutcome::Changed, - $orderChange->withUid($this->orderChangeRepository->add($orderChange)) - ); - } + $result = $this->statusTransition->apply( + new OrderChange( + orderItem: $orderItemUid, + type: $changeType, + oldValue: $fromStatus, + newValue: $toStatus, + date: $this->statusTransition->getNow(), + source: $source, + backendUser: $backendUserUid, + initiator: $initiator, + ), + fn (string $fromStatus, string $toStatus, DateTimeImmutable $date): bool => $this->changeStoredStatusIfExpected($table, $serviceUid, $fromStatus, $toStatus, $date), + fn (): ?string => $this->findStoredStatus($table, $serviceUid), ); if ($result->orderChange !== null) { $service->setStatus($toStatus); + // after the transaction, listeners may take time, e.g. to send an email $afterStatusChangeEvent = new AfterStatusChangeEvent($orderItem, $service, $serviceType, $result->orderChange); $this->eventDispatcher->dispatch($afterStatusChangeEvent); @@ -181,7 +146,33 @@ private static function getServiceTypeAndChangeType(AbstractService $service): a }; } - private function getStoredStatus(string $table, int $serviceUid): ?string + private function changeStoredStatusIfExpected( + string $table, + int $serviceUid, + string $fromStatus, + string $toStatus, + DateTimeImmutable $date + ): bool { + $affectedRows = $this->connectionPool->getConnectionForTable($table)->update( + $table, + [ + 'status' => $toStatus, + 'tstamp' => $date->getTimestamp(), + ], + [ + 'uid' => $serviceUid, + 'status' => $fromStatus, + ], + [ + 'tstamp' => Connection::PARAM_INT, + 'uid' => Connection::PARAM_INT, + ] + ); + + return $affectedRows > 0; + } + + private function findStoredStatus(string $table, int $serviceUid): ?string { $queryBuilder = $this->connectionPool->getQueryBuilderForTable($table); $queryBuilder->getRestrictions()->removeAll(); @@ -197,18 +188,4 @@ private function getStoredStatus(string $table, int $serviceUid): ?string return is_string($status) ? $status : null; } - - private function getNow(): DateTimeImmutable - { - $now = $this->context->getPropertyFromAspect('date', 'full'); - - return $now instanceof DateTimeImmutable ? $now : new DateTimeImmutable(); - } - - private function getBackendUserUid(): int - { - $uid = $this->context->getPropertyFromAspect('backend.user', 'id', 0); - - return is_int($uid) ? $uid : 0; - } } diff --git a/Classes/Domain/Order/Status/StatusTransition.php b/Classes/Domain/Order/Status/StatusTransition.php new file mode 100644 index 00000000..13d28587 --- /dev/null +++ b/Classes/Domain/Order/Status/StatusTransition.php @@ -0,0 +1,94 @@ +context->getPropertyFromAspect('date', 'full'); + + return $now instanceof DateTimeImmutable ? $now : new DateTimeImmutable(); + } + + public function getBackendUserUid(): int + { + $uid = $this->context->getPropertyFromAspect('backend.user', 'id', 0); + + return is_int($uid) ? $uid : 0; + } + + /** + * @param Closure(string $fromStatus, string $toStatus, DateTimeImmutable $date): bool $changeStoredStatusIfExpected + * @param Closure(): ?string $findStoredStatus + */ + public function apply( + OrderChange $orderChange, + Closure $changeStoredStatusIfExpected, + Closure $findStoredStatus, + ): StatusChangeResult { + $connection = $this->connectionPool->getConnectionForTable(OrderChangeRepository::TABLE_NAME); + + return $connection->transactional( + function () use ($orderChange, $changeStoredStatusIfExpected, $findStoredStatus): StatusChangeResult { + $isChanged = $changeStoredStatusIfExpected( + $orderChange->oldValue, + $orderChange->newValue, + $orderChange->date + ); + + if (!$isChanged) { + $storedStatus = $findStoredStatus(); + + return $storedStatus === $orderChange->newValue + ? new StatusChangeResult(StatusChangeOutcome::Unchanged) + : new StatusChangeResult(StatusChangeOutcome::Stale, storedStatus: $storedStatus); + } + + return new StatusChangeResult( + StatusChangeOutcome::Changed, + $orderChange->withUid($this->orderChangeRepository->add($orderChange)) + ); + } + ); + } +} diff --git a/Classes/Event/Order/AfterShipmentStatusChangeEvent.php b/Classes/Event/Order/AfterShipmentStatusChangeEvent.php new file mode 100644 index 00000000..3d32e221 --- /dev/null +++ b/Classes/Event/Order/AfterShipmentStatusChangeEvent.php @@ -0,0 +1,67 @@ + + */ + private array $errors = []; + + public function __construct( + private readonly Shipment $shipment, + private readonly OrderChange $orderChange, + ) { + } + + public function addError(string $message): void + { + $this->errors[] = $message; + } + + /** + * @return list + */ + public function getErrors(): array + { + return $this->errors; + } + + public function getShipmentWithNewStatus(): Shipment + { + return $this->shipment; + } + + public function getOrderChange(): OrderChange + { + return $this->orderChange; + } + + public function getFromStatus(): string + { + return $this->orderChange->oldValue; + } + + public function getToStatus(): string + { + return $this->orderChange->newValue; + } +} diff --git a/Classes/Event/Order/BeforeShipmentStatusChangeEvent.php b/Classes/Event/Order/BeforeShipmentStatusChangeEvent.php new file mode 100644 index 00000000..887fdf69 --- /dev/null +++ b/Classes/Event/Order/BeforeShipmentStatusChangeEvent.php @@ -0,0 +1,89 @@ +shipment; + } + + public function getFromStatus(): string + { + return $this->fromStatus; + } + + public function getToStatus(): string + { + return $this->toStatus; + } + + public function getSource(): OrderChangeSource + { + return $this->source; + } + + public function getInitiator(): string + { + return $this->initiator; + } + + public function getBackendUserUid(): int + { + return $this->backendUserUid; + } + + public function veto(string $reason): void + { + $this->vetoed = true; + $this->vetoReason = $reason; + } + + public function isVetoed(): bool + { + return $this->vetoed; + } + + public function getVetoReason(): string + { + return $this->vetoReason; + } + + public function isPropagationStopped(): bool + { + return $this->vetoed; + } +} diff --git a/Classes/EventListener/Order/Create/PersistOrder/ShippingNotRequired.php b/Classes/EventListener/Order/Create/PersistOrder/ShippingNotRequired.php new file mode 100644 index 00000000..02b977d4 --- /dev/null +++ b/Classes/EventListener/Order/Create/PersistOrder/ShippingNotRequired.php @@ -0,0 +1,52 @@ +features->isFeatureEnabled(FulfillmentFeatureToggle::NAME)) { + return; + } + + $orderItem = $event->getOrderItem(); + $shipping = $orderItem->getShipping(); + if ($shipping === null) { + return; + } + + foreach ($orderItem->getProducts() as $orderProduct) { + if ($orderProduct->isShippable()) { + return; + } + } + + $shipping->setStatus(ShippingStatus::NOT_REQUIRED); + $this->shippingRepository->update($shipping); + $this->persistenceManager->persistAll(); + } +} diff --git a/Configuration/Services.php b/Configuration/Services.php index 1352e3aa..f141808a 100644 --- a/Configuration/Services.php +++ b/Configuration/Services.php @@ -4,6 +4,9 @@ namespace Extcode\Cart\Configuration; +use Extcode\Cart\Domain\Order\Fulfillment\OrderProductQuantityCalculator; +use Extcode\Cart\Domain\Order\Fulfillment\ShipmentCreationService; +use Extcode\Cart\Domain\Order\Fulfillment\ShipmentStatusChangeService; use Extcode\Cart\Domain\Order\History\OrderChangeRepository; use Extcode\Cart\Domain\Order\History\OrderHistoryService; use Extcode\Cart\Domain\Order\Status\Mail\StatusChangeMailRuleLoader; @@ -53,6 +56,10 @@ ->public() ; + $services->set(OrderProductQuantityCalculator::class)->public(); + $services->set(ShipmentCreationService::class)->public(); + $services->set(ShipmentStatusChangeService::class)->public(); + // @deprecated since cart 12.7, will be removed in cart 13.0 $deprecatedServiceIds = [ 'Extcode\\Cart\\OrderHistory\\OrderChangeRepository' => OrderChangeRepository::class, diff --git a/Configuration/Services/EventListeners.php b/Configuration/Services/EventListeners.php index f4ba6f0f..5a976ec4 100644 --- a/Configuration/Services/EventListeners.php +++ b/Configuration/Services/EventListeners.php @@ -25,6 +25,7 @@ use Extcode\Cart\EventListener\Order\Create\PersistOrder\Payment; use Extcode\Cart\EventListener\Order\Create\PersistOrder\Products; use Extcode\Cart\EventListener\Order\Create\PersistOrder\Shipping; +use Extcode\Cart\EventListener\Order\Create\PersistOrder\ShippingNotRequired; use Extcode\Cart\EventListener\Order\Create\PersistOrder\TaxClasses; use Extcode\Cart\EventListener\Order\Create\PersistOrder\Taxes; use Extcode\Cart\EventListener\Order\Export\FluidTemplate; @@ -204,6 +205,18 @@ ) ; + $services + ->set(ShippingNotRequired::class) + ->tag( + 'event.listener', + [ + 'event' => PersistOrderEvent::class, + 'identifier' => 'cart--order--create--persist-order--shipping-not-required', + 'after' => 'cart--order--create--persist-order--products,cart--order--create--persist-order--shipping', + ] + ) + ; + $services ->set(OrderNumber::class) ->tag( diff --git a/Documentation/Changelog/12.9/Feature-902-OrderShipments.rst b/Documentation/Changelog/12.9/Feature-902-OrderShipments.rst index 7a63b97d..d7e06929 100644 --- a/Documentation/Changelog/12.9/Feature-902-OrderShipments.rst +++ b/Documentation/Changelog/12.9/Feature-902-OrderShipments.rst @@ -36,8 +36,9 @@ New status (see :ref:`developer-order-status`): product is shippable). The new feature toggle ``cart.orderFulfillment`` is disabled by default. It -will enable the backend UI for shipments and the derived shipping status of -the order; for now it has no effect. +sets the shipping status ``not_required`` for orders without shippable +products, see :doc:`Feature-905-CreateShipmentsAndDeriveShippingStatus`, and +will enable the backend UI for shipments. Impact ====== diff --git a/Documentation/Changelog/12.9/Feature-905-CreateShipmentsAndDeriveShippingStatus.rst b/Documentation/Changelog/12.9/Feature-905-CreateShipmentsAndDeriveShippingStatus.rst new file mode 100644 index 00000000..c17f3aa2 --- /dev/null +++ b/Documentation/Changelog/12.9/Feature-905-CreateShipmentsAndDeriveShippingStatus.rst @@ -0,0 +1,66 @@ +.. include:: ../../Includes.rst.txt + +=================================================================== +Feature: #905 - Create shipments and derive the shipping status +=================================================================== + +See `Issue 905 `__ + +Description +=========== + +Shipments (see :doc:`Feature-902-OrderShipments`) are created and changed by +services in ``\Extcode\Cart\Domain\Order\Fulfillment``. There is no backend UI +yet, it follows in a later version. + +``ShipmentCreationService::create()`` stores a shipment with its products in +one database transaction. The order is locked while the quantities are +checked, so concurrent requests cannot ship more than ordered: + +* Only shippable products of the order with a count greater than 0 can be + added, otherwise an ``\InvalidArgumentException`` is thrown. +* The counts of all shipments which are not canceled must not exceed the + ordered count, otherwise nothing is stored and the outcome is + ``ShipmentCreationOutcome::QuantityExceeded``. +* The creation is written to the order history with the type + ``shipment_status``, the subject ``shipment:`` and the products and + counts as data. + +``ShipmentStatusChangeService::change()`` changes the status of a shipment +atomically like the ``StatusChangeService`` does for payment and shipping. A +shipment can only be canceled before it is shipped, a canceled shipment does +not change anymore (``StatusChangeOutcome::NotAllowed``). Listeners of the new +events ``\Extcode\Cart\Event\Order\BeforeShipmentStatusChangeEvent`` (with +veto) and ``\Extcode\Cart\Event\Order\AfterShipmentStatusChangeEvent`` react to +a change. + +``OrderProductQuantityCalculator::calculateForOrderItem()`` returns the +``OrderProductQuantities`` of an order: per ordered product the ordered count, +the count in shipments which are not canceled, the shipped count (shipments +with the status ``shipped`` or ``delivered``) and the count which is still +available for a shipment. + +After a shipment is created or its status is changed, the shipping status of +the order is derived from the shipments and changed via the +``StatusChangeService``, so it is written to the order history and the events +and status mails work like for a manual change: + +* ``partially_shipped``: some quantities are shipped, some are open. +* ``shipped``: all ordered quantities of shippable products are shipped. +* Nothing is shipped (anymore): ``open``, ``on_hold`` and ``in_process`` stay + as set manually; a derived ``partially_shipped`` or ``shipped`` falls back + to ``in_process``. + +With the feature toggle ``cart.orderFulfillment`` enabled, an order without +shippable products gets the shipping status ``not_required`` when it is +persisted. + +Impact +====== + +Without the feature toggle nothing changes for existing shops. + +``\Extcode\Cart\Domain\Order\Status\StatusChangeOutcome`` has the new case +``NotAllowed``. Code that matches all cases of the enum has to handle it. + +.. index:: PHP-API diff --git a/Documentation/Changelog/12.9/Index.rst b/Documentation/Changelog/12.9/Index.rst index 6b85e89a..2140534e 100644 --- a/Documentation/Changelog/12.9/Index.rst +++ b/Documentation/Changelog/12.9/Index.rst @@ -16,6 +16,7 @@ Features ~~~~~~~~ * :doc:`#902 - Shipments with lines ` +* :doc:`#905 - Create shipments and derive the shipping status ` .. toctree:: :hidden: diff --git a/Documentation/Developer/Events/Index.rst b/Documentation/Developer/Events/Index.rst index 5441f20f..3cde0ab6 100644 --- a/Documentation/Developer/Events/Index.rst +++ b/Documentation/Developer/Events/Index.rst @@ -200,6 +200,18 @@ events: the shipping status of an order was changed and written to the order history, e.g. to send an email. See :ref:`developer-order-status-events`. +.. confval:: \Extcode\Cart\Event\Order\BeforeShipmentStatusChangeEvent + + This event is triggered by the `ShipmentStatusChangeService` before the + status of a shipment is changed. Listeners can prevent the change with + `veto()`. + +.. confval:: \Extcode\Cart\Event\Order\AfterShipmentStatusChangeEvent + + This event is triggered by the `ShipmentStatusChangeService` after the + status of a shipment was changed and written to the order history, before + the shipping status of the order is derived from its shipments. + .. confval:: `Extcode\Cart\Event\Order\UpdateServiceEvent This event is triggered when the payment or shipping status of an order is diff --git a/Resources/Private/Language/locallang.xlf b/Resources/Private/Language/locallang.xlf index b5a09f82..0847c576 100644 --- a/Resources/Private/Language/locallang.xlf +++ b/Resources/Private/Language/locallang.xlf @@ -222,6 +222,12 @@ The shipping status "%s" is not available, nothing was changed. + + The payment status can not be changed to "%s", nothing was changed. + + + The shipping status can not be changed to "%s", nothing was changed. + Show @@ -623,6 +629,9 @@ Shipping status + + Shipment status + Backend diff --git a/Tests/Functional/Domain/Order/Fulfillment/Fixtures/OrderWithProducts.php b/Tests/Functional/Domain/Order/Fulfillment/Fixtures/OrderWithProducts.php new file mode 100644 index 00000000..3d168d0a --- /dev/null +++ b/Tests/Functional/Domain/Order/Fulfillment/Fixtures/OrderWithProducts.php @@ -0,0 +1,20 @@ + [ + ['uid' => 1, 'pid' => 105, 'order_number' => 'O-1', 'products' => 3, 'shipping' => 1], + ['uid' => 2, 'pid' => 105, 'order_number' => 'O-2', 'products' => 1, 'shipping' => 1], + ], + 'tx_cart_domain_model_order_shipping' => [ + ['uid' => 1, 'pid' => 105, 'item' => 1, 'name' => 'Standard', 'status' => 'open'], + ['uid' => 2, 'pid' => 105, 'item' => 2, 'name' => 'Standard', 'status' => 'open'], + ], + 'tx_cart_domain_model_order_product' => [ + ['uid' => 11, 'pid' => 105, 'item' => 1, 'sku' => 'book', 'count' => 3, 'shippable' => 1], + ['uid' => 12, 'pid' => 105, 'item' => 1, 'sku' => 'mug', 'count' => 1, 'shippable' => 1], + ['uid' => 13, 'pid' => 105, 'item' => 1, 'sku' => 'download', 'count' => 1, 'shippable' => 0], + ['uid' => 21, 'pid' => 105, 'item' => 2, 'sku' => 'book', 'count' => 1, 'shippable' => 1], + ], +]; diff --git a/Tests/Functional/Domain/Order/Fulfillment/OrderProductQuantityCalculatorTest.php b/Tests/Functional/Domain/Order/Fulfillment/OrderProductQuantityCalculatorTest.php new file mode 100644 index 00000000..b39fd12c --- /dev/null +++ b/Tests/Functional/Domain/Order/Fulfillment/OrderProductQuantityCalculatorTest.php @@ -0,0 +1,98 @@ +importPHPDataSet(__DIR__ . '/../../../../Fixtures/BaseDatabase.php'); + $this->importPHPDataSet(__DIR__ . '/Fixtures/OrderWithProducts.php'); + + $subject = $this->get(OrderProductQuantityCalculator::class); + self::assertInstanceOf(OrderProductQuantityCalculator::class, $subject); + $this->subject = $subject; + } + + #[Test] + public function calculateForOrderItemReturnsTheQuantitiesOfTheOrderedProductsFromTheShipments(): void + { + (new PhpDataSet())->import([ + 'tx_cart_domain_model_order_shipment' => [ + ['uid' => 1, 'pid' => 105, 'item' => 1, 'status' => ShipmentStatus::SHIPPED], + ['uid' => 2, 'pid' => 105, 'item' => 1, 'status' => ShipmentStatus::DELIVERED], + ['uid' => 3, 'pid' => 105, 'item' => 1, 'status' => ShipmentStatus::IN_PROCESS], + ['uid' => 4, 'pid' => 105, 'item' => 1, 'status' => ShipmentStatus::CANCELED], + ['uid' => 5, 'pid' => 105, 'item' => 1, 'status' => ShipmentStatus::SHIPPED, 'deleted' => 1], + ['uid' => 6, 'pid' => 105, 'item' => 2, 'status' => ShipmentStatus::SHIPPED], + ], + 'tx_cart_domain_model_order_shipment_product' => [ + ['uid' => 1, 'pid' => 105, 'shipment' => 1, 'order_product' => 11, 'count' => 1], + ['uid' => 2, 'pid' => 105, 'shipment' => 2, 'order_product' => 11, 'count' => 1], + ['uid' => 3, 'pid' => 105, 'shipment' => 3, 'order_product' => 12, 'count' => 1], + ['uid' => 4, 'pid' => 105, 'shipment' => 4, 'order_product' => 11, 'count' => 1], + ['uid' => 5, 'pid' => 105, 'shipment' => 5, 'order_product' => 11, 'count' => 1], + ['uid' => 6, 'pid' => 105, 'shipment' => 6, 'order_product' => 21, 'count' => 1], + ], + ]); + + $orderProductQuantities = iterator_to_array($this->subject->calculateForOrderItem(1)); + + self::assertSame([11, 12, 13], array_keys($orderProductQuantities)); + self::assertSame( + [ + 11 => [true, 3, 2, 2, 1], + 12 => [true, 1, 1, 0, 0], + 13 => [false, 1, 0, 0, 0], + ], + array_map( + static fn (OrderProductQuantity $orderProductQuantity): array => [ + $orderProductQuantity->isShippable, + $orderProductQuantity->orderedCount, + $orderProductQuantity->countInUncanceledShipments, + $orderProductQuantity->shippedCount, + $orderProductQuantity->getCountAvailableForShipment(), + ], + $orderProductQuantities + ) + ); + } + + #[Test] + public function calculateForOrderItemReturnsNothingForAnOrderWithoutProducts(): void + { + self::assertCount(0, $this->subject->calculateForOrderItem(99)); + } +} diff --git a/Tests/Functional/Domain/Order/Fulfillment/ShipmentCreationServiceTest.php b/Tests/Functional/Domain/Order/Fulfillment/ShipmentCreationServiceTest.php new file mode 100644 index 00000000..9f8ef119 --- /dev/null +++ b/Tests/Functional/Domain/Order/Fulfillment/ShipmentCreationServiceTest.php @@ -0,0 +1,343 @@ +importPHPDataSet(__DIR__ . '/../../../../Fixtures/BaseDatabase.php'); + $this->importPHPDataSet(__DIR__ . '/Fixtures/OrderWithProducts.php'); + + GeneralUtility::makeInstance(Context::class)->setAspect( + 'date', + new DateTimeAspect(new DateTimeImmutable(self::NOW)) + ); + + $subject = $this->get(ShipmentCreationService::class); + self::assertInstanceOf(ShipmentCreationService::class, $subject); + $this->subject = $subject; + } + + #[Test] + public function createStoresTheShipmentAndWritesItToTheOrderHistory(): void + { + $result = $this->subject->create( + new Shipment( + orderItemUid: 1, + status: ShipmentStatus::IN_PROCESS, + products: [ + new ShipmentProduct(orderProductUid: 11, count: 2), + new ShipmentProduct(orderProductUid: 12, count: 1), + ], + carrier: 'DHL', + ), + 'erp_sync', + source: OrderChangeSource::Api + ); + + self::assertSame(ShipmentCreationOutcome::Created, $result->outcome); + self::assertTrue($result->isCreated()); + self::assertNotNull($result->shipment); + self::assertGreaterThan(0, $result->shipment->uid); + self::assertSame('DHL', $result->shipment->carrier); + self::assertSame( + [[11, 2], [12, 1]], + array_map( + static fn (ShipmentProduct $shipmentProduct): array => [$shipmentProduct->orderProductUid, $shipmentProduct->count], + $result->shipment->products + ) + ); + self::assertSame( + [ + [ + 'item' => 1, + 'type' => OrderChangeType::SHIPMENT_STATUS, + 'subject' => 'shipment:' . $result->shipment->uid, + 'old_value' => '', + 'new_value' => ShipmentStatus::IN_PROCESS, + 'data' => '{"products":[{"orderProduct":11,"count":2},{"orderProduct":12,"count":1}]}', + 'crdate' => (new DateTimeImmutable(self::NOW))->getTimestamp(), + 'source' => 'api', + 'initiator' => 'erp_sync', + ], + ], + $this->fetchOrderChanges() + ); + self::assertNotNull($result->orderChange); + self::assertSame($this->fetchOrderChangeUids(), [$result->orderChange->uid]); + } + + #[Test] + public function createDoesNotChangeTheShippingStatusOfTheOrderAsLongAsNothingIsShipped(): void + { + $result = $this->subject->create(new Shipment( + orderItemUid: 1, + status: ShipmentStatus::OPEN, + products: [new ShipmentProduct(orderProductUid: 11, count: 3), new ShipmentProduct(orderProductUid: 12, count: 1)], + )); + + self::assertNull($result->shippingStatusChange); + self::assertSame(ShippingStatus::OPEN, $this->fetchShippingStatus(1)); + } + + #[Test] + public function createChangesTheShippingStatusOfTheOrderToPartiallyShipped(): void + { + $result = $this->subject->create(new Shipment( + orderItemUid: 1, + status: ShipmentStatus::SHIPPED, + products: [new ShipmentProduct(orderProductUid: 11, count: 1)], + )); + + self::assertSame(StatusChangeOutcome::Changed, $result->shippingStatusChange?->outcome); + self::assertSame(ShippingStatus::PARTIALLY_SHIPPED, $this->fetchShippingStatus(1)); + self::assertSame( + [ + [OrderChangeType::SHIPMENT_STATUS, '', ShipmentStatus::SHIPPED], + [OrderChangeType::SHIPPING_STATUS, ShippingStatus::OPEN, ShippingStatus::PARTIALLY_SHIPPED], + ], + array_map( + static fn (array $orderChange): array => [$orderChange['type'], $orderChange['old_value'], $orderChange['new_value']], + $this->fetchOrderChanges() + ) + ); + } + + #[Test] + public function createChangesTheShippingStatusOfTheOrderToShippedIfAllShippableProductsAreShipped(): void + { + $this->subject->create(new Shipment( + orderItemUid: 1, + status: ShipmentStatus::SHIPPED, + products: [new ShipmentProduct(orderProductUid: 11, count: 2)], + )); + $result = $this->subject->create(new Shipment( + orderItemUid: 1, + status: ShipmentStatus::DELIVERED, + products: [new ShipmentProduct(orderProductUid: 11, count: 1), new ShipmentProduct(orderProductUid: 12, count: 1)], + )); + + self::assertSame(StatusChangeOutcome::Changed, $result->shippingStatusChange?->outcome); + self::assertSame(ShippingStatus::SHIPPED, $this->fetchShippingStatus(1)); + } + + #[Test] + public function createStoresNothingIfACountExceedsTheCountAvailableForShipment(): void + { + $this->subject->create(new Shipment( + orderItemUid: 1, + status: ShipmentStatus::OPEN, + products: [new ShipmentProduct(orderProductUid: 11, count: 2)], + )); + $orderChangeUids = $this->fetchOrderChangeUids(); + + $result = $this->subject->create(new Shipment( + orderItemUid: 1, + status: ShipmentStatus::SHIPPED, + products: [new ShipmentProduct(orderProductUid: 11, count: 2), new ShipmentProduct(orderProductUid: 12, count: 1)], + )); + + self::assertSame(ShipmentCreationOutcome::QuantityExceeded, $result->outcome); + self::assertFalse($result->isCreated()); + self::assertSame([11], $result->exceededOrderProductUids); + self::assertNull($result->shipment); + self::assertCount(1, $this->fetchRows(self::ORDER_SHIPMENT_TABLE_NAME)); + self::assertCount(1, $this->fetchRows(self::ORDER_SHIPMENT_PRODUCT_TABLE_NAME)); + self::assertSame($orderChangeUids, $this->fetchOrderChangeUids()); + self::assertSame(ShippingStatus::OPEN, $this->fetchShippingStatus(1)); + } + + #[Test] + public function createSumsUpTheCountsOfAProductGivenTwice(): void + { + $result = $this->subject->create(new Shipment( + orderItemUid: 1, + status: ShipmentStatus::OPEN, + products: [new ShipmentProduct(orderProductUid: 12, count: 1), new ShipmentProduct(orderProductUid: 12, count: 1)], + )); + + self::assertSame([12], $result->exceededOrderProductUids); + } + + #[Test] + public function theCountOfACanceledShipmentIsAvailableForShipmentAgain(): void + { + (new PhpDataSet())->import([ + self::ORDER_SHIPMENT_TABLE_NAME => [ + ['uid' => 1, 'pid' => 105, 'item' => 1, 'status' => ShipmentStatus::CANCELED, 'products' => 1], + ], + self::ORDER_SHIPMENT_PRODUCT_TABLE_NAME => [ + ['uid' => 1, 'pid' => 105, 'shipment' => 1, 'order_product' => 11, 'count' => 3], + ], + ]); + + $result = $this->subject->create(new Shipment( + orderItemUid: 1, + status: ShipmentStatus::OPEN, + products: [new ShipmentProduct(orderProductUid: 11, count: 3)], + )); + + self::assertTrue($result->isCreated()); + } + + #[DataProvider('invalidShipmentDataProvider')] + #[Test] + public function createThrowsExceptionForAnInvalidShipment(Shipment $shipment, int $expectedExceptionCode): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionCode($expectedExceptionCode); + + try { + $this->subject->create($shipment); + } finally { + self::assertSame([], $this->fetchRows(self::ORDER_SHIPMENT_TABLE_NAME)); + self::assertSame([], $this->fetchOrderChangeUids()); + } + } + + /** + * @return iterable + */ + public static function invalidShipmentDataProvider(): iterable + { + $products = [new ShipmentProduct(orderProductUid: 11, count: 1)]; + + yield 'stored already' => [ + new Shipment(orderItemUid: 1, status: ShipmentStatus::OPEN, products: $products, uid: 5), + 1795600010, + ]; + yield 'canceled' => [ + new Shipment(orderItemUid: 1, status: ShipmentStatus::CANCELED, products: $products), + 1795600011, + ]; + yield 'unknown status' => [ + new Shipment(orderItemUid: 1, status: 'lost', products: $products), + 1795600011, + ]; + yield 'without products' => [ + new Shipment(orderItemUid: 1, status: ShipmentStatus::OPEN), + 1795600012, + ]; + yield 'count 0' => [ + new Shipment(orderItemUid: 1, status: ShipmentStatus::OPEN, products: [new ShipmentProduct(orderProductUid: 11, count: 0)]), + 1795600014, + ]; + yield 'product of another order' => [ + new Shipment(orderItemUid: 1, status: ShipmentStatus::OPEN, products: [new ShipmentProduct(orderProductUid: 21, count: 1)]), + 1795600015, + ]; + yield 'product which is not shippable' => [ + new Shipment(orderItemUid: 1, status: ShipmentStatus::OPEN, products: [new ShipmentProduct(orderProductUid: 13, count: 1)]), + 1795600016, + ]; + yield 'order which does not exist' => [ + new Shipment(orderItemUid: 99, status: ShipmentStatus::OPEN, products: $products), + 1795600002, + ]; + } + + private function fetchShippingStatus(int $shippingUid): mixed + { + $row = $this->getConnectionPool()->getConnectionForTable(self::ORDER_SHIPPING_TABLE_NAME) + ->select(['status'], self::ORDER_SHIPPING_TABLE_NAME, ['uid' => $shippingUid]) + ->fetchAssociative() + ; + + return is_array($row) ? $row['status'] : null; + } + + /** + * @return list + */ + private function fetchOrderChangeUids(): array + { + return array_map( + static fn (array $row): int => is_numeric($row['uid']) ? (int) $row['uid'] : 0, + $this->fetchRows(self::ORDER_CHANGE_TABLE_NAME, ['uid']) + ); + } + + /** + * @return list> + */ + private function fetchOrderChanges(): array + { + return $this->fetchRows( + self::ORDER_CHANGE_TABLE_NAME, + ['item', 'type', 'subject', 'old_value', 'new_value', 'data', 'crdate', 'source', 'initiator'] + ); + } + + /** + * @param list $columns + * + * @return list> + */ + private function fetchRows(string $table, array $columns = ['*']): array + { + return $this->getConnectionPool()->getConnectionForTable($table) + ->select($columns, $table, [], [], ['uid' => 'ASC']) + ->fetchAllAssociative() + ; + } +} diff --git a/Tests/Functional/Domain/Order/Fulfillment/ShipmentStatusChangeServiceTest.php b/Tests/Functional/Domain/Order/Fulfillment/ShipmentStatusChangeServiceTest.php new file mode 100644 index 00000000..3cec4308 --- /dev/null +++ b/Tests/Functional/Domain/Order/Fulfillment/ShipmentStatusChangeServiceTest.php @@ -0,0 +1,372 @@ +importPHPDataSet(__DIR__ . '/../../../../Fixtures/BaseDatabase.php'); + $this->importPHPDataSet(__DIR__ . '/Fixtures/OrderWithProducts.php'); + + GeneralUtility::makeInstance(Context::class)->setAspect( + 'date', + new DateTimeAspect(new DateTimeImmutable(self::NOW)) + ); + + $subject = $this->get(ShipmentStatusChangeService::class); + self::assertInstanceOf(ShipmentStatusChangeService::class, $subject); + $this->subject = $subject; + } + + #[Test] + public function changeChangesTheStatusAndWritesTheChangeToTheOrderHistory(): void + { + $shipment = $this->addShipment(ShipmentStatus::OPEN, 1); + + $result = $this->subject->change($shipment, ShipmentStatus::IN_PROCESS, ShipmentStatus::OPEN, 'erp_sync', source: OrderChangeSource::Api); + + self::assertTrue($result->isChanged()); + self::assertSame(StatusChangeOutcome::Changed, $result->shipmentStatusChange->outcome); + self::assertSame(ShipmentStatus::IN_PROCESS, $this->fetchShipmentStatus($shipment->uid)); + self::assertSame( + [ + [ + 'item' => 1, + 'type' => OrderChangeType::SHIPMENT_STATUS, + 'subject' => 'shipment:' . $shipment->uid, + 'old_value' => ShipmentStatus::OPEN, + 'new_value' => ShipmentStatus::IN_PROCESS, + 'crdate' => (new DateTimeImmutable(self::NOW))->getTimestamp(), + 'source' => 'api', + 'initiator' => 'erp_sync', + ], + ], + $this->fetchOrderChanges() + ); + self::assertNull($result->shippingStatusChange, 'Nothing is shipped, the shipping status of the order is kept.'); + self::assertSame(ShippingStatus::OPEN, $this->fetchShippingStatus(1)); + } + + #[Test] + public function shippingAShipmentChangesTheShippingStatusOfTheOrder(): void + { + $shipment = $this->addShipment(ShipmentStatus::IN_PROCESS, 1); + + $result = $this->subject->change($shipment, ShipmentStatus::SHIPPED, ShipmentStatus::IN_PROCESS); + + self::assertSame(StatusChangeOutcome::Changed, $result->shippingStatusChange?->outcome); + self::assertSame(ShippingStatus::PARTIALLY_SHIPPED, $this->fetchShippingStatus(1)); + self::assertSame( + [ + [OrderChangeType::SHIPMENT_STATUS, ShipmentStatus::IN_PROCESS, ShipmentStatus::SHIPPED], + [OrderChangeType::SHIPPING_STATUS, ShippingStatus::OPEN, ShippingStatus::PARTIALLY_SHIPPED], + ], + array_map( + static fn (array $orderChange): array => [$orderChange['type'], $orderChange['old_value'], $orderChange['new_value']], + $this->fetchOrderChanges() + ) + ); + } + + #[Test] + public function settingBackTheOnlyShippedShipmentChangesTheShippingStatusOfTheOrderToInProcess(): void + { + $shipment = $this->addShipment(ShipmentStatus::SHIPPED, 3); + $this->setShippingStatus(1, ShippingStatus::PARTIALLY_SHIPPED); + + $result = $this->subject->change($shipment, ShipmentStatus::IN_PROCESS, ShipmentStatus::SHIPPED); + + self::assertSame(StatusChangeOutcome::Changed, $result->shippingStatusChange?->outcome); + self::assertSame(ShippingStatus::IN_PROCESS, $this->fetchShippingStatus(1)); + } + + #[Test] + public function cancelingAShipmentBeforeItIsShippedFreesItsCount(): void + { + $shipment = $this->addShipment(ShipmentStatus::IN_PROCESS, 3); + + $result = $this->subject->change($shipment, ShipmentStatus::CANCELED, ShipmentStatus::IN_PROCESS); + + self::assertTrue($result->isChanged()); + self::assertSame(ShipmentStatus::CANCELED, $this->fetchShipmentStatus($shipment->uid)); + } + + #[DataProvider('notAllowedChangeDataProvider')] + #[Test] + public function changeDoesNothingForAChangeWhichIsNotAllowed(string $fromStatus, string $toStatus): void + { + $shipment = $this->addShipment($fromStatus, 1); + $events = $this->collectEvents(); + + $result = $this->subject->change($shipment, $toStatus, $fromStatus); + + self::assertSame(StatusChangeOutcome::NotAllowed, $result->shipmentStatusChange->outcome); + self::assertSame($fromStatus, $this->fetchShipmentStatus($shipment->uid)); + self::assertSame([], $this->fetchOrderChanges()); + self::assertSame([], $events->getArrayCopy()); + } + + /** + * @return iterable + */ + public static function notAllowedChangeDataProvider(): iterable + { + yield 'cancel a shipped shipment' => [ShipmentStatus::SHIPPED, ShipmentStatus::CANCELED]; + yield 'cancel a delivered shipment' => [ShipmentStatus::DELIVERED, ShipmentStatus::CANCELED]; + yield 'reopen a canceled shipment' => [ShipmentStatus::CANCELED, ShipmentStatus::OPEN]; + yield 'ship a canceled shipment' => [ShipmentStatus::CANCELED, ShipmentStatus::SHIPPED]; + } + + #[Test] + public function changeDoesNothingIfTheStatusIsNotRegistered(): void + { + $shipment = $this->addShipment(ShipmentStatus::OPEN, 1); + + $result = $this->subject->change($shipment, 'lost', ShipmentStatus::OPEN); + + self::assertSame(StatusChangeOutcome::UnknownStatus, $result->shipmentStatusChange->outcome); + self::assertSame(ShipmentStatus::OPEN, $this->fetchShipmentStatus($shipment->uid)); + } + + #[Test] + public function changeDoesNothingIfTheStatusIsNotChanged(): void + { + $shipment = $this->addShipment(ShipmentStatus::OPEN, 1); + + $result = $this->subject->change($shipment, ShipmentStatus::OPEN, ShipmentStatus::OPEN); + + self::assertSame(StatusChangeOutcome::Unchanged, $result->shipmentStatusChange->outcome); + self::assertSame([], $this->fetchOrderChanges()); + } + + #[Test] + public function changeDoesNothingIfTheShipmentHasNotTheExpectedStatusAnymore(): void + { + $shipment = $this->addShipment(ShipmentStatus::SHIPPED, 1); + + $result = $this->subject->change($shipment, ShipmentStatus::CANCELED, ShipmentStatus::OPEN); + + self::assertSame(StatusChangeOutcome::Stale, $result->shipmentStatusChange->outcome); + self::assertSame(ShipmentStatus::SHIPPED, $result->shipmentStatusChange->storedStatus); + self::assertSame(ShipmentStatus::SHIPPED, $this->fetchShipmentStatus($shipment->uid)); + self::assertSame([], $this->fetchOrderChanges()); + } + + #[Test] + public function changeThrowsExceptionForAShipmentWhichIsNotStored(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionCode(1795600020); + + $this->subject->change(new Shipment(orderItemUid: 1, status: ShipmentStatus::OPEN), ShipmentStatus::SHIPPED, ShipmentStatus::OPEN); + } + + #[Test] + public function changeDispatchesTheBeforeAndTheAfterEventWithTheShipment(): void + { + $shipment = $this->addShipment(ShipmentStatus::OPEN, 1); + $events = $this->collectEvents(); + + $this->subject->change($shipment, ShipmentStatus::IN_PROCESS, ShipmentStatus::OPEN, 'erp_sync', source: OrderChangeSource::Api); + + self::assertCount(2, $events); + [$beforeEvent, $afterEvent] = $events->getArrayCopy(); + self::assertInstanceOf(BeforeShipmentStatusChangeEvent::class, $beforeEvent); + self::assertSame($shipment, $beforeEvent->getShipmentWithStoredStatus()); + self::assertSame(ShipmentStatus::OPEN, $beforeEvent->getFromStatus()); + self::assertSame(ShipmentStatus::IN_PROCESS, $beforeEvent->getToStatus()); + self::assertSame(OrderChangeSource::Api, $beforeEvent->getSource()); + self::assertSame('erp_sync', $beforeEvent->getInitiator()); + self::assertSame(0, $beforeEvent->getBackendUserUid()); + self::assertInstanceOf(AfterShipmentStatusChangeEvent::class, $afterEvent); + self::assertSame(ShipmentStatus::IN_PROCESS, $afterEvent->getShipmentWithNewStatus()->status, 'The shipment has the new status already.'); + self::assertSame($shipment->products, $afterEvent->getShipmentWithNewStatus()->products); + self::assertSame(ShipmentStatus::OPEN, $afterEvent->getFromStatus()); + self::assertSame(ShipmentStatus::IN_PROCESS, $afterEvent->getToStatus()); + self::assertSame('shipment:' . $shipment->uid, $afterEvent->getOrderChange()->subject); + } + + #[Test] + public function aVetoOfABeforeEventListenerPreventsTheChange(): void + { + $shipment = $this->addShipment(ShipmentStatus::IN_PROCESS, 1); + $this->addEventListener( + BeforeShipmentStatusChangeEvent::class, + static function (BeforeShipmentStatusChangeEvent $event): void { + $event->veto('The parcel is still in the warehouse.'); + } + ); + + $result = $this->subject->change($shipment, ShipmentStatus::SHIPPED, ShipmentStatus::IN_PROCESS); + + self::assertSame(StatusChangeOutcome::Vetoed, $result->shipmentStatusChange->outcome); + self::assertSame('The parcel is still in the warehouse.', $result->shipmentStatusChange->vetoReason); + self::assertSame(ShipmentStatus::IN_PROCESS, $this->fetchShipmentStatus($shipment->uid)); + self::assertSame(ShippingStatus::OPEN, $this->fetchShippingStatus(1)); + self::assertSame([], $this->fetchOrderChanges()); + } + + #[Test] + public function errorsOfAfterEventListenersAreReturnedAndTheStatusIsChangedAnyway(): void + { + $shipment = $this->addShipment(ShipmentStatus::IN_PROCESS, 1); + $this->addEventListener( + AfterShipmentStatusChangeEvent::class, + static function (AfterShipmentStatusChangeEvent $event): void { + $event->addError('The shipping confirmation could not be sent.'); + } + ); + + $result = $this->subject->change($shipment, ShipmentStatus::SHIPPED, ShipmentStatus::IN_PROCESS); + + self::assertTrue($result->isChanged()); + self::assertSame(['The shipping confirmation could not be sent.'], $result->shipmentStatusChange->errors); + self::assertSame(ShipmentStatus::SHIPPED, $this->fetchShipmentStatus($shipment->uid)); + self::assertSame(ShippingStatus::PARTIALLY_SHIPPED, $this->fetchShippingStatus(1)); + } + + private function addShipment(string $status, int $countOfFirstProduct): Shipment + { + $shipmentRepository = new ShipmentRepository($this->getConnectionPool(), GeneralUtility::makeInstance(Context::class)); + + $shipmentUid = $shipmentRepository->add(new Shipment( + orderItemUid: 1, + status: $status, + products: [new ShipmentProduct(orderProductUid: 11, count: $countOfFirstProduct)], + )); + $shipment = $shipmentRepository->findByUid($shipmentUid); + self::assertInstanceOf(Shipment::class, $shipment); + + return $shipment; + } + + /** + * @return ArrayObject + */ + private function collectEvents(): ArrayObject + { + $events = new ArrayObject(); + $listener = static function (object $event) use ($events): void { + $events->append($event); + }; + $this->addEventListener(BeforeShipmentStatusChangeEvent::class, $listener, 'before'); + $this->addEventListener(AfterShipmentStatusChangeEvent::class, $listener, 'after'); + + return $events; + } + + private function addEventListener(string $eventClass, Closure $listener, string $name = 'listener'): void + { + $container = $this->getContainer(); + assert($container instanceof Container); + + $identifier = 'cart-test--event-listener--' . $name . '--' . md5($eventClass); + $container->set($identifier, $listener); + GeneralUtility::makeInstance(ListenerProvider::class)->addListener($eventClass, $identifier); + } + + private function fetchShipmentStatus(int $shipmentUid): mixed + { + return $this->fetchStatus(self::ORDER_SHIPMENT_TABLE_NAME, $shipmentUid); + } + + private function fetchShippingStatus(int $shippingUid): mixed + { + return $this->fetchStatus(self::ORDER_SHIPPING_TABLE_NAME, $shippingUid); + } + + private function setShippingStatus(int $shippingUid, string $status): void + { + $this->getConnectionPool()->getConnectionForTable(self::ORDER_SHIPPING_TABLE_NAME) + ->update(self::ORDER_SHIPPING_TABLE_NAME, ['status' => $status], ['uid' => $shippingUid]) + ; + } + + private function fetchStatus(string $table, int $uid): mixed + { + $row = $this->getConnectionPool()->getConnectionForTable($table) + ->select(['status'], $table, ['uid' => $uid]) + ->fetchAssociative() + ; + + return is_array($row) ? $row['status'] : null; + } + + /** + * @return list> + */ + private function fetchOrderChanges(): array + { + return $this->getConnectionPool()->getConnectionForTable(self::ORDER_CHANGE_TABLE_NAME) + ->select( + ['item', 'type', 'subject', 'old_value', 'new_value', 'crdate', 'source', 'initiator'], + self::ORDER_CHANGE_TABLE_NAME, + [], + [], + ['uid' => 'ASC'] + ) + ->fetchAllAssociative() + ; + } +} diff --git a/Tests/Functional/EventListener/Order/Create/PersistOrder/Fixtures/OrderItemWithShipping.php b/Tests/Functional/EventListener/Order/Create/PersistOrder/Fixtures/OrderItemWithShipping.php new file mode 100644 index 00000000..b786dc1d --- /dev/null +++ b/Tests/Functional/EventListener/Order/Create/PersistOrder/Fixtures/OrderItemWithShipping.php @@ -0,0 +1,16 @@ + [ + ['uid' => 1, 'pid' => 105, 'currency' => '€', 'products' => 2, 'shipping' => 1], + ], + 'tx_cart_domain_model_order_shipping' => [ + ['uid' => 1, 'pid' => 105, 'item' => 1, 'name' => 'Standard', 'status' => 'open'], + ], + 'tx_cart_domain_model_order_product' => [ + ['uid' => 1, 'pid' => 105, 'item' => 1, 'sku' => 'ticket', 'count' => 2, 'shippable' => 0], + ['uid' => 2, 'pid' => 105, 'item' => 1, 'sku' => 'download', 'count' => 1, 'shippable' => 0], + ], +]; diff --git a/Tests/Functional/EventListener/Order/Create/PersistOrder/ShippingNotRequiredTest.php b/Tests/Functional/EventListener/Order/Create/PersistOrder/ShippingNotRequiredTest.php new file mode 100644 index 00000000..62cf8386 --- /dev/null +++ b/Tests/Functional/EventListener/Order/Create/PersistOrder/ShippingNotRequiredTest.php @@ -0,0 +1,108 @@ + [ + 'features' => [ + FulfillmentFeatureToggle::NAME => true, + ], + ], + ]; + + protected function setUp(): void + { + parent::setUp(); + + $this->importPHPDataSet(__DIR__ . '/../../../../../Fixtures/BaseDatabase.php'); + $this->importPHPDataSet(__DIR__ . '/Fixtures/OrderItemWithShipping.php'); + } + + #[Test] + public function theShippingOfAnOrderWithoutShippableProductsIsNotRequired(): void + { + $this->persistOrder(); + + self::assertSame(ShippingStatus::NOT_REQUIRED, $this->fetchShippingStatus()); + } + + #[Test] + public function theShippingStatusOfAnOrderWithAShippableProductIsKept(): void + { + $this->getConnectionPool()->getConnectionForTable(self::ORDER_PRODUCT_TABLE_NAME) + ->update(self::ORDER_PRODUCT_TABLE_NAME, ['shippable' => 1], ['uid' => 2]) + ; + + $this->persistOrder(); + + self::assertSame(ShippingStatus::OPEN, $this->fetchShippingStatus()); + } + + #[Test] + public function theShippingStatusIsKeptWithoutTheFeatureToggle(): void + { + $configuration = $GLOBALS['TYPO3_CONF_VARS']; + self::assertIsArray($configuration); + $GLOBALS['TYPO3_CONF_VARS'] = ArrayUtility::setValueByPath($configuration, ['SYS', 'features', FulfillmentFeatureToggle::NAME], false); + + $this->persistOrder(); + + self::assertSame(ShippingStatus::OPEN, $this->fetchShippingStatus()); + } + + private function persistOrder(): void + { + $orderItem = GeneralUtility::makeInstance(PersistenceManager::class)->getObjectByIdentifier(1, Item::class); + self::assertInstanceOf(Item::class, $orderItem); + + $subject = $this->get(ShippingNotRequired::class); + self::assertInstanceOf(ShippingNotRequired::class, $subject); + $subject(new PersistOrderEvent(new Cart([]), $orderItem, ['settings' => ['order' => ['pid' => 105]]])); + } + + private function fetchShippingStatus(): mixed + { + $row = $this->getConnectionPool()->getConnectionForTable(self::ORDER_SHIPPING_TABLE_NAME) + ->select(['status'], self::ORDER_SHIPPING_TABLE_NAME, ['uid' => 1]) + ->fetchAssociative() + ; + + return is_array($row) ? $row['status'] : null; + } +} diff --git a/Tests/Unit/Domain/Order/Fulfillment/ShippingStatusDerivationTest.php b/Tests/Unit/Domain/Order/Fulfillment/ShippingStatusDerivationTest.php new file mode 100644 index 00000000..df9737f3 --- /dev/null +++ b/Tests/Unit/Domain/Order/Fulfillment/ShippingStatusDerivationTest.php @@ -0,0 +1,119 @@ + $orderProductQuantities + */ + #[DataProvider('derivationDataProvider')] + #[Test] + public function deriveReturnsTheStatusDerivedFromTheOrderProductQuantities(string $storedStatus, array $orderProductQuantities, string $expectedStatus): void + { + self::assertSame($expectedStatus, ShippingStatusDerivation::derive($storedStatus, new OrderProductQuantities(...$orderProductQuantities))); + } + + /** + * @return iterable, string}> + */ + public static function derivationDataProvider(): iterable + { + yield 'no products' => [ + ShippingStatus::OPEN, + [], + ShippingStatus::NOT_REQUIRED, + ]; + yield 'no shippable product' => [ + ShippingStatus::OPEN, + [self::orderProductQuantity(1, 1, isShippable: false)], + ShippingStatus::NOT_REQUIRED, + ]; + foreach ([ShippingStatus::OPEN, ShippingStatus::ON_HOLD, ShippingStatus::IN_PROCESS] as $manualStatus) { + yield 'nothing shipped keeps ' . $manualStatus => [ + $manualStatus, + [self::orderProductQuantity(2, 2, countInUncanceledShipments: 2)], + $manualStatus, + ]; + } + yield 'nothing shipped anymore falls back from partially shipped to in process' => [ + ShippingStatus::PARTIALLY_SHIPPED, + [self::orderProductQuantity(3, 2)], + ShippingStatus::IN_PROCESS, + ]; + yield 'nothing shipped anymore falls back from shipped to in process' => [ + ShippingStatus::SHIPPED, + [self::orderProductQuantity(4, 2, countInUncanceledShipments: 2)], + ShippingStatus::IN_PROCESS, + ]; + yield 'nothing shipped keeps not required of an order with shippable products' => [ + ShippingStatus::NOT_REQUIRED, + [self::orderProductQuantity(5, 2)], + ShippingStatus::NOT_REQUIRED, + ]; + yield 'some count of a product shipped' => [ + ShippingStatus::IN_PROCESS, + [self::orderProductQuantity(6, 3, countInUncanceledShipments: 1, shippedCount: 1)], + ShippingStatus::PARTIALLY_SHIPPED, + ]; + yield 'one of two products shipped' => [ + ShippingStatus::OPEN, + [self::orderProductQuantity(7, 1, countInUncanceledShipments: 1, shippedCount: 1), self::orderProductQuantity(8, 1)], + ShippingStatus::PARTIALLY_SHIPPED, + ]; + yield 'everything shipped' => [ + ShippingStatus::PARTIALLY_SHIPPED, + [self::orderProductQuantity(9, 2, countInUncanceledShipments: 2, shippedCount: 2), self::orderProductQuantity(10, 1, countInUncanceledShipments: 1, shippedCount: 1)], + ShippingStatus::SHIPPED, + ]; + yield 'everything shippable shipped, a product which is not shippable does not count' => [ + ShippingStatus::OPEN, + [self::orderProductQuantity(11, 1, countInUncanceledShipments: 1, shippedCount: 1), self::orderProductQuantity(12, 1, isShippable: false)], + ShippingStatus::SHIPPED, + ]; + yield 'a replacement exceeds the ordered count' => [ + ShippingStatus::SHIPPED, + [self::orderProductQuantity(13, 1, countInUncanceledShipments: 2, shippedCount: 2)], + ShippingStatus::SHIPPED, + ]; + } + + #[Test] + public function theCountAvailableForShipmentIsTheOrderedCountWithoutTheCountInUncanceledShipments(): void + { + self::assertSame(2, self::orderProductQuantity(14, 3, countInUncanceledShipments: 1)->getCountAvailableForShipment()); + self::assertSame(0, self::orderProductQuantity(15, 1, countInUncanceledShipments: 2)->getCountAvailableForShipment()); + self::assertSame(0, self::orderProductQuantity(16, 3, isShippable: false)->getCountAvailableForShipment()); + } + + private static function orderProductQuantity( + int $orderProductUid, + int $orderedCount, + bool $isShippable = true, + int $countInUncanceledShipments = 0, + int $shippedCount = 0 + ): OrderProductQuantity { + return new OrderProductQuantity($orderProductUid, $isShippable, $orderedCount, $countInUncanceledShipments, $shippedCount); + } +}