AbsolutePriceDefinition example

$context = Generator::createSalesChannelContext();

        $matchingLineItem = (new LineItem(Uuid::randomHex(), LineItem::PRODUCT_LINE_ITEM_TYPE, Uuid::randomHex(), 2))->setStackable(true);
        $cart = new Cart('foo');
        $cart->setLineItems(
            new LineItemCollection([
                $matchingLineItem,
                (new LineItem(Uuid::randomHex(), LineItem::PRODUCT_LINE_ITEM_TYPE, Uuid::randomHex()))->setStackable(true),
            ])
        );

        $priceDefinition = new AbsolutePriceDefinition(42, new LineItemRule(Rule::OPERATOR_EQ, [$matchingLineItem->getReferencedId() ?? '']));
        $discount = new DiscountLineItem('foo', $priceDefinition['discountScope' => 'foo', 'discountType' => 'bar'], null);

        $packager = new CartScopeDiscountPackager();
        $items = $packager->getMatchingItems($discount$cart$context);

        $expected = new DiscountPackageCollection([
            new DiscountPackage(
                new LineItemQuantityCollection([
                    new LineItemQuantity($matchingLineItem->getId(), 1),
                    new LineItemQuantity($matchingLineItem->getId(), 1),
                ])
            ),
public function testCalculateAbsolutePrice(): void
    {
        $cart = new Cart('test');

        $lineItem = (new LineItem('A', 'test', null, 2))
            ->setPriceDefinition(new QuantityPriceDefinition(100, new TaxRuleCollection([]), 2));

        $cart->add($lineItem);

        $lineItem = (new LineItem('B', 'test'))
            ->setPriceDefinition(new AbsolutePriceDefinition(-15));

        $cart->add($lineItem);

        $calculated = $this->calculator->calculate($cart->getLineItems()$this->context, new CartBehavior());

        static::assertCount(2, $calculated);
        static::assertInstanceOf(LineItem::class$calculated->get('A'));
        static::assertInstanceOf(CalculatedPrice::class$calculated->get('A')->getPrice());
        static::assertSame(200.0, $calculated->get('A')->getPrice()->getTotalPrice());
        static::assertInstanceOf(LineItem::class$calculated->get('B'));
        static::assertInstanceOf(CalculatedPrice::class$calculated->get('B')->getPrice());
        
#[Package('checkout')] class PriceDefinitionFactory
{
    public function factory(Context $context, array $priceDefinition, string $lineItemType): PriceDefinitionInterface
    {
        if (!isset($priceDefinition['type'])) {
            throw new InvalidPriceFieldTypeException('none');
        }

        return match ($priceDefinition['type']) {
            QuantityPriceDefinition::TYPE => QuantityPriceDefinition::fromArray($priceDefinition),
            AbsolutePriceDefinition::TYPE => new AbsolutePriceDefinition((float) $priceDefinition['price']),
            PercentagePriceDefinition::TYPE => new PercentagePriceDefinition($priceDefinition['percentage']),
            default => throw new InvalidPriceFieldTypeException($priceDefinition['type']),
        };
    }
}
$calculator = new AbsolutePriceCalculator(
            new QuantityPriceCalculator(
                new GrossPriceCalculator($taxCalculator$rounding),
                new NetPriceCalculator($taxCalculator$rounding),
            ),
            new PercentageTaxRuleBuilder()
        );

        $discountCalculator = new DiscountAbsoluteCalculator($calculator);

        $priceDefinition = new AbsolutePriceDefinition($discountIn);
        $discount = new DiscountLineItem('foo', $priceDefinition['discountScope' => 'foo', 'discountType' => 'bar'], null);

        $lineItem = new LineItem(Uuid::randomHex(), LineItem::PRODUCT_LINE_ITEM_TYPE, Uuid::randomHex(), 2);
        $lineItem->setPrice(new CalculatedPrice($packageSum / 2, $packageSumnew CalculatedTaxCollection()new TaxRuleCollection()));

        $package = new DiscountPackage(
            new LineItemQuantityCollection([
                new LineItemQuantity($lineItem->getId(), 1),
                new LineItemQuantity($lineItem->getId(), 1),
            ])
        );
        
private function getDiscountItem(string $promotionId): LineItem
    {
        $discountItemToBeExcluded = new LineItem(Uuid::randomHex(), PromotionProcessor::LINE_ITEM_TYPE);
        $discountItemToBeExcluded->setRequirement(null);
        $discountItemToBeExcluded->setPayloadValue('discountScope', PromotionDiscountEntity::SCOPE_CART);
        $discountItemToBeExcluded->setPayloadValue('discountType', PromotionDiscountEntity::TYPE_ABSOLUTE);
        $discountItemToBeExcluded->setPayloadValue('exclusions', []);
        $discountItemToBeExcluded->setPayloadValue('promotionId', $promotionId);
        $discountItemToBeExcluded->setReferencedId($promotionId);
        $discountItemToBeExcluded->setLabel('PHPUnit');
        $discountItemToBeExcluded->setPriceDefinition(new AbsolutePriceDefinition(-10.0));

        return $discountItemToBeExcluded;
    }
}
if ($description !== null && !\is_string($description)) {
            throw RoutingException::invalidRequestParameter('description');
        }

        $lineItem->setLabel($label);
        $lineItem->setDescription($description);
        $lineItem->setRemovable($removeable);
        $lineItem->setStackable($stackable);
        $lineItem->setPayload($payload);

        $lineItem->setPriceDefinition(
            new AbsolutePriceDefinition(
                (float) $priceDefinition['price'],
                new LineItemOfTypeRule(Rule::OPERATOR_NEQ, $type)
            )
        );

        $this->recalculationService->addCustomLineItem($orderId$lineItem$context);

        return new Response(null, Response::HTTP_NO_CONTENT);
    }

    #[Route(path: '/api/_action/order/{orderId}/lineItem', name: 'api.action.order.add-line-item', methods: ['POST'])]
if (!\array_key_exists('type', $decoded)) {
            throw new InvalidPriceFieldTypeException('none');
        }

        switch ($decoded['type']) {
            case QuantityPriceDefinition::TYPE:
                return QuantityPriceDefinition::fromArray($decoded);
            case AbsolutePriceDefinition::TYPE:
                $rules = (\array_key_exists('filter', $decoded) && $decoded['filter'] !== null) ? $this->decodeRule($decoded['filter']) : null;

                return new AbsolutePriceDefinition($decoded['price']$rules);
            case CurrencyPriceDefinition::TYPE:
                $rules = (\array_key_exists('filter', $decoded) && $decoded['filter'] !== null) ? $this->decodeRule($decoded['filter']) : null;

                $collection = new PriceCollection();
                foreach ($decoded['price'] as $price) {
                    $collection->add(new Price($price['currencyId'](float) $price['net'](float) $price['gross'](bool) $price['linked']));
                }

                return new CurrencyPriceDefinition($collection$rules);
            case PercentagePriceDefinition::TYPE:
                $rules = \array_key_exists('filter', $decoded) && $decoded['filter'] !== null ? $this->decodeRule($decoded['filter']) : null;

                
$persister = new OrderPersister($repository$this->orderConverter);

        $persister->persist($cart$this->getSalesChannelContext());
    }

    public function testSaveWithMissingLabel(): void
    {
        $cart = new Cart('a-b-c');
        $cart->add(
            (new LineItem('test', LineItem::CREDIT_LINE_ITEM_TYPE))
                ->setPriceDefinition(new AbsolutePriceDefinition(1))
        );

        $context = $this->getContainer()->get(SalesChannelContextFactory::class)
            ->create(Uuid::randomHex(), TestDefaults::SALES_CHANNEL);

        $processedCart = $this->cartProcessor->process($cart$contextnew CartBehavior());

        $exception = null;

        try {
            $this->orderPersister->persist($processedCart$context);
        }
$taxForCustomItem = 20;

        $productLineItem = new LineItem($productId, LineItem::PRODUCT_LINE_ITEM_TYPE, $productId, 1);
        $taxRulesCustomItem = new TaxRuleCollection([new TaxRule($taxForCustomItem)]);
        $customLineItem = (new LineItem($customItemId, LineItem::CUSTOM_LINE_ITEM_TYPE, $customItemId, 1))
            ->setLabel('custom')
            ->setPriceDefinition(new QuantityPriceDefinition(200, $taxRulesCustomItem, 2));

        $creditLineItem = (new LineItem($creditId, LineItem::CREDIT_LINE_ITEM_TYPE, $creditId, 1))
            ->setLabel('credit')
            ->setPriceDefinition(new AbsolutePriceDefinition(-100));

        $cart->addLineItems(new LineItemCollection([$productLineItem$customLineItem$creditLineItem]));

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

        static::assertCount(3, $calculated->getLineItems());

        $creditLineItem = $calculated->getLineItems()->filterType(LineItem::CREDIT_LINE_ITEM_TYPE)->first();
        static::assertInstanceOf(LineItem::class$creditLineItem);
        static::assertInstanceOf(CalculatedPrice::class$creditLineItem->getPrice());
        static::assertCount(2, $creditCalculatedTaxes = $creditLineItem->getPrice()->getCalculatedTaxes()->getElements());

        

        }

        // our promotion values are always negative values.         // either type percentage or absolute needs to be negative to get         // automatically subtracted within the calculation process         $promotionValue = -abs($discount->getValue());

        switch ($discount->getType()) {
            case PromotionDiscountEntity::TYPE_ABSOLUTE:
                $promotionValue = -$this->getCurrencySpecificValue($discount$discount->getValue()$currencyId$currencyFactor);
                $promotionDefinition = new AbsolutePriceDefinition($promotionValue$targetFilter);

                break;

            case PromotionDiscountEntity::TYPE_PERCENTAGE:
                $promotionDefinition = new PercentagePriceDefinition($promotionValue$targetFilter);

                break;

            case PromotionDiscountEntity::TYPE_FIXED:
            case PromotionDiscountEntity::TYPE_FIXED_UNIT:
                $promotionValue = -abs($this->getCurrencySpecificValue($discount$discount->getValue()$currencyId$currencyFactor));
                
/** * @param array<int, int> $creditPrices */
    private function generateCreditItems(Cart $cart, array $creditPrices): Cart
    {
        $lineItems = [];

        foreach ($creditPrices as $price) {
            $creditId = Uuid::randomHex();
            $creditLineItem = (new LineItem($creditId, LineItem::CREDIT_LINE_ITEM_TYPE, $creditId, 1))
                ->setLabel('credit' . $price)
                ->setPriceDefinition(new AbsolutePriceDefinition($price));

            $lineItems[] = $creditLineItem;
        }

        $cart->setRuleIds($this->salesChannelContext->getRuleIds());

        return $this->cartService->add($cart$lineItems$this->salesChannelContext);
    }

    private function createShippingMethod(string $priceRuleId): string
    {
        
$currencyFactor = random_int(0, mt_getrandmax()) / mt_getrandmax();

        $discount = new PromotionDiscountEntity();
        $discount->setId('D5');
        $discount->setType(PromotionDiscountEntity::TYPE_ABSOLUTE);
        $discount->setValue(50);
        $discount->setScope(PromotionDiscountEntity::SCOPE_CART);

        $item = $builder->buildDiscountLineItem('', $this->promotion, $discount, 'C1', $currencyFactor);

        $expectedPriceDefinition = new AbsolutePriceDefinition(-50 * $currencyFactor, null);

        static::assertEquals($expectedPriceDefinition$item->getPriceDefinition());
    }

    /** * This test verifies that the correct discount filter * is set in the discountItemBuilder * * @group promotions */
    public function testDiscountTargetFilter(): void
    {
new OrRule([
                new CurrencyRule(CurrencyRule::OPERATOR_EQ, [Defaults::CURRENCY]),
            ]),
            new CurrencyRule(CurrencyRule::OPERATOR_EQ, [Defaults::CURRENCY]),
        ]);

        yield 'Test quantity price definition' => [
            new QuantityPriceDefinition(100, new TaxRuleCollection([new TaxRule(19, 50)new TaxRule(7, 50)]), 3),
        ];

        yield 'Test absolute price definition' => [
            new AbsolutePriceDefinition(20, $rule),
        ];

        yield 'Test percentage price definition' => [
            new PercentagePriceDefinition(-20, $rule),
        ];

        yield 'Test currency price definition' => [
            new CurrencyPriceDefinition(new PriceCollection([
                new Price(Defaults::CURRENCY, 100, 200, false),
                new Price(Uuid::randomHex(), 200, 300, true),
            ])$rule),
        ];
Home | Imprint | This part of the site doesn't use cookies.