<?php
declare(strict_types=1);
namespace Wbfk\MultipleTransactions\Subscriber;
use Shopware\Core\Checkout\Cart\Price\CashRounding;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionCollection;
use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStates;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Pricing\CashRoundingConfig;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Wbfk\MultipleTransactions\Core\Checkout\Order\TransactionsSummary;
class OrderLoadedSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly CashRounding $cashRounding)
{
}
public static function getSubscribedEvents(): array
{
return [
'order.loaded' => 'calculateTransactionsSummary',
];
}
public function calculateTransactionsSummary(EntityLoadedEvent $event): void
{
$orders = $event->getEntities();
foreach ($orders as $order) {
$this->addTransactionsSummaryAsExtension($order);
}
}
private function addTransactionsSummaryAsExtension(OrderEntity $order): void
{
$alreadyPaid = 0.0;
if (!$order->getTransactions()) {
return;
}
foreach ($order->getTransactions() as $transaction) {
if ($transaction->getStateMachineState()->getTechnicalName() !== OrderTransactionStates::STATE_PAID) {
continue;
}
$alreadyPaid += $transaction->getAmount()->getTotalPrice();
}
$balance = $order->getAmountTotal() - $alreadyPaid;
$cashRoundingConfig = new CashRoundingConfig(2, 0.01, true);
$alreadyPaid = $this->cashRounding->cashRound($alreadyPaid, $cashRoundingConfig);
$balance = $this->cashRounding->cashRound($balance, $cashRoundingConfig);
$transactionsSummary = new TransactionsSummary();
$transactionsSummary->alreadyPaid = $alreadyPaid;
$transactionsSummary->balance = $balance;
$transactionsSummary->transactions = $order->getTransactions();
$order->addExtension('transactionsSummary', $transactionsSummary);
}
}