Price example


#[Package('checkout')] class AbsoluteItem extends LineItem
{
    public function __construct(
        float $price,
        ?string $id = null
    ) {
        parent::__construct($id ?? Uuid::randomHex(), LineItem::DISCOUNT_LINE_ITEM);

        $this->priceDefinition = new CurrencyPriceDefinition(new PriceCollection([
            new Price(Defaults::CURRENCY, $price$price, false),
        ]));
        $this->removable = true;
    }
}
static::assertInstanceOf(CalculatedPrice::class$price);

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

    public static function taxStateWillBeUsedProvider(): \Generator
    {
        $product = (new PartialEntity())->assign([
            'taxId' => Uuid::randomHex(),
            'price' => new PriceCollection([
                new Price(Defaults::CURRENCY, 10, 20, false),
            ]),
        ]);

        yield 'Gross price will be used for gross state' => [$product, CartPrice::TAX_STATE_GROSS, 20];

        yield 'Net price will be used for net price state' => [$product, CartPrice::TAX_STATE_NET, 10];

        yield 'Net price will be used for tax free state' => [$product, CartPrice::TAX_STATE_FREE, 10];
    }

    public function testEnsureUnitCaching(): void
    {

class PriceFacadeTest extends TestCase
{
    public function testLineItemsGetUpdatePriceDefinition(): void
    {
        $item = new LineItem('test', 'test', 'temp');

        $original = new CalculatedPrice(1, 1, new CalculatedTaxCollection()new TaxRuleCollection());
        $price = new PriceFacade($item$original$this->createMock(ScriptPriceStubs::class)$this->createMock(SalesChannelContext::class));

        $price->change(new PriceCollection([
            new Price(Defaults::CURRENCY, 2, 2, false),
        ]));

        static::assertInstanceOf(QuantityPriceDefinition::class$item->getPriceDefinition());
        static::assertEquals(2, $item->getPriceDefinition()->getPrice());
        static::assertNull($item->getPrice());
    }

    public function testChangesAreAppliedDirectlyForEntities(): void
    {
        $item = new Entity();
        $original = new CalculatedPrice(1, 1, new CalculatedTaxCollection()new TaxRuleCollection());
        


        foreach ($record as $currencyIso => $price) {
            $currency = $this->getCurrencyIdFromIso($currencyIso);

            if ($currency === null || !$this->isValidPrice($price)) {
                continue;
            }

            $listPrice = null;
            if (isset($price['listPrice']) && $this->isValidPrice($price['listPrice'])) {
                $listPrice = new Price($currency(float) $price['listPrice']['net'](float) $price['listPrice']['gross'](bool) ($price['listPrice']['linked'] ?? false));
            }

            $priceStruct = new Price($currency(float) $price['net'](float) $price['gross'](bool) ($price['linked'] ?? false)$listPrice);
            $prices[$currency] = $priceStruct->jsonSerialize();

            if (isset($prices[$currency]['listPrice']) && $prices[$currency]['listPrice'] instanceof Price) {
                $prices[$currency]['listPrice'] = $prices[$currency]['listPrice']->jsonSerialize();
            }
        }

        if (empty($prices)) {
            

    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()),
            
static::assertTrue($rule->match($ruleScope));
    }

    private function createLineItem(float $price): LineItem
    {
        $lineItem = new LineItem(
            Uuid::randomHex(),
            LineItem::PRODUCT_LINE_ITEM_TYPE,
            Uuid::randomHex()
        );

        $price = new Price('currency-id', $price$price, false);

        $lineItem->setPayloadValue('purchasePrices', json_encode($price, \JSON_THROW_ON_ERROR));

        return $lineItem;
    }
}
$this->repository->create([$data]$this->context);

        /** @var ProductEntity $product */
        $product = $this->repository
            ->search(new Criteria([$id])$this->context)
            ->get($id);

        static::assertInstanceOf(PriceCollection::class$product->getPrice());

        static::assertEquals(
            new Price(Defaults::CURRENCY, 10, 15, false),
            $product->getPrice()->getCurrencyPrice(Defaults::CURRENCY)
        );
    }

    public function testWriteMultipleCurrencyPrices(): void
    {
        $id = Uuid::randomHex();

        $this->getContainer()->get('currency.repository')->create(
            [
                [
                    


        static::assertFalse($match);
    }

    private function createLineItemWithPurchasePrice(
        float $purchasePriceNet = 0,
        float $purchasePriceGross = 0
    ): LineItem {
        return $this->createLineItem()->setPayloadValue(
            'purchasePrices',
            json_encode(new Price(
                Defaults::CURRENCY,
                $purchasePriceNet,
                $purchasePriceGross,
                false
            ), \JSON_THROW_ON_ERROR)
        );
    }
}

        $sumByTaxes = $this->sumByTax($prices);

        $total = array_sum($sumByTaxes);

        $taxes = [];

        foreach ($sumByTaxes as $taxRate => $price) {
            $taxRate = (float) $taxRate;

            if ((float) $price === 0.0) {
                $taxes[] = new Price(0.0, 0.0, $taxRate, 0.0);
                continue;
            }

            $proportion = $price / $total * 100;

            $priceForTax = $discount / 100 * $proportion;

            $net = $priceForTax / ((100 + $taxRate) / 100);

            $tax = $net * ($taxRate / 100);

            
/** * Returns prices from invoice positions * * @return Price[] */
    private function getPricePositions(): array
    {
        $prices = [];

        foreach ($this->_positions as $position) {
            if ((int) $position['modus'] === CartPositionsMode::PRODUCT) {
                $prices[] = new Price($position['amount']$position['amount_netto'](float) $position['tax_rate'], null);
            }
        }

        return $prices;
    }

    /** * This method overwrites all attribute values with the translated value * in case there is one. * * @param array<string, string> $position * @param array<string, string> $translation * * @return array<string, string> */
// used for nested hydration (example cheapest-price-hydrator)         if (\is_string($value)) {
            $value = json_decode($value, true, 512, \JSON_THROW_ON_ERROR);
        }

        $collection = new PriceCollection();

        foreach ($value as $row) {
            if ((!isset($row['listPrice']) || !isset($row['listPrice']['gross'])) && (!isset($row['regulationPrice']) || !isset($row['regulationPrice']['gross']))) {
                $collection->add(
                    new Price($row['currencyId'](float) $row['net'](float) $row['gross'](bool) $row['linked'])
                );

                continue;
            }

            $listPrice = $regulationPrice = null;
            if (isset($row['listPrice']) && isset($row['listPrice']['gross'])) {
                $data = $row['listPrice'];
                $listPrice = new Price(
                    $row['currencyId'],
                    (float) $data['net'],
                    

    public function testChange(string $currencyKey, string $taxState, float $unit, float $tax): void
    {
        $ids = new IdsCollection([
            'default' => Defaults::CURRENCY,
            'usd' => Uuid::randomHex(),
        ]);

        $price = $this->rampUpPriceFacade($ids$currencyKey$taxState);

        $update = new PriceCollection([
            new Price(Defaults::CURRENCY, 2, 5, false),
            new Price($ids->get('usd'), 1, 4, false),
        ]);

        $price->change($update);

        static::assertEquals($unit$price->getUnit());
        static::assertEquals($tax$price->getTaxes()->getAmount());
    }

    public function testChangeWithPriceFacade(): void
    {
        

        $this->currencyRepository = $this->getContainer()->get(CurrencyDefinition::ENTITY_NAME . '.repository');
    }

    public function testSerializePrice(): void
    {
        $priceField = new PriceField('price', 'price');

        $priceSerializer = new PriceSerializer($this->currencyRepository);
        $config = new Config([][][]);

        $price = new Price(Defaults::CURRENCY, 10.0, 10.0, false);

        $expectedSerialized = [
            'EUR' => [
                'currencyId' => Defaults::CURRENCY,
                'extensions' => [],
                'gross' => 10.0,
                'linked' => false,
                'listPrice' => null,
                'net' => 10.0,
                'percentage' => null,
                'regulationPrice' => null,
            ],
$products = $this->repository->search($criteria$context);
        static::assertTrue($products->has($id));

        /** @var ProductEntity $product */
        $product = $products->get($id);

        static::assertCount(2, $product->getPrices());

        /** @var ProductPriceEntity $price */
        $price = $product->getPrices()->get($id);
        static::assertEquals($ruleA$price->getRuleId());
        static::assertEquals(new Price(Defaults::CURRENCY, 4000, 5000, false)$price->getPrice()->get(Defaults::CURRENCY));

        static::assertEquals(1, $price->getQuantityStart());
        static::assertEquals(20, $price->getQuantityEnd());

        $id3 = Uuid::randomHex();

        $data = [
            'id' => $id,
            'prices' => [
                [
                    'id' => $id3,
                    
$object = new CheapestPrice();
        $object->setRuleId($cheapest['rule_id']);
        $object->setVariantId($cheapest['variant_id']);
        $object->setParentId($cheapest['parent_id']);
        $object->setHasRange($hasRange);
        $object->setPurchase($cheapest['purchase_unit'] ? (float) $cheapest['purchase_unit'] : null);
        $object->setReference($cheapest['reference_unit'] ? (float) $cheapest['reference_unit'] : null);
        $object->setUnitId($cheapest['unit_id'] ?? null);

        $prices = [];

        $blueprint = new Price('', 1, 1, true);

        foreach ($cheapest['price'] as $row) {
            $price = clone $blueprint;
            $price->setCurrencyId($row['currencyId']);
            $price->setGross((float) $row['gross']);
            $price->setNet((float) $row['net']);
            $price->setLinked((bool) $row['linked']);

            if (isset($row['listPrice'])) {
                $list = clone $blueprint;

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