getPrice example

$new = new Cart('after');
        $processor->process(new CartDataCollection()$cart$new$contextnew CartBehavior());

        if ($expected === null) {
            static::assertFalse($new->has($item->getId()));

            return;
        }

        static::assertTrue($new->has($item->getId()));

        static::assertInstanceOf(CalculatedPrice::class$item->getPrice());
        static::assertEquals($expected->getUnitPrice()$item->getPrice()->getUnitPrice());
        static::assertEquals($expected->getTotalPrice()$item->getPrice()->getTotalPrice());
        static::assertEquals($expected->getCalculatedTaxes()->getAmount()$item->getPrice()->getCalculatedTaxes()->getAmount());

        foreach ($expected->getCalculatedTaxes() as $tax) {
            $actual = $item->getPrice()->getCalculatedTaxes()->get((string) $tax->getTaxRate());

            static::assertInstanceOf(CalculatedTax::class$actualsprintf('Missing tax for rate %f', $tax->getTaxRate()));
            static::assertEquals($tax->getTax()$actual->getTax());
        }

        
if (!$price instanceof PriceRule) {
                continue;
            }

            $discount = $this->getHighestQuantityDiscount($product$context$price->getFrom());

            if (!$discount) {
                continue;
            }
            $price->setPrice(
                $price->getPrice() / 100 * (100 - $discount->getPercent())
            );
        }

        return $prices;
    }

    /** * Helper function which iterates the products and builds a price array which indexed * with the product order number. * * @param BaseProduct[] $products * @param PriceRule[] $priceRules * * @return array<string, PriceRule> */
'productId' => $productId,
            'promotionId' => $promotionId,
            'referencedId' => $lineItem->getReferencedId(),
            'quantity' => $lineItem->getQuantity(),
            'type' => $lineItem->getType(),
            'label' => $lineItem->getLabel(),
            'description' => $lineItem->getDescription(),
            'good' => $lineItem->isGood(),
            'removable' => $lineItem->isRemovable(),
            'stackable' => $lineItem->isStackable(),
            'position' => $position,
            'price' => $lineItem->getPrice(),
            'priceDefinition' => $definition,
            'parentId' => $parentId,
            'coverId' => $lineItem->getCover() ? $lineItem->getCover()->getId() : null,
            'payload' => $lineItem->getPayload(),
            'states' => $lineItem->getStates(),
        ];

        $downloads = $lineItem->getExtensionOfType(OrderConverter::ORIGINAL_DOWNLOADS, OrderLineItemDownloadCollection::class);
        if ($downloads instanceof OrderLineItemDownloadCollection) {
            $data['downloads'] = array_values($downloads->map(fn (OrderLineItemDownloadEntity $download): array => ['id' => $download->getId()]));
        }

        
$package = new DiscountPackage(
            new LineItemQuantityCollection([
                new LineItemQuantity($lineItem->getId(), 1),
                new LineItemQuantity($lineItem->getId(), 1),
            ])
        );
        $package->setCartItems(new LineItemFlatCollection([$lineItem]));

        $price = $discountCalculator->calculate($discountnew DiscountPackageCollection([$package])$context);

        static::assertEquals($discountOut$price->getPrice()->getTotalPrice());
    }

    public function testInvalidPriceDefinitionThrow(): void
    {
        $context = Generator::createSalesChannelContext();

        $rounding = new CashRounding();

        $taxCalculator = new TaxCalculator();

        $calculator = new AbsolutePriceCalculator(
            


    public function getConfig(): RuleConfig
    {
        return (new RuleConfig())
            ->operatorSet(RuleConfig::OPERATOR_SET_NUMBER)
            ->numberField('amount');
    }

    private function lineItemMatches(LineItem $lineItem): bool
    {
        $price = $lineItem->getPrice();

        if ($price === null || !$this->amount) {
            return RuleComparison::isNegativeOperator($this->operator);
        }

        return RuleComparison::numeric($price->getTotalPrice()$this->amount, $this->operator);
    }
}
$helper = $this->createMock(CartFacadeHelper::class);
        $context = $this->createMock(SalesChannelContext::class);

        $facade = new ItemFacade($item$stubs$helper$context);

        static::assertEquals('foo', $facade->getId());
        static::assertEquals('type', $facade->getType());
        static::assertEquals('reference', $facade->getReferencedId());
        static::assertEquals('label', $facade->getLabel());
        static::assertEquals(2, $facade->getQuantity());

        static::assertInstanceOf(PriceFacade::class$facade->getPrice());
        static::assertEquals(10, $facade->getPrice()->getUnit());
        static::assertEquals(10, $facade->getPrice()->getTotal());

        static::assertEquals('bar', $facade->getPayload()->offsetGet('foo'));
        // @phpstan-ignore-next-line         static::assertEquals('bar', $facade->getPayload()['foo']);
        static::assertEquals('nested', $facade->getPayload()->offsetGet('nested')['foo']);

        // @phpstan-ignore-next-line         static::assertEquals('nested', $facade->getPayload()['nested']['foo']);

        
public static function creditNoteRendererCustomerGroupDataProvider(): \Generator
    {
        yield 'render credit_note with customer group gross' => [
            false,
            [7],
            [-100],
            function DOrderEntity $order): void {
                static::assertNotNull($lineItems = $order->getLineItems());
                $taxAmount = $lineItems->getPrices()->sum()->getCalculatedTaxes()->getAmount();

                static::assertEquals($order->getPrice()->getTotalPrice(), 100);
                static::assertEquals($order->getAmountNet(), -(-100 - $taxAmount));
            },
        ];

        yield 'render credit_note with customer group net' => [
            true,
            [7],
            [-100],
            function DOrderEntity $order): void {
                static::assertEquals($order->getPrice()->getTotalPrice(), \abs(7) + \abs(-100));
                static::assertEquals($order->getAmountNet(), \abs(-100));
            },
public function convertToCart(OrderEntity $order, Context $context): Cart
    {
        if ($order->getLineItems() === null) {
            throw OrderException::missingAssociation('lineItems');
        }

        if ($order->getDeliveries() === null) {
            throw OrderException::missingAssociation('deliveries');
        }

        $cart = new Cart(Uuid::randomHex());
        $cart->setPrice($order->getPrice());
        $cart->setCustomerComment($order->getCustomerComment());
        $cart->setAffiliateCode($order->getAffiliateCode());
        $cart->setCampaignCode($order->getCampaignCode());
        $cart->setSource($order->getSource());
        $cart->addExtension(self::ORIGINAL_ID, new IdStruct($order->getId()));
        $orderNumber = $order->getOrderNumber();
        if ($orderNumber === null) {
            throw OrderException::missingOrderNumber($order->getId());
        }

        $cart->addExtension(self::ORIGINAL_ORDER_NUMBER, new IdStruct($orderNumber));
        
$firstGraduation = clone $reference;
            $previous = $firstGraduation;

            $prices[] = $firstGraduation;
        }

        foreach ($discounts as $discount) {
            $rule = clone $reference;

            $percent = (100 - $discount->getPercent()) / 100;

            $price = $reference->getPrice() * $percent;

            $pseudo = $reference->getPseudoPrice();

            $rule->setPrice($price);

            $rule->setPseudoPrice($pseudo);

            $rule->setFrom($discount->getQuantity());

            $rule->setCustomerGroup($customerGroup);

            


                $params = [
                    $this->session->get('sessionId'),
                    $voucherName . ($hasMultipleTaxes ? ' (' . $voucherPrice->getTaxRate() . '%)' : ''),
                    $voucherDetails['id'],
                    $voucherDetails['ordercode'],
                    $freeShipping,
                    $voucherPrice->getPrice(),
                    $voucherPrice->getNetPrice(),
                    $voucherPrice->getTaxRate(),
                    $timeInsert,
                    $this->sSYSTEM->sCurrency['factor'],
                ];

                $sql = $this->eventManager->filter(
                    'Shopware_Modules_Basket_AddVoucher_FilterSql',
                    $sql,
                    [
                        'subject' => $this,
                        
static::assertInstanceOf(OrderLineItemEntity::class$item);

        return $item;
    }

    protected function assertLineItemTotalPrice(Cart $cart, string $id, float $price): void
    {
        $item = $cart->get($id);

        static::assertInstanceOf(LineItem::class$item, \sprintf('Can not find line item with id %s', $id));

        static::assertInstanceOf(CalculatedPrice::class$item->getPrice(), \sprintf('Line item with id %s has no price', $id));

        static::assertEquals($price$item->getPrice()->getTotalPrice(), \sprintf('Line item with id %s has wrong total price', $id));
    }

    protected function assertLineItemUnitPrice(Cart $cart, string $id, float $price): void
    {
        $item = $cart->get($id);

        static::assertInstanceOf(LineItem::class$item, \sprintf('Can not find line item with id %s', $id));

        static::assertInstanceOf(CalculatedPrice::class$item->getPrice(), \sprintf('Line item with id %s has no price', $id));

        
$surcharge = new PriceCollection([new Price(Defaults::CURRENCY, 2, 2, false)]);
        $container->surcharge('my-surcharge', 'absolute', $surcharge, 'unit test');

        $service->items()->add($container);
        $service->calculate();

        static::assertTrue($service->has('my-container'));
        $container = $service->get('my-container');

        static::assertInstanceOf(ItemFacade::class$container);
        static::assertInstanceOf(PriceFacade::class$container->getPrice());
        static::assertEquals(182, $container->getPrice()->getTotal());
    }

    public function testRemove(): void
    {
        $context = $this->getContainer()->get(SalesChannelContextFactory::class)
            ->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL, []);

        $hook = new CartHook($this->createCart()$context);
        $cart = $this->getContainer()->get(CartFacadeHookFactory::class)->factory($hook$this->script);

        

        return (new RuleConfig())
            ->operatorSet(RuleConfig::OPERATOR_SET_NUMBER, true)
            ->numberField('amount');
    }

    /** * @throws UnsupportedOperatorException */
    private function matchesListPriceCondition(LineItem $lineItem): bool
    {
        $calculatedPrice = $lineItem->getPrice();

        if (!$calculatedPrice instanceof CalculatedPrice) {
            return RuleComparison::isNegativeOperator($this->operator);
        }

        $listPrice = $calculatedPrice->getListPrice();

        $listPriceAmount = null;
        if ($listPrice instanceof ListPrice) {
            $listPriceAmount = $listPrice->getPrice();
        }

        


    /** * @return DiscountCompositionItem[] */
    private function getCompositionItems(float $percentage, DiscountPackageCollection $packages): array
    {
        $items = [];

        foreach ($packages as $package) {
            foreach ($package->getCartItems() as $lineItem) {
                if ($lineItem->getPrice() === null) {
                    continue;
                }

                $itemTotal = $lineItem->getQuantity() * $lineItem->getPrice()->getUnitPrice();
                $percentageFactor = abs($percentage) / 100.0;

                $items[] = new DiscountCompositionItem(
                    $lineItem->getId(),
                    $lineItem->getQuantity(),
                    $itemTotal * $percentageFactor
                );
            }
// add a new promotion black friday         $this->createTestFixturePercentagePromotion($promotionId$code, 100, null, $this->getContainer());

        $cart = $this->cartService->getCart($context->getToken()$context);

        // create product and add to cart         $cart = $this->addProduct($productId, 1, $cart$this->cartService, $context);

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

        static::assertEquals(0.0, $cart->getPrice()->getPositionPrice(), 'Position Total Price has to be 0,00');
        static::assertEquals(0.0, $cart->getPrice()->getTotalPrice(), 'Total Price has to be 0,00');
        static::assertEquals(0.0, $cart->getPrice()->getCalculatedTaxes()->getAmount(), 'Taxes have to be 0,00');
        static::assertEquals(0.0, $cart->getPrice()->getNetPrice(), 'Net Price has to be 0,00');
    }

    /** * This test verifies that our promotion components are really involved in our checkout. * We add a product to the cart and apply a code for a promotion with 50% discount. * Our cart should have a total value of 15,00 in the end. * * @group promotions * * @throws CartException */
Home | Imprint | This part of the site doesn't use cookies.