getDeliveries example

public function getConfig(): RuleConfig
    {
        return (new RuleConfig())
            ->operatorSet(RuleConfig::OPERATOR_SET_NUMBER)
            ->numberField('volume', ['unit' => RuleConfig::UNIT_VOLUME]);
    }

    private function calculateCartVolume(Cart $cart): float
    {
        $volume = 0.0;

        foreach ($cart->getDeliveries() as $delivery) {
            if ($delivery instanceof Delivery) {
                $volume += $delivery->getPositions()->getVolume();
            }
        }

        return $volume;
    }
}
'operator' => RuleConstraints::uuidOperators(false),
            'stateIds' => RuleConstraints::uuids(),
        ];
    }

    public function match(RuleScope $scope): bool
    {
        if (!$scope instanceof FlowRuleScope) {
            return false;
        }

        if (!$deliveries = $scope->getOrder()->getDeliveries()) {
            return false;
        }

        $deliveryStateIds = [];
        foreach ($deliveries->getElements() as $delivery) {
            $deliveryStateIds[] = $delivery->getStateId();
        }

        return RuleComparison::uuids($deliveryStateIds$this->stateIds, $this->operator);
    }

    

    public function __construct(
        private readonly AmountCalculator $amountCalculator,
        private readonly CashRounding $rounding
    ) {
    }

    public function adjust(Cart $cart, TaxProviderResult $result, SalesChannelContext $context): void
    {
        $lineItems = $cart->getLineItems();
        $deliveries = $cart->getDeliveries();

        $this->applyLineItemTaxes($lineItems$result->getLineItemTaxes());
        $this->applyDeliveryTaxes($deliveries$result->getDeliveryTaxes());

        $price = $this->amountCalculator->calculate(
            $cart->getLineItems()->getPrices(),
            $cart->getDeliveries()->getShippingCosts(),
            $context
        );

        // either take the price from the tax provider result or take the calculated taxes

                    ]);

                    if ($operation->isStatic()) {
                        $doc = new RenderedDocument('', $number$config->buildName()$operation->getFileType()$config->jsonSerialize());
                        $result->addSuccess($orderId$doc);

                        continue;
                    }

                    $deliveries = null;
                    if ($order->getDeliveries()) {
                        $deliveries = $order->getDeliveries()->first();
                    }

                    /** @var LocaleEntity $locale */
                    $locale = $order->getLanguage()->getLocale();

                    $html = $this->documentTemplateRenderer->render(
                        $template,
                        [
                            'order' => $order,
                            'orderDelivery' => $deliveries,
                            
static::assertSame($orderCustomer->getEmail()$order->getOrderCustomer()->getEmail());

        static::assertInstanceOf(OrderAddressEntity::class$billingAddress = $serialized['billingAddress']);
        static::assertSame($billingAddress->getZipcode()$order->getBillingAddress()->getZipcode());
        static::assertSame($billingAddress->getStreet()$order->getBillingAddress()->getStreet());
        static::assertSame($billingAddress->getCity()$order->getBillingAddress()->getCity());
        static::assertSame($billingAddress->getCompany()$order->getBillingAddress()->getCompany());
        static::assertSame($billingAddress->getDepartment()$order->getBillingAddress()->getDepartment());
        static::assertSame($billingAddress->getCountryId()$order->getBillingAddress()->getCountryId());
        static::assertSame($billingAddress->getCountryStateId()$order->getBillingAddress()->getCountryStateId());

        static::assertNotNull($deliveries = $order->getDeliveries());
        static::assertNotNull($delivery = $deliveries->first());
        $shippingAddress = $delivery->getShippingOrderAddress();

        static::assertNotNull($shippingAddress);

        static::assertNotEmpty($serialized['deliveries']);
        static::assertNotEmpty($serialized['deliveries']['shippingOrderAddress']);
        static::assertSame($serialized['deliveries']['trackingCodes']implode('|', $delivery->getTrackingCodes()));
        static::assertSame($serialized['deliveries']['shippingOrderAddress']['street']$shippingAddress->getStreet());
        static::assertSame($serialized['deliveries']['shippingOrderAddress']['zipcode']$shippingAddress->getZipcode());
        static::assertSame($serialized['deliveries']['shippingOrderAddress']['city']$shippingAddress->getCity());
        
// create product and add to cart         $cart = $this->addProduct($productId, 2, $cart$this->cartService, $this->context);

        static::assertEquals(100, $cart->getShippingCosts()->getTotalPrice(), 'Delivery costs should be 100 in the beginning');

        // create promotion and add to cart         $cart = $this->addPromotionCode($code$cart$this->cartService, $this->context);

        static::assertEquals(90, $cart->getShippingCosts()->getTotalPrice());

        static::assertEquals(2, $cart->getDeliveries()->count());
    }

    /** * This test verifies that our percentage promotions are correctly added. * We add a product and also an percentage promotion. * Our final delivery price should then be as expected. * * @group promotions * * @throws CartException */
    
use Shopware\Core\Checkout\Cart\CartValidatorInterface;
use Shopware\Core\Checkout\Cart\Error\ErrorCollection;
use Shopware\Core\Checkout\Shipping\Cart\Error\ShippingMethodBlockedError;
use Shopware\Core\Framework\Log\Package;
use Shopware\Core\System\SalesChannel\SalesChannelContext;

#[Package('checkout')] class DeliveryValidator implements CartValidatorInterface
{
    public function validate(Cart $cart, ErrorCollection $errors, SalesChannelContext $context): void
    {
        foreach ($cart->getDeliveries() as $delivery) {
            $matches = \in_array($delivery->getShippingMethod()->getAvailabilityRuleId()$context->getRuleIds(), true);

            if ($matches && $delivery->getShippingMethod()->getActive()) {
                continue;
            }

            $errors->add(
                new ShippingMethodBlockedError(
                    (string) $delivery->getShippingMethod()->getTranslation('name')
                )
            );
        }
$processor = new TaxProviderProcessor(
            $repo,
            static::createMock(LoggerInterface::class),
            $this->adjustment,
            $taxProviderRegistry,
            static::createMock(TaxProviderPayloadService::class)
        );

        $processor->process($cart$salesChannelContext);

        $lineItem = $cart->getLineItems()->get($this->ids->get('line-item-1'));
        $delivery = $cart->getDeliveries()->first();

        static::assertInstanceOf(LineItem::class$lineItem);
        static::assertInstanceOf(Delivery::class$delivery);

        $lineItemPrice = $lineItem->getPrice();

        static::assertNotNull($lineItemPrice);

        $lineItemTaxes = $lineItemPrice->getCalculatedTaxes()->getElements();
        $deliveryTaxes = $delivery->getShippingCosts()->getCalculatedTaxes()->getElements();

        


    public function collect(CartDataCollection $data, Cart $original, SalesChannelContext $context, CartBehavior $behavior): void
    {
        Profiler::trace('cart::delivery::collect', function D) use ($data$original$context): void {
            $default = $context->getShippingMethod()->getId();

            if (!$data->has(self::buildKey($default))) {
                $ids = [$default];
            }

            foreach ($original->getDeliveries() as $delivery) {
                $id = $delivery->getShippingMethod()->getId();

                if (!$data->has(self::buildKey($id))) {
                    $ids[] = $id;
                }
            }

            if (empty($ids)) {
                return;
            }

            


    public function cleanupCart(Cart $cart): void
    {
        $customFieldAllowList = $this->connection->fetchFirstColumn('SELECT `name` FROM `custom_field` WHERE `allow_cart_expose` = 1;');

        $event = new CartBeforeSerializationEvent($cart$customFieldAllowList);
        $this->eventDispatcher->dispatch($event);

        $this->cleanupLineItems($cart->getLineItems()$event->getCustomFieldAllowList());

        foreach ($cart->getDeliveries() as $delivery) {
            $this->cleanupLineItems($delivery->getPositions()->getLineItems()$event->getCustomFieldAllowList());
        }
    }

    /** * @param array<mixed> $customFieldAllowList */
    private function cleanupLineItems(LineItemCollection $lineItems, array $customFieldAllowList): void
    {
        foreach ($lineItems as $lineItem) {
            $this->cleanupLineItem($lineItem$customFieldAllowList);
        }
'languageId' => self::$deLanguageId,
                ]], Context::createDefaultContext());

                $criteria = OrderDocumentCriteriaFactory::create([$operation->getOrderId()]);
                /** @var OrderEntity $order */
                $order = $container->get('order.repository')->search($criteria, Context::createDefaultContext())->get($operation->getOrderId());

                $context = clone Context::createDefaultContext();
                $context = $context->assign([
                    'languageIdChain' => array_unique(array_filter([self::$deLanguageId, Context::createDefaultContext()->getLanguageId()])),
                ]);
                static::assertNotNull($order->getDeliveries());
                /** @var $delivery OrderDeliveryEntity */
                static::assertNotNull($delivery = $order->getDeliveries()->first());
                /** @var $shippingMethod ShippingMethodEntity */
                static::assertNotNull($shippingMethod = $delivery->getShippingMethod());

                $container->get('shipping_method.repository')->upsert([[
                    'id' => $shippingMethod->getId(),
                    'name' => 'DE express',
                ]]$context);

                $operation->assign([
                    
        foreach ($this->processors as $processor) {
            $processor->process($cart->getData()$original$cart$context$behavior);

            $this->calculateAmount($context$cart);
        }
    }

    private function calculateAmount(SalesChannelContext $context, Cart $cart): void
    {
        $amount = $this->amountCalculator->calculate(
            $cart->getLineItems()->getPrices(),
            $cart->getDeliveries()->getShippingCosts(),
            $context
        );

        $cart->setPrice($amount);
    }
}
$conversionContext = (new OrderConversionContext())
            ->setIncludeCustomer(false)
            ->setIncludeBillingAddress(false)
            ->setIncludeDeliveries(true)
            ->setIncludeTransactions(false)
            ->setIncludeOrderDate(false);

        $orderData = $this->orderConverter->convertToOrder($recalculatedCart$salesChannelContext$conversionContext);
        $orderData['id'] = $order->getId();
        $orderData['stateId'] = $order->getStateId();
        if ($order->getDeliveries()?->first()?->getStateId()) {
            $orderData['deliveries'][0]['stateId'] = $order->getDeliveries()->first()->getStateId();
        }

        // change scope to be able to write protected state fields of transactions and deliveries         $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($orderData): void {
            $this->orderRepository->upsert([$orderData]$context);
        });
    }

    /** * @throws DeliveryWithoutAddressException * @throws InconsistentCriteriaIdsException * @throws CartException * @throws ProductNotFoundException */
$request = new Request(['downloadId' => $download->getId(), 'orderId' => $orderId]);
                    $this->downloadRoute->load($request$this->salesChannelContext);

                    static::fail('Download route returned response without access granted');
                } catch (\Throwable $exception) {
                    static::assertInstanceOf(CustomerException::class$exception);
                    static::assertSame(sprintf('Line item download file with id "%s" not found.', $download->getId())$exception->getMessage());
                }
            }
        }

        static::assertNotNull($order->getDeliveries());
        if (\in_array([]$productDownloads, true)) {
            static::assertNotNull($order->getLineItems());
            static::assertTrue($order->getLineItems()->hasLineItemWithState(State::IS_PHYSICAL));
            static::assertEquals(1, $order->getDeliveries()->count());
        } else {
            static::assertEquals(0, $order->getDeliveries()->count());
        }

        return $orderId;
    }

    
private readonly LineItemDownloadLoader $downloadLoader
    ) {
    }

    /** * @throws DeliveryWithoutAddressException * * @return array<string, mixed|float|string|array<int, array<string, string|int|bool|mixed>>|null> */
    public function convertToOrder(Cart $cart, SalesChannelContext $context, OrderConversionContext $conversionContext): array
    {
        foreach ($cart->getDeliveries() as $delivery) {
            if ($delivery->getLocation()->getAddress() !== null || $delivery->hasExtensionOfType(self::ORIGINAL_ID, IdStruct::class)) {
                continue;
            }

            throw new DeliveryWithoutAddressException();
        }
        $data = CartTransformer::transform(
            $cart,
            $context,
            $this->initialStateIdLoader->get(OrderStates::STATE_MACHINE),
            $conversionContext->shouldIncludeOrderDate()
        );
Home | Imprint | This part of the site doesn't use cookies.