getShippingMethod example

$salesChannelContext->expects(static::once())
            ->method('getShippingLocation')
            ->willReturn($deliveryLocation);

        $deliveryCollection = (new DeliveryBuilder())->buildByUsingShippingMethod($cart$shippingMethod$salesChannelContext);

        static::assertEquals(1, $deliveryCollection->count());

        /** @var Delivery $delivery */
        $delivery = $deliveryCollection->first();

        static::assertSame($shippingMethod$delivery->getShippingMethod());
        static::assertSame($deliveryLocation$delivery->getLocation());
        static::assertEquals(
            new CalculatedPrice(0, 0, new CalculatedTaxCollection()new TaxRuleCollection()),
            $delivery->getShippingCosts(),
        );

        static::assertEquals($expectedDeliveryDate$delivery->getDeliveryDate());
    }

    /** * @return iterable<array{0: LineItemCollection, 1: DeliveryDate}> */
public function getShippingAddress(): OrderAddressCollection
    {
        return new OrderAddressCollection(
            $this->fmap(fn (OrderDeliveryEntity $orderDelivery) => $orderDelivery->getShippingOrderAddress())
        );
    }

    public function getShippingMethods(): ShippingMethodCollection
    {
        return new ShippingMethodCollection(
            $this->fmap(fn (OrderDeliveryEntity $orderDelivery) => $orderDelivery->getShippingMethod())
        );
    }

    public function getApiAlias(): string
    {
        return 'order_delivery_collection';
    }

    protected function getExpectedClass(): string
    {
        return OrderDeliveryEntity::class;
    }
$this->calculateDelivery($data$cart$delivery$context);
        }
    }

    private function calculateDelivery(CartDataCollection $data, Cart $cart, Delivery $delivery, SalesChannelContext $context): void
    {
        $costs = null;
        $manualShippingCost = $cart->getExtension(DeliveryProcessor::MANUAL_SHIPPING_COSTS);
        $manualShippingCost = $manualShippingCost instanceof CalculatedPrice ? $manualShippingCost : null;
        if ($delivery->getShippingCosts()->getUnitPrice() > 0 || $manualShippingCost) {
            $costs = $this->calculateShippingCosts(
                $delivery->getShippingMethod(),
                new PriceCollection([
                    new Price(
                        Defaults::CURRENCY,
                        $delivery->getShippingCosts()->getTotalPrice(),
                        $delivery->getShippingCosts()->getTotalPrice(),
                        false
                    ),
                ]),
                $delivery->getPositions()->getLineItems(),
                $context,
                $manualShippingCost
            );

    private function addDiscountDeliveryItem(DeliveryCollection $deliveries, Delivery $delivery, CalculatedPrice $price): void
    {
        if ($price->getTotalPrice() >= 0) {
            return;
        }

        $delivery = new Delivery(
            $delivery->getPositions(),
            $delivery->getDeliveryDate(),
            $delivery->getShippingMethod(),
            $delivery->getLocation(),
            $price
        );

        $deliveries->add($delivery);
    }

    /** * if we have a discount with scope delivery we add a lineItem in cart with price 0 * * @throws CartException */
$this->getContainer()->get('event_dispatcher'),
            $this->getContainer()->get(StorefrontCartFacade::class),
            $this->getContainer()->get(PaymentMethodRoute::class),
            $route,
            $this->getContainer()->get(CountryRoute::class)
        );

        $context = $this->createSalesChannelContextWithNavigation();

        $result = $loader->load(new Request()$context);

        static::assertTrue($result->getShippingMethods()->has($context->getShippingMethod()->getId()));
    }

    /** * @return CheckoutCartPageLoader */
    protected function getPageLoader()
    {
        return $this->getContainer()->get(CheckoutCartPageLoader::class);
    }
}
return [
            'Mixed shipping by quantity' => [DeliveryCalculator::CALCULATION_BY_LINE_ITEM_COUNT, 1, 100],
            'Mixed shipping by cart price' => [DeliveryCalculator::CALCULATION_BY_PRICE, 100, 1],
            'Mixed shipping by weight' => [DeliveryCalculator::CALCULATION_BY_WEIGHT, 1, 1],
            'Mixed shipping by volume' => [DeliveryCalculator::CALCULATION_BY_VOLUME, 1, 1],
        ];
    }

    private function buildDeliveries(LineItemCollection $lineItems, SalesChannelContext $context): DeliveryCollection
    {
        $data = new CartDataCollection();
        $data->set(DeliveryProcessor::buildKey($context->getShippingMethod()->getId())$context->getShippingMethod());

        $cart = new Cart('test');
        $cart->setLineItems($lineItems);

        return $this->getContainer()->get(DeliveryBuilder::class)
            ->build($cart$data$contextnew CartBehavior());
    }

    private function createLineItem(DeliveryInformation $deliveryInformation, CalculatedPrice $calculatedPrice): LineItem
    {
        $lineItem = new LineItem(Uuid::randomHex(), 'product');
        


        if (\in_array('language:read', $privileges, true)) {
            $builder->withClaim('languageId', $context->getLanguageId());
        }

        if (\in_array('payment_method:read', $privileges, true)) {
            $builder->withClaim('paymentMethodId', $context->getPaymentMethod()->getId());
        }

        if (\in_array('shipping_method:read', $privileges, true)) {
            $builder->withClaim('shippingMethodId', $context->getShippingMethod()->getId());
        }

        return new JsonResponse([
            'token' => $builder->getToken($configuration->signer()$configuration->signingKey())->toString(),
            'expires' => $expiration->format(\DateTime::ATOM),
            'shopId' => $shopId,
        ]);
    }

    /** * @return array{app_secret: non-empty-string, privileges: array<string>} */

#[Package('checkout')] class BlockedShippingMethodSwitcher
{
    public function __construct(private readonly AbstractShippingMethodRoute $shippingMethodRoute)
    {
    }

    public function switch(ErrorCollection $errors, SalesChannelContext $salesChannelContext): ShippingMethodEntity
    {
        $originalShippingMethod = $salesChannelContext->getShippingMethod();
        if (!$this->shippingMethodBlocked($errors)) {
            return $originalShippingMethod;
        }

        $shippingMethod = $this->getShippingMethodToChangeTo($errors$salesChannelContext);
        if ($shippingMethod === null) {
            return $originalShippingMethod;
        }

        $this->addNoticeToCart($errors$shippingMethod);

        


        $salesChannelContext = new SalesChannelContext(
            $context,
            $token,
            $options[SalesChannelContextService::DOMAIN_ID] ?? null,
            $base->getSalesChannel(),
            $base->getCurrency(),
            $customerGroup,
            $taxRules,
            $payment,
            $base->getShippingMethod(),
            $shippingLocation,
            $customer,
            $itemRounding,
            $totalRounding
        );

        if (\array_key_exists(SalesChannelContextService::PERMISSIONS, $options)) {
            $salesChannelContext->setPermissions($options[SalesChannelContextService::PERMISSIONS]);

            $event = new SalesChannelContextPermissionsChangedEvent($salesChannelContext$options[SalesChannelContextService::PERMISSIONS]);
            $this->eventDispatcher->dispatch($event);

            
if ($addressId !== null && \array_key_exists($addressId$addresses)) {
            $shippingAddress = $addresses[$addressId];
        } elseif ($delivery->getLocation()->getAddress() !== null) {
            $shippingAddress = AddressTransformer::transform($delivery->getLocation()->getAddress());
        }

        $deliveryData = [
            'id' => self::getId($delivery),
            'shippingDateEarliest' => $delivery->getDeliveryDate()->getEarliest()->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            'shippingDateLatest' => $delivery->getDeliveryDate()->getLatest()->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            'shippingMethodId' => $delivery->getShippingMethod()->getId(),
            'shippingOrderAddress' => $shippingAddress,
            'shippingCosts' => $delivery->getShippingCosts(),
            'positions' => [],
            'stateId' => $stateId,
        ];

        $deliveryData = array_filter($deliveryDatafn ($item) => $item !== null);

        foreach ($delivery->getPositions() as $position) {
            $deliveryData['positions'][] = [
                'id' => self::getId($position),
                


    private function getShippingMethods(SalesChannelContext $context): ShippingMethodCollection
    {
        $request = new Request();
        $request->query->set('onlyAvailable', '1');

        $shippingMethods = $this->shippingMethodRoute
            ->load($request$contextnew Criteria())
            ->getShippingMethods();

        if (!$shippingMethods->has($context->getShippingMethod()->getId())) {
            $shippingMethods->add($context->getShippingMethod());
        }

        return $shippingMethods;
    }

    private function getCountries(SalesChannelContext $context): CountryCollection
    {
        $countries = $this->countryRoute->load(new Request()new Criteria()$context)->getCountries();
        $countries->sortByPositionAndName();

        
$identifier,
                    $lineItems->get($identifier),
                    $position->getPrice()->getQuantity(),
                    $position->getPrice(),
                    $deliveryDate
                );
                $deliveryPosition->addExtension(self::ORIGINAL_ID, new IdStruct($position->getId()));

                $deliveryPositions->add($deliveryPosition);
            }

            if ($orderDelivery->getShippingMethod() === null
                || $orderDelivery->getShippingOrderAddress() === null
                || $orderDelivery->getShippingOrderAddress()->getCountry() === null
            ) {
                continue;
            }

            $cartDelivery = new Delivery(
                $deliveryPositions,
                $deliveryDate,
                $orderDelivery->getShippingMethod(),
                new ShippingLocation(
                    
private $salesChannelContext;

    protected function setUp(): void
    {
        $this->salesChannelContext = $this->getContainer()->get(SalesChannelContextFactory::class)
            ->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL);

        $shippingMethodPriceEntity = new ShippingMethodPriceEntity();
        $shippingMethodPriceEntity->setUniqueIdentifier('test');
        $shippingMethodPriceEntity->setCurrencyPrice(new PriceCollection([new Price(Defaults::CURRENCY, 5, 5, false)]));

        $this->salesChannelContext->getShippingMethod()->setPrices(new ShippingMethodPriceCollection([$shippingMethodPriceEntity]));
    }

    public function testProcessShouldRecalculateAll(): void
    {
        $deliveryProcessor = $this->getContainer()->get(DeliveryProcessor::class);

        $cartDataCollection = new CartDataCollection();
        $cartDataCollection->set(
            DeliveryProcessor::buildKey($this->salesChannelContext->getShippingMethod()->getId()),
            $this->salesChannelContext->getShippingMethod()
        );
        
/** @var CustomerGroupEntity $customerGroup */
        $customerGroup = $customerGroups->get($groupId);

        // loads tax rules based on active customer and delivery address         $taxRules = $this->getTaxRules($context);

        // detect active payment method, first check if checkout defined other payment method, otherwise validate if customer logged in, at least use shop default         $payment = $this->getPaymentMethod($options$context$salesChannel);

        // detect active delivery method, at first checkout scope, at least shop default method         $shippingMethod = $this->getShippingMethod($options$context$salesChannel);

        [$itemRounding$totalRounding] = $this->getCashRounding($currency$shippingLocation$context);

        $context = new Context(
            $context->getSource(),
            [],
            $currency->getId(),
            $context->getLanguageIdChain(),
            $context->getVersionId(),
            $currency->getFactor(),
            true,
            
/** @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([
                    'config' => [
                        'displayHeader' => true,
                        'documentDate' => $documentDate,
                    ],
                ]);
Home | Imprint | This part of the site doesn't use cookies.