getTotalPrice example

/** * Provide a negative percentage value for discount or a positive percentage value for a surcharge * * @param float $percentage 10.00 for 10%, -10.0 for -10% */
    public function calculate(float $percentage, PriceCollection $prices, SalesChannelContext $context): CalculatedPrice
    {
        $price = $prices->sum();

        $discount = $this->round(
            $price->getTotalPrice() / 100 * $percentage,
            $context
        );

        $rules = $this->percentageTaxRuleBuilder->buildRules($price);

        $definition = new QuantityPriceDefinition($discount$rules, 1);

        return $this->priceCalculator->calculate($definition$context);
    }

    private function round(float $price, SalesChannelContext $context): float
    {
return;
        }

        static::assertTrue($new->has(self::DISCOUNT_ID));

        $item = $new->get(self::DISCOUNT_ID);
        static::assertInstanceOf(LineItem::class$item);
        $price = $item->getPrice();

        static::assertInstanceOf(CalculatedPrice::class$price);
        static::assertEquals($expected->getUnitPrice()$price->getUnitPrice());
        static::assertEquals($expected->getTotalPrice()$price->getTotalPrice());

        $taxes = $expected->getCalculatedTaxes();

        static::assertEquals($taxes->getAmount()$price->getCalculatedTaxes()->getAmount());

        foreach ($taxes as $tax) {
            $actual = $price->getCalculatedTaxes()->get((string) $tax->getTaxRate());

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

        
$orderId = $this->order($cart$context);

            $listener->assertSent('order_confirmation_mail');

            return $orderId;
        });

        $item = $this->assertProductInOrder($orderId$product->id);

        static::assertEquals(100, $item->getUnitPrice());

        static::assertEquals(100, $item->getTotalPrice());

        if (Feature::isActive('STOCK_HANDLING')) {
            $this->assertStock($product->id, 99, 99);
        } else {
            $this->assertStock($product->id, 100, 99);
        }
    }
}
$delivery = $cart->getDeliveries()->first();

        static::assertNotNull($lineItem);
        static::assertNotNull($delivery);

        $lineItemPrice = $lineItem->getPrice();
        $deliveryPosition = $delivery->getPositions()->first();

        static::assertNotNull($lineItemPrice);
        static::assertNotNull($deliveryPosition);

        static::assertSame(214.0, $cart->getPrice()->getTotalPrice());
        static::assertSame(200.0, $cart->getPrice()->getNetPrice());
        static::assertSame(14.0, $cart->getPrice()->getCalculatedTaxes()->getAmount());
        static::assertSame(7.0, $lineItemPrice->getCalculatedTaxes()->getAmount());
        static::assertSame(7.0, $delivery->getShippingCosts()->getCalculatedTaxes()->getAmount());
        static::assertSame(7.0, $deliveryPosition->getPrice()->getCalculatedTaxes()->getAmount());
    }

    public function testCalculateGross(): void
    {
        $result = new TaxProviderResult(
            [
                
$price = $this->calculatePrice($creditItems$order);

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

                $html = $this->documentTemplateRenderer->render(
                    $template,
                    [
                        'order' => $order,
                        'creditItems' => $creditItems,
                        'price' => $price->getTotalPrice() * -1,
                        'amountTax' => $price->getCalculatedTaxes()->getAmount(),
                        'config' => $config,
                        'rootDir' => $this->rootDir,
                        'context' => $context,
                    ],
                    $context,
                    $order->getSalesChannelId(),
                    $order->getLanguageId(),
                    $locale->getCode()
                );

                
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));
            },
$newLineItem = $splitter->split($lineItem$splitterQty$this->salesChannelContext);

        if ($calcExpects <= 0) {
            static::assertEquals($lineItem$newLineItem);
        } else {
            $expectedPrice = 10 * $splitterQty;

            static::assertNotEquals($lineItem$newLineItem);
            static::assertEquals($splitterQty$newLineItem->getQuantity());
            static::assertNotNull($newLineItem->getPrice());
            static::assertEquals($expectedPrice$newLineItem->getPrice()->getTotalPrice());
        }
    }

    /** * @return \Generator<string, int[]> */
    public static function splitProvider(): \Generator
    {
        yield 'should not split items when item qty = 10 and splitter qty = 10' => [10, 10, 0];
        yield 'should split items when item qty = 10 and splitter qty = 9' => [10, 9, 1];
        yield 'should split items when item qty = 9 and splitter qty = 10' => [9, 10, 1];
    }
$price = $calculator->calculate(
            $calculation->getPercentageDiscount(),
            $calculation->getPrices(),
            Generator::createSalesChannelContext()
        );
        $expected = $calculation->getExpected();

        static::assertEquals($expected$price);
        static::assertEquals($expected->getCalculatedTaxes()$price->getCalculatedTaxes());
        static::assertEquals($expected->getTaxRules()$price->getTaxRules());
        static::assertEquals($expected->getTotalPrice()$price->getTotalPrice());
        static::assertEquals($expected->getUnitPrice()$price->getUnitPrice());
        static::assertEquals($expected->getQuantity()$price->getQuantity());
    }

    public static function grossPriceDataProvider(): \Generator
    {
        yield [self::getDifferentTaxesCalculation()];
        yield [self::getOneHundredPercentageCalculation()];
        yield [self::getFiftyPercentageCalculation()];
        yield [self::regression_next_12270()];
    }

    
use Shopware\Core\Checkout\Cart\Price\Struct\CalculatedPrice;
use Shopware\Core\Checkout\Cart\Transaction\Struct\Transaction;
use Shopware\Core\Checkout\Cart\Transaction\Struct\TransactionCollection;
use Shopware\Core\Framework\Log\Package;
use Shopware\Core\System\SalesChannel\SalesChannelContext;

#[Package('checkout')] class TransactionProcessor
{
    public function process(Cart $cart, SalesChannelContext $context): TransactionCollection
    {
        $price = $cart->getPrice()->getTotalPrice();

        return new TransactionCollection([
            new Transaction(
                new CalculatedPrice(
                    $price,
                    $price,
                    $cart->getPrice()->getCalculatedTaxes(),
                    $cart->getPrice()->getTaxRules()
                ),
                $context->getPaymentMethod()->getId()
            ),
        ]);
$orderDeliveryRepository = $this->getContainer()->get('order_delivery.repository');
        $deliveries = $orderDeliveryRepository->search($criteria$versionContext);

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

        /** @var OrderDeliveryEntity $delivery */
        $delivery = $deliveries->first();
        $shippingCosts = $delivery->getShippingCosts();

        static::assertSame(1, $shippingCosts->getQuantity());
        static::assertSame(10.0, $shippingCosts->getUnitPrice());
        static::assertSame(10.0, $shippingCosts->getTotalPrice());
        static::assertEquals(2, $shippingCosts->getCalculatedTaxes()->count());

        // change shipping costs         $newShippingCosts = new CalculatedPrice(5, 5, new CalculatedTaxCollection()new TaxRuleCollection());

        /** @var OrderDeliveryEntity $delivery */
        $delivery = $deliveries->first();

        $payload = [
            'id' => $delivery->getId(),
            'shippingCosts' => $newShippingCosts,
        ];
$customerId = $context->getCustomer() ? Uuid::fromHexToBytes($context->getCustomer()->getId()) : null;

        $data = [
            'token' => $cart->getToken(),
            'currency_id' => Uuid::fromHexToBytes($context->getCurrency()->getId()),
            'shipping_method_id' => Uuid::fromHexToBytes($context->getShippingMethod()->getId()),
            'payment_method_id' => Uuid::fromHexToBytes($context->getPaymentMethod()->getId()),
            'country_id' => Uuid::fromHexToBytes($context->getShippingLocation()->getCountry()->getId()),
            'sales_channel_id' => Uuid::fromHexToBytes($context->getSalesChannel()->getId()),
            'customer_id' => $customerId,
            'price' => $cart->getPrice()->getTotalPrice(),
            'line_item_count' => $cart->getLineItems()->count(),
            'payload' => $this->serializeCart($cart$payloadExists),
            'rule_ids' => json_encode($context->getRuleIds(), \JSON_THROW_ON_ERROR),
            'now' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
        ];

        // @deprecated tag:v6.6.0 - remove if condition, but keep body         if ($payloadExists) {
            $data['compressed'] = (int) $this->compress;
        }

        
$this->createTestFixturePercentagePromotion($promotionId2, '100off', 100, null, $this->getContainer());

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

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

        // create promotion and add to cart         $cart = $this->addPromotionCode('sale', $cart$this->cartService, $context);
        $cart = $this->addPromotionCode('100off', $cart$this->cartService, $context);

        static::assertEquals(0.0, $cart->getPrice()->getTotalPrice());
        static::assertEquals(0.0, $cart->getPrice()->getPositionPrice());
        static::assertEquals(0.0, $cart->getPrice()->getNetPrice());
    }

    /** * This test verifies that we can successfully remove an added * promotion by code and get the original price again. * * @group promotions * * @throws CartException */
->setStackable(true)
                ->setRemovable(true)
        );

        $calculated = $this->processor->process($cart$this->context, new CartBehavior());

        static::assertCount(1, $calculated->getLineItems());
        static::assertTrue($calculated->has($id));
        $item = $calculated->get($id);
        static::assertInstanceOf(LineItem::class$item);
        static::assertInstanceOf(CalculatedPrice::class$item->getPrice());
        static::assertSame(119.99, $item->getPrice()->getTotalPrice());

        static::assertCount(1, $calculated->getDeliveries());

        /** @var Delivery $delivery */
        $delivery = $calculated->getDeliveries()->first();
        static::assertTrue($delivery->getPositions()->getLineItems()->has($id));
    }

    public function testExtensionsAreMergedEarly(): void
    {
        $extension = new class() extends Struct {
        };
$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(
            
/** * Calculates discounts for delivery costs of cart * The calculation process will first determine if we have a delivery discount * (we use the same collector for all promotions) * after that it is calculating the shipping costs respecting absolute, fixed or percentage discounts * * @throws InvalidPriceDefinitionException * @throws CartException */
    public function calculate(LineItemCollection $discountLineItems, Cart $original, Cart $toCalculate, SalesChannelContext $context): void
    {
        $notDiscountedDeliveriesValue = $toCalculate->getDeliveries()->getShippingCosts()->sum()->getTotalPrice();

        // reduce discount lineItems if fixed price discounts are in collection         $checkedDiscountLineItems = $this->reduceDiscountLineItemsIfFixedPresent($discountLineItems);

        $exclusions = $this->buildExclusions($checkedDiscountLineItems);

        foreach ($checkedDiscountLineItems as $discountItem) {
            if ($notDiscountedDeliveriesValue <= 0.0) {
                continue;
            }

            
Home | Imprint | This part of the site doesn't use cookies.