<?php
declare(strict_types=1);
/**
* WBFK
* Copyright © 2023 WBFK - Anselm Ruby
*
* @copyright Copyright (c) 2022, 2023 WBFK - Anselm Ruby (http://www.wbfk.at)
* @author Anselm Ruby <anselm.ruby@wbfk.at>
*/
namespace Wbfk\Offer\Subscriber;
use Shopware\Core\Checkout\Cart\Price\GrossPriceCalculator;
use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice;
use Shopware\Core\Checkout\Cart\Price\Struct\CartPrice;
use Shopware\Core\Checkout\Cart\Price\Struct\PriceCollection;
use Shopware\Core\Checkout\Cart\Price\Struct\QuantityPriceDefinition;
use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRule;
use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRuleCollection;
use Shopware\Core\Framework\Api\Context\AdminApiSource;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Pricing\CashRoundingConfig;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Wbfk\Offer\Core\Entity\Offer\Aggregate\OfferDocument\OfferDocumentComputedData;
use Wbfk\Offer\Core\Entity\Offer\Aggregate\OfferDocument\OfferDocumentEntity;
use Wbfk\Offer\Core\Entity\Offer\Aggregate\OfferItem\OfferItemCollection;
use Wbfk\Offer\Core\Entity\Offer\Aggregate\OfferItem\OfferItemComputedData;
use Wbfk\Offer\Core\Entity\Offer\Aggregate\OfferItem\OfferItemEntity;
use Wbfk\Offer\Core\Entity\Offer\OfferComputedData;
use Wbfk\Offer\Core\Entity\Offer\OfferEntity;
use Wbfk\Offer\Service\OfferDataComputer;
class OfferLoadedSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly OfferDataComputer $offerDataComputer,
) {
}
public static function getSubscribedEvents(): array
{
return [
'wbfk_offer.loaded' => [
['offerLoaded'],
],
];
}
public function offerLoaded(EntityLoadedEvent $event): void
{
$offers = $event->getEntities();
$isSourceAdmin = $event->getContext()->getSource() instanceof AdminApiSource;
foreach ($offers as $offer) {
if (!($offer instanceof OfferEntity) || !$offer->getItems()) {
continue;
}
// Get the last user generated configuration for this offer
$lastConfiguration = $offer->getDocuments()?->getLatestUserGenerated();
// Calculate offer data with the latest configuration
$offerComputedDate = $this->offerDataComputer->computeOfferData($offer, $event->getContext(), $lastConfiguration);
$offer->setComputed($offerComputedDate);
if (!$isSourceAdmin) {
continue;
}
// Calculate price of all configurations/documents if the context source is admin API
/** @var OfferDocumentEntity $document */
foreach ($configurations ?? [] as $document) {
// Calculate price of all configurations/documents
$document->setComputed($this->offerDataComputer->calculateOfferDocumentPrice($offerComputedDate->nestedItems, $document));
}
}
}
}