Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Classes/Controller/Backend/Order/AbstractStatusController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
82 changes: 82 additions & 0 deletions Classes/Domain/Order/Fulfillment/OrderItemLock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

declare(strict_types=1);

namespace Extcode\Cart\Domain\Order\Fulfillment;

/*
* This file is part of the package extcode/cart.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/

use Doctrine\DBAL\Platforms\SQLitePlatform;
use InvalidArgumentException;
use LogicException;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;

/**
* Concurrent requests check and write the quantities of an order one after
* the other, so they can not ship more than ordered.
*
* @internal
*/
final readonly class OrderItemLock
{
private const ORDER_ITEM_TABLE_NAME = 'tx_cart_domain_model_order_item';

public function __construct(
private ConnectionPool $connectionPool,
) {
}

/**
* @throws InvalidArgumentException
* @throws LogicException
*/
public function lock(int $orderItemUid): void
{
$connection = $this->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);
}
}
93 changes: 93 additions & 0 deletions Classes/Domain/Order/Fulfillment/OrderProductQuantities.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

declare(strict_types=1);

namespace Extcode\Cart\Domain\Order\Fulfillment;

/*
* This file is part of the package extcode/cart.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/

use ArrayIterator;
use Countable;
use IteratorAggregate;

/**
* @implements IteratorAggregate<int, OrderProductQuantity>
*/
final readonly class OrderProductQuantities implements Countable, IteratorAggregate
{
/**
* @var array<int, OrderProductQuantity>
*/
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<int, OrderProductQuantity>
*/
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->quantitiesByOrderProductUid);
}

public function count(): int
{
return count($this->quantitiesByOrderProductUid);
}

/**
* @return list<OrderProductQuantity>
*/
private function getShippableQuantities(): array
{
return array_values(array_filter(
$this->quantitiesByOrderProductUid,
static fn (OrderProductQuantity $orderProductQuantity): bool => $orderProductQuantity->isShippable
&& $orderProductQuantity->orderedCount > 0
));
}
}
38 changes: 38 additions & 0 deletions Classes/Domain/Order/Fulfillment/OrderProductQuantity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Extcode\Cart\Domain\Order\Fulfillment;

/*
* This file is part of the package extcode/cart.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/

final readonly class OrderProductQuantity
{
public function __construct(
public int $orderProductUid,
public bool $isShippable,
public int $orderedCount,
public int $countInUncanceledShipments = 0,
public int $shippedCount = 0,
) {
}

public function getCountAvailableForShipment(): int
{
if (!$this->isShippable) {
return 0;
}

return max(0, $this->orderedCount - $this->countInUncanceledShipments);
}

public function isCompletelyShipped(): bool
{
return $this->shippedCount >= $this->orderedCount;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

declare(strict_types=1);

namespace Extcode\Cart\Domain\Order\Fulfillment;

/*
* This file is part of the package extcode/cart.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/

use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;

final readonly class OrderProductQuantityCalculator
{
private const ORDER_PRODUCT_TABLE_NAME = 'tx_cart_domain_model_order_product';

private const SHIPPED_STATUSES = [
ShipmentStatus::SHIPPED,
ShipmentStatus::DELIVERED,
];

public function __construct(
private ConnectionPool $connectionPool,
private ShipmentRepository $shipmentRepository,
) {
}

public function calculateForOrderItem(int $orderItemUid): OrderProductQuantities
{
$countInUncanceledShipmentsByOrderProductUid = [];
$shippedCountByOrderProductUid = [];
foreach ($this->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<array<string, mixed>>
*/
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;
}
}
67 changes: 67 additions & 0 deletions Classes/Domain/Order/Fulfillment/OrderShippingStatusUpdater.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

declare(strict_types=1);

namespace Extcode\Cart\Domain\Order\Fulfillment;

/*
* This file is part of the package extcode/cart.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/

use Extcode\Cart\Domain\Model\Order\Item;
use Extcode\Cart\Domain\Order\History\OrderChangeSource;
use Extcode\Cart\Domain\Order\Status\StatusChangeOutcome;
use Extcode\Cart\Domain\Order\Status\StatusChangeResult;
use Extcode\Cart\Domain\Order\Status\StatusChangeService;
use Extcode\Cart\Domain\Repository\Order\ItemRepository;
use Psr\Http\Message\ServerRequestInterface;

/**
* The derived status is changed via the StatusChangeService, so the order
* history, the events and the status mails work like for a manual change.
*/
final readonly class OrderShippingStatusUpdater
{
public function __construct(
private ItemRepository $itemRepository,
private OrderProductQuantityCalculator $orderProductQuantityCalculator,
private StatusChangeService $statusChangeService,
) {
}

public function changeToDerivedStatus(
int $orderItemUid,
string $initiator = '',
?ServerRequestInterface $request = null,
?OrderChangeSource $source = null
): ?StatusChangeResult {
$orderItem = $this->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);
}
}
Loading
Loading