CalculatedTaxCollection example

private function createTransaction(
        string $orderId,
        string $paymentMethodId,
        Context $context
    ): string {
        $id = Uuid::randomHex();
        $transaction = [
            'id' => $id,
            'orderId' => $orderId,
            'paymentMethodId' => $paymentMethodId,
            'stateId' => $this->getContainer()->get(InitialStateIdLoader::class)->get(OrderTransactionStates::STATE_MACHINE),
            'amount' => new CalculatedPrice(100, 100, new CalculatedTaxCollection()new TaxRuleCollection(), 1),
            'payload' => '{}',
        ];

        $this->orderTransactionRepository->upsert([$transaction]$context);

        return $id;
    }

    private function createOrder(
        string $customerId,
        string $paymentMethodId,
        
$order = [
            'id' => $ids->get('order'),
            'itemRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'totalRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'billingAddressId' => $ids->get('billing'),
            'currencyId' => Defaults::CURRENCY,
            'salesChannelId' => TestDefaults::SALES_CHANNEL,
            'stateId' => $this->getStateId(),
            'currencyFactor' => 1,
            'orderDateTime' => new \DateTime(),
            'price' => json_decode(json_encode(new CartPrice(1, 1, 1, new CalculatedTaxCollection()new TaxRuleCollection(), CartPrice::TAX_STATE_FREE), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'shippingCosts' => json_decode(json_encode(new CalculatedPrice(1, 1, new CalculatedTaxCollection()new TaxRuleCollection()), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
        ];

        $this->getContainer()->get('order.repository')
            ->create([$order], Context::createDefaultContext());

        $this->getContainer()->get(Connection::class)
            ->executeStatement('UPDATE `order` SET total_rounding = NULL WHERE id = :id', ['id' => $ids->getBytes('order')]);

        $rounding = $this->getContainer()->get(Connection::class)
            ->fetchOne('SELECT total_rounding FROM `order` WHERE id = :id', ['id' => $ids->getBytes('order')]);

        
$addressId = Uuid::randomHex();
        $orderLineItemId = Uuid::randomHex();
        $countryStateId = Uuid::randomHex();
        $salutation = $this->getValidSalutationId();

        $order = [
            [
                'id' => $orderId,
                'itemRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
                'totalRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
                'orderDateTime' => (new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
                'price' => new CartPrice(10, 10, 10, new CalculatedTaxCollection()new TaxRuleCollection(), CartPrice::TAX_STATE_NET),
                'shippingCosts' => new CalculatedPrice(10, 10, new CalculatedTaxCollection()new TaxRuleCollection()),
                'stateId' => $this->getContainer()->get(InitialStateIdLoader::class)->get(OrderStates::STATE_MACHINE),
                'paymentMethodId' => $this->getValidPaymentMethodId(),
                'currencyId' => Defaults::CURRENCY,
                'currencyFactor' => 1,
                'salesChannelId' => TestDefaults::SALES_CHANNEL,
                'deliveries' => [
                    [
                        'stateId' => $this->getContainer()->get(InitialStateIdLoader::class)->get(OrderDeliveryStates::STATE_MACHINE),
                        'shippingMethodId' => $this->getValidShippingMethodId(),
                        'shippingCosts' => new CalculatedPrice(10, 10, new CalculatedTaxCollection()new TaxRuleCollection()),
                        
$this->buildPositions($collection$positions$deliveryTime);

        if ($positions->count() <= 0) {
            return null;
        }

        return new Delivery(
            $positions,
            $this->getDeliveryDateByPositions($positions),
            $shippingMethod,
            $context->getShippingLocation(),
            new CalculatedPrice(0, 0, new CalculatedTaxCollection()new TaxRuleCollection())
        );
    }

    private function getDeliveryDateByPositions(DeliveryPositionCollection $positions): DeliveryDate
    {
        // this function is only called if the provided collection contains a deliverable line item         $max = $positions->first()->getDeliveryDate();

        foreach ($positions as $position) {
            $date = $position->getDeliveryDate();

            
return $salesChannelContextFactory->create($token, TestDefaults::SALES_CHANNEL, $options);
    }

    private function createOrder(string $customerId): void
    {
        $this->getContainer()->get('order.repository')->create(
            [[
                'id' => $this->ids->create('order'),
                'itemRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
                'totalRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
                'orderDateTime' => (new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
                'price' => new CartPrice(10, 10, 10, new CalculatedTaxCollection()new TaxRuleCollection(), CartPrice::TAX_STATE_NET),
                'shippingCosts' => new CalculatedPrice(10, 10, new CalculatedTaxCollection()new TaxRuleCollection()),
                'orderCustomer' => [
                    'customerId' => $customerId,
                    'email' => 'test@example.com',
                    'salutationId' => $this->fetchFirstIdFromTable('salutation'),
                    'firstName' => 'Max',
                    'lastName' => 'Mustermann',
                ],
                'stateId' => $this->fetchFirstIdFromTable('state_machine'),
                'paymentMethodId' => $this->fetchFirstIdFromTable('payment_method'),
                'currencyId' => Defaults::CURRENCY,
                
$this->ids->set(
            'state',
            $this->getContainer()->get(InitialStateIdLoader::class)->get(OrderStates::STATE_MACHINE)
        );

        $stateId = $this->ids->get('state');
        $customerId = $this->createCustomer();

        $order = (new OrderBuilder($this->ids, '10000'))
            ->add('id', $this->ids->get('order'))
            ->add('orderDateTime', (new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT))
            ->add('price', new CartPrice(10, 10, 10, new CalculatedTaxCollection()new TaxRuleCollection(), CartPrice::TAX_STATE_NET))
            ->add('shippingCosts', new CalculatedPrice(10, 10, new CalculatedTaxCollection()new TaxRuleCollection()))
            ->add('orderCustomer', [
                'customerId' => $customerId,
                'email' => 'test@example.com',
                'salutationId' => $this->getValidSalutationId(),
                'firstName' => 'Max',
                'lastName' => 'Mustermann',
            ])
            ->add('stateId', $stateId)
            ->add('paymentMethodId', $paymentMethodId)
            ->add('currencyId', Defaults::CURRENCY)
            


    public function testCalculateAddsValidPromotionToCalculatedCart(): void
    {
        $promotionId = $this->getPromotionId();
        $discountItem = $this->getDiscountItem($promotionId);

        $discountItems = new LineItemCollection([$discountItem]);
        $original = new Cart(Uuid::randomHex());

        $productLineItem = new LineItem(Uuid::randomHex(), LineItem::PRODUCT_LINE_ITEM_TYPE);
        $productLineItem->setPrice(new CalculatedPrice(100.0, 100.0, new CalculatedTaxCollection()new TaxRuleCollection()));
        $productLineItem->setStackable(true);

        $toCalculate = new Cart(Uuid::randomHex());
        $toCalculate->add($productLineItem);
        $toCalculate->setPrice(new CartPrice(84.03, 100.0, 100.0, new CalculatedTaxCollection()new TaxRuleCollection(), CartPrice::TAX_STATE_GROSS));

        $this->promotionCalculator->calculate($discountItems$original$toCalculate$this->salesChannelContext, new CartBehavior());
        static::assertCount(2, $toCalculate->getLineItems());
        $promotionLineItems = $toCalculate->getLineItems()->filterType(PromotionProcessor::LINE_ITEM_TYPE);
        static::assertCount(1, $promotionLineItems);

        
$definition = new QuantityPriceDefinition(30, new TaxRuleCollection([new TaxRule(19)]));
        $price1 = $calculator->calculate($definition, Generator::createSalesChannelContext());

        $definition = new QuantityPriceDefinition(30, new TaxRuleCollection([new TaxRule(7)]));
        $price2 = $calculator->calculate($definition, Generator::createSalesChannelContext());

        return new AbsoluteCalculation(
            -6,
            new CalculatedPrice(
                -6,
                -6,
                new CalculatedTaxCollection([
                    new CalculatedTax(-0.48, 19, -3),
                    new CalculatedTax(-0.20, 7, -3),
                ]),
                new TaxRuleCollection([
                    new TaxRule(19, 50),
                    new TaxRule(7, 50),
                ]),
                1
            ),
            new PriceCollection([$price1$price2])
        );
    }
/** * @internal * * @covers \Shopware\Core\Checkout\Cart\Tax\Struct\CalculatedTaxCollection */
class CalculatedTaxCollectionTest extends TestCase
{
    final public const DUMMY_TAX_NAME = 'dummy-tax';

    public function testCollectionIsCountable(): void
    {
        $collection = new CalculatedTaxCollection();
        static::assertCount(0, $collection);
    }

    public function testCountReturnsCorrectValue(): void
    {
        $collection = new CalculatedTaxCollection([
            new CalculatedTax(10.99, 19, 1),
            new CalculatedTax(5.99, 14, 1),
            new CalculatedTax(1.99, 2, 1),
        ]);
        static::assertCount(3, $collection);
    }

        $context = $this->createMock(SalesChannelContext::class);
        $context->method('getContext')->willReturn(Context::createDefaultContext());
        $context->method('getItemRounding')->willReturn(new CashRoundingConfig(2, 0.01, true));

        $positions = new DeliveryPositionCollection();
        $positions->add(
            new DeliveryPosition(
                Uuid::randomHex(),
                new LineItem('test', 'test'),
                1,
                new CalculatedPrice(0, 0, new CalculatedTaxCollection()new TaxRuleCollection()),
                new DeliveryDate(new \DateTime()new \DateTime())
            )
        );

        $shippingMethod = new ShippingMethodEntity();
        $shippingMethod->setTaxType(ShippingMethodEntity::TAX_TYPE_AUTO);
        $delivery = new Delivery(
            $positions,
            new DeliveryDate(new \DateTime()new \DateTime()),
            $shippingMethod,
            new ShippingLocation(new CountryEntity(), null, null),
            
->willReturn($priceDefinitions);

        return $mock;
    }

    public static function createCart(): Cart
    {
        $cart = new Cart('test');
        $cart->setLineItems(
            new LineItemCollection([
                (new LineItem('A', 'product', 'A', 27))
                    ->setPrice(new CalculatedPrice(10, 270, new CalculatedTaxCollection()new TaxRuleCollection(), 27)),
                (new LineItem('B', 'test', 'B', 5))
                    ->setGood(false)
                    ->setPrice(new CalculatedPrice(0, 0, new CalculatedTaxCollection()new TaxRuleCollection())),
            ])
        );
        $cart->setPrice(
            new CartPrice(
                275.0,
                275.0,
                0,
                new CalculatedTaxCollection(),
                

    private function createProductItem(float $price, float $taxRate): LineItem
    {
        $product = new LineItem(Uuid::randomBytes(), LineItem::PRODUCT_LINE_ITEM_TYPE);

        // allow quantity change         $product->setStackable(true);

        $taxValue = $price * ($taxRate / 100.0);

        $calculatedTaxes = new CalculatedTaxCollection();
        $calculatedTaxes->add(new CalculatedTax($taxValue$taxRate$taxValue));

        $product->setPrice(new CalculatedPrice($price$price$calculatedTaxesnew TaxRuleCollection()));

        return $product;
    }
}

                $this->getMinPriceRule(50),
            ]
        );

        $ruleEntity = new RuleEntity();
        $ruleEntity->setId('R1');
        $ruleEntity->setPayload($rules);

        // create our 2 test product line items         $product50 = new LineItem('ABC1', LineItem::PRODUCT_LINE_ITEM_TYPE);
        $product50->setPrice(new CalculatedPrice(50, 50, new CalculatedTaxCollection()new TaxRuleCollection()));

        $productLower50 = new LineItem('ABC2', LineItem::PRODUCT_LINE_ITEM_TYPE);
        $productLower50->setPrice(new CalculatedPrice(49, 49, new CalculatedTaxCollection()new TaxRuleCollection()));

        // create our group with our price rule         // and use it to match both our products         $group = $this->buildGroup(
            self::KEY_PACKAGER_COUNT,
            1,
            self::KEY_SORTER_PRICE_ASC,
            new RuleCollection([$ruleEntity])
        );
static::assertSame($expected$match);
    }

    /** * @return iterable <string, array{CartShippingCostRule, CalculatedPrice, boolean}> */
    public static function getRuleTestData(): iterable
    {
        yield 'operator equals / same shipping cost / match' => [
            new CartShippingCostRule(Rule::OPERATOR_EQ, 8.99),
            new CalculatedPrice(1.0, 8.99, new CalculatedTaxCollection()new TaxRuleCollection()),
            true,
        ];

        yield 'operator equals / different shipping cost / no match' => [
            new CartShippingCostRule(Rule::OPERATOR_EQ, 10),
            new CalculatedPrice(1.0, 8.99, new CalculatedTaxCollection()new TaxRuleCollection()),
            false,
        ];

        yield 'operator not equals / different shipping cost / match' => [
            new CartShippingCostRule(Rule::OPERATOR_NEQ, 10),
            

        $orderId = Uuid::randomHex();
        $stateId = $this->getContainer()->get(InitialStateIdLoader::class)->get(OrderStates::STATE_MACHINE);
        $billingAddressId = Uuid::randomHex();

        $order = [
            'id' => $orderId,
            'itemRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'totalRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'orderNumber' => Uuid::randomHex(),
            'orderDateTime' => (new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
            'price' => new CartPrice(10, 10, 10, new CalculatedTaxCollection()new TaxRuleCollection(), CartPrice::TAX_STATE_NET),
            'shippingCosts' => new CalculatedPrice(10, 10, new CalculatedTaxCollection()new TaxRuleCollection()),
            'orderCustomer' => [
                'customerId' => $this->ids->get('customer'),
                'email' => 'test@example.com',
                'salutationId' => $this->getValidSalutationId(),
                'firstName' => 'Max',
                'lastName' => 'Mustermann',
            ],
            'stateId' => $stateId,
            'paymentMethodId' => $this->getValidPaymentMethodId(),
            'currencyId' => Defaults::CURRENCY,
            
Home | Imprint | This part of the site doesn't use cookies.