getAmount example

use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRule;
use Shopware\Core\Checkout\Cart\Tax\Struct\TaxRuleCollection;
use Shopware\Core\Framework\Log\Package;

#[Package('checkout')] class TaxCalculator
{
    public function calculateGross(float $netPrice, TaxRuleCollection $rules): float
    {
        $taxes = $this->calculateNetTaxes($netPrice$rules);

        return $netPrice + $taxes->getAmount();
    }

    public function calculateGrossTaxes(float $price, TaxRuleCollection $rules): CalculatedTaxCollection
    {
        $taxes = [];
        foreach ($rules as $rule) {
            $taxes[] = $this->calculateTaxFromGrossPrice($price$rule);
        }

        return new CalculatedTaxCollection($taxes);
    }

    
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());
        }

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

            
yield [self::getFiftyPercentageCalculation()];
        yield [self::regression_next_12270()];
    }

    private static function regression_next_12270(): PercentageCalculation
    {
        $calculator = self::createQuantityPriceCalculator();

        $priceDefinition = new QuantityPriceDefinition(10.40, new TaxRuleCollection([new TaxRule(21, 100)]), 1);
        $price = $calculator->calculate($priceDefinition, Generator::createSalesChannelContext());
        static::assertSame(10.40, $price->getTotalPrice());
        static::assertSame(1.80, $price->getCalculatedTaxes()->getAmount());

        $priceDefinition = new QuantityPriceDefinition(104.00, new TaxRuleCollection([new TaxRule(21, 100)]), 1);
        $price = $calculator->calculate($priceDefinition, Generator::createSalesChannelContext());
        static::assertSame(104.00, $price->getTotalPrice());
        static::assertSame(18.05, $price->getCalculatedTaxes()->getAmount());

        return new PercentageCalculation(
            -10,
            new CalculatedPrice(
                -10.4,
                -10.4,
                
$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());
        }

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

            
// add as long as the minimum package value is not reached             if ($currentPackageSum >= $minPackageValue) {
                break;
            }

            // add the item to our result             // with the current quantity             $result->addItem($lineItem->getId()$lineItem->getQuantity());

            $grossPrice = $lineItem->getPrice()->getUnitPrice();

            $netPrice = $grossPrice - $lineItem->getPrice()->getCalculatedTaxes()->getAmount();

            $currentPackageSum += $lineItem->getQuantity() * $netPrice;
        }

        // if we have less results than our max value         // return an empty list, because that is not a valid group         if ($currentPackageSum < $minPackageValue) {
            return new LineItemGroup();
        }

        return $result;
    }
public function getCurrency()
    {
        return $this->currency;
    }
}

class MoneyDataMapper implements DataMapperInterface
{
    public function mapDataToForms(mixed $viewData, \Traversable $forms): void
    {
        $forms = iterator_to_array($forms);
        $forms['amount']->setData($viewData ? $viewData->getAmount() : 0);
        $forms['currency']->setData($viewData ? $viewData->getCurrency() : 'EUR');
    }

    public function mapFormsToData(\Traversable $forms, mixed &$viewData): void
    {
        $forms = iterator_to_array($forms);

        $amount = $forms['amount']->getData();
        if (!is_numeric($amount)) {
            $failure = new TransformationFailedException('Expected numeric value');
            $failure->setInvalidMessage('Money amount should be numeric. {{ amount }} is invalid.', ['{{ amount }}' => json_encode($amount)]);

            
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(
            [
                $this->ids->get('line-item-1') => new CalculatedTaxCollection([
                    new CalculatedTax(
                        
private function isReachedCountryTaxFreeAmount(
        SalesChannelContext $context,
        CountryEntity $country,
        float $cartNetAmount = 0,
        string $taxFreeType = CountryDefinition::TYPE_CUSTOMER_TAX_FREE
    ): bool {
        $countryTaxFreeLimit = $taxFreeType === CountryDefinition::TYPE_CUSTOMER_TAX_FREE ? $country->getCustomerTax() : $country->getCompanyTax();
        if (!$countryTaxFreeLimit->getEnabled()) {
            return false;
        }

        $countryTaxFreeLimitAmount = $countryTaxFreeLimit->getAmount() / $this->fetchCurrencyFactor($countryTaxFreeLimit->getCurrencyId()$context);

        $currency = $context->getCurrency();

        $cartNetAmount /= $this->fetchCurrencyFactor($currency->getId()$context);

        // currency taxFreeAmount === 0.0 mean currency taxFreeFrom is disabled         return $currency->getTaxFreeFrom() === 0.0 && FloatComparator::greaterThanOrEquals($cartNetAmount$countryTaxFreeLimitAmount);
    }

    private function fetchCurrencyFactor(string $currencyId, SalesChannelContext $context): float
    {
        
// prepare a percentage promotion with 100% OFF         // with a set group of the 2 cheapest items.         $promotionBuilder = $this->createPromotionFixtureBuilder($container)
            ->addSetGroup('COUNT', 2, 'PRICE_ASC')
            ->setCode($code)
            ->addDiscount(PromotionDiscountEntity::SCOPE_SET, PromotionDiscountEntity::TYPE_PERCENTAGE, 100.0, false, null);
        $cart = $this->getCart($promotionBuilder$productId1$productId2$code);

        static::assertEquals(65.0, $cart->getPrice()->getPositionPrice(), 'Position Total Price is wrong');
        static::assertEquals(65.0, $cart->getPrice()->getTotalPrice(), 'Total Price is wrong');
        static::assertEquals(54.62, $cart->getPrice()->getNetPrice(), 'Net Price is wrong');
        static::assertEquals(10.38, $cart->getPrice()->getCalculatedTaxes()->getAmount(), 'Taxes are wrong');
    }

    /** * This test verifies that we give correct absolute discounts if the * set group consists of different line items and custom quantities. * We have a package of 2 of the cheapest items. * We only have 2 different products in our cart with total quantity 3 (1x and 2x). * Our cheapest 2 items are 1x the item with quantity 1 and then only 1x * the item of the products with quantity 2. * We give 50 EUR discount on that package, which means the customer has to * pay (product 1 + product 2 - 50) + product 2. * * @group promotions * * @throws CartException */
$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 */
->first();

        // check that the live entity contains the original price         static::assertInstanceOf(ArrayEntity::class$entity);

        /** @var CalculatedPrice $livePrice */
        $livePrice = $entity->get('price');
        static::assertInstanceOf(CalculatedPrice::class$livePrice);

        static::assertEquals(100.20, $livePrice->getUnitPrice());
        static::assertEquals(100.30, $livePrice->getTotalPrice());
        static::assertEquals(0.38, $livePrice->getCalculatedTaxes()->getAmount());

        // check that the version entity is updated with the new price         /** @var Entity $entity */
        $entity = $repository
            ->search(new Criteria([$id])$versionContext)
            ->first();

        static::assertInstanceOf(ArrayEntity::class$entity);

        /** @var CalculatedPrice $versionPrice */
        $versionPrice = $entity->get('price');
        
// create product and add to cart         $cart = $this->addProduct($productId, 1, $cart$this->cartService, $this->context);
        // create product and add to cart         $cart = $this->addProduct($productTwoId, 1, $cart$this->cartService, $this->context);

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

        static::assertEquals(52, $cart->getDeliveries()->getShippingCosts()->sum()->getTotalPrice());
        static::assertEquals(3, $cart->getLineItems()->count());
        static::assertEquals(2, $cart->getDeliveries()->count());
        static::assertEquals(5.85, $cart->getDeliveries()->getShippingCosts()->sum()->getCalculatedTaxes()->getAmount());
    }

    /** * helper function for deleting our created promotions * * @throws InconsistentCriteriaIdsException */
    private function deletePromotions(): void
    {
        $idSearchResult = $this->promotionRepository->searchIds(new Criteria()$this->context->getContext());
        $data = [];
        
$successCallback($order);
    }

    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 {
                
$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()
                );

                $doc = new RenderedDocument(
                    
if ($result->getCartPriceTaxes()) {
            $price = $this->applyCartPriceTaxes($price$result->getCartPriceTaxes()$context);
        }

        $cart->setPrice($price);
    }

    private function applyCartPriceTaxes(CartPrice $price, CalculatedTaxCollection $taxes, SalesChannelContext $context): CartPrice
    {
        $netPrice = $price->getNetPrice();
        $grossPrice = $price->getTotalPrice();
        $taxSum = $taxes->getAmount();

        if ($context->getTaxState() === CartPrice::TAX_STATE_NET) {
            $grossPrice = $this->rounding->cashRound(
                $netPrice + $taxSum,
                $context->getTotalRounding()
            );
        }

        if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
            $netPrice = $this->rounding->cashRound(
                $grossPrice - $taxSum,
                
Home | Imprint | This part of the site doesn't use cookies.