PercentagePriceDefinition example

'maxValue' => '55',
                'discountScope' => 'cart',
                'preventCombination' => false,
                'exclusions' => [],
                'groupId' => '',
                'setGroups' => [],
            ],
            'good' => false,
            'removable' => true,
            'stackable' => false,
            'price' => new CalculatedPrice(-1.1, -1.1, new CalculatedTaxCollection()new TaxRuleCollection(), 1),
            'priceDefinition' => new PercentagePriceDefinition(-5),
            'unitPrice' => -1.1,
            'totalPrice' => -1.1,
            'position' => 2,
            'description' => 'Test',
            'type' => PromotionProcessor::LINE_ITEM_TYPE,
        ];

        /** @var EntityRepository $orderRepository */
        $orderRepository = $this->getContainer()->get('order.repository');

        $orderRepository->create($orderData$context);
    }
public function testPercentagePrice(): 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 PercentagePriceDefinition(-10));

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

                return new PercentagePriceDefinition($decoded['percentage']$rules);
        }

        throw new InvalidPriceFieldTypeException($decoded['type']);
    }

    private function validateRules(array $data, string $basePath): ConstraintViolationList
    {
        $violationList = new ConstraintViolationList();
        /** @var string|null $type */
        $type = null;
        if (\array_key_exists('_name', $data)) {
            
$uniqueKey = 'promotion-' . $code;
        $item = new LineItem($uniqueKey, LineItem::PROMOTION_LINE_ITEM_TYPE);
        $item->setLabel($uniqueKey);
        $item->setGood(false);

        // this is used to pass on the code for later usage         $item->setReferencedId($code);

        // this is important to avoid any side effects when calculating the cart         // a percentage of 0,00 will just do nothing         $item->setPriceDefinition(new PercentagePriceDefinition(0));

        return $item;
    }

    public function update(LineItem $lineItem, array $data, SalesChannelContext $context): void
    {
        throw new \RuntimeException(sprintf('You cannot update a line item of type "%s"', $lineItem->getType()));
    }
}
$calculator = new AbsolutePriceCalculator(
            new QuantityPriceCalculator(
                new GrossPriceCalculator($taxCalculator$rounding),
                new NetPriceCalculator($taxCalculator$rounding),
            ),
            new PercentageTaxRuleBuilder()
        );

        $discountCalculator = new DiscountAbsoluteCalculator($calculator);

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

        static::expectException(InvalidPriceDefinitionException::class);

        $discountCalculator->calculate($discountnew DiscountPackageCollection()$context);
    }

    /** * @return iterable<string, float[]> */
    public static function priceProvider(): iterable
    {
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']),
        };
    }
}
/** * @param float|PriceCollection|string|int|null $value */
    private function buildDiscountDefinition(string $type$value, string $key): PriceDefinitionInterface
    {
        if ($type === PercentagePriceDefinition::TYPE) {
            if ($value instanceof PriceCollection) {
                throw CartException::invalidPercentageDiscount($key);
            }
            $value = FloatComparator::cast((float) $value);

            return new PercentagePriceDefinition(abs($value) * -1);
        }
        if ($type !== AbsolutePriceDefinition::TYPE) {
            throw CartException::discountTypeNotSupported($key$type);
        }
        if (!$value instanceof PriceCollection) {
            throw CartException::absoluteDiscountMissingPriceCollection($key);
        }
        if (!$value->has(Defaults::CURRENCY)) {
            throw CartException::missingDefaultPriceCollectionForDiscount($key);
        }

        


        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),
        ];

        $customFieldsRule = new LineItemCustomFieldRule(
            LineItemCustomFieldRule::OPERATOR_EQ,
            [
        $uniqueKey = self::PLACEHOLDER_PREFIX . $code;

        $item = new LineItem($uniqueKey, PromotionProcessor::LINE_ITEM_TYPE);
        $item->setLabel($uniqueKey);
        $item->setGood(false);

        // this is used to pass on the code for later usage         $item->setReferencedId($code);

        // this is important to avoid any side effects when calculating the cart         // a percentage of 0,00 will just do nothing         $item->setPriceDefinition(new PercentagePriceDefinition(0));

        return $item;
    }

    /** * Builds a new Line Item for the provided discount and its promotion. * It will automatically reference all provided "product" item Ids within the payload. * * @throws CartException * @throws UnknownPromotionDiscountTypeException */
    


    public function testEncodeConstraintViolation(): void
    {
        static::expectException(WriteConstraintViolationException::class);

        $rule = new LineItemListPriceRule();
        $rule->assign(['operator' => Rule::OPERATOR_EQ]);

        $this->ruleConditionRegistry->method('getRuleInstance')->willReturn(new LineItemListPriceRule());

        $definition = new PercentagePriceDefinition(10, $rule);
        $writeContext = WriteContext::createFromContext(Context::createDefaultContext());

        iterator_to_array($this->fieldSerializer->encode(
            new PriceDefinitionField('test', 'test'),
            new EntityExistence('', [], false, false, false, []),
            new KeyValuePair('test', $definition, true),
            new WriteParameterBag($this->createMock(CurrencyDefinition::class)$writeContext, '', new WriteCommandQueue())
        ));
    }

    public function testEncodeDecodeWithEmptyOperatorCondition(): void
    {

    public function testDefaultPriceIsEmpty(): void
    {
        $builder = new PromotionItemBuilder();

        $item = $builder->buildPlaceholderItem('CODE-123');

        $expectedPriceDefinition = new PercentagePriceDefinition(0);

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

    /** * This one is the most important test. * It asserts that our applied code is added to the expected property referenceId of the line item. * When it is converted into a real promotion line item, this code is being used * to fetch that promotion. * * @group promotions */

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

        $this->priceDefinition = new PercentagePriceDefinition($percentage);
        $this->removable = true;
    }
}


    private function buildSurchargeDefinition(string $type, float|PriceCollection|string|int $value, string $key): PriceDefinitionInterface
    {
        if ($type === PercentagePriceDefinition::TYPE) {
            if ($value instanceof PriceCollection) {
                throw CartException::invalidPercentageSurcharge($key);
            }

            $value = FloatComparator::cast((float) $value);

            return new PercentagePriceDefinition(abs($value));
        }
        if ($type !== AbsolutePriceDefinition::TYPE) {
            throw CartException::surchargeTypeNotSupported($key$type);
        }
        if (!$value instanceof PriceCollection) {
            throw CartException::absoluteSurchargeMissingPriceCollection($key);
        }
        if (!$value->has(Defaults::CURRENCY)) {
            throw CartException::missingDefaultPriceCollectionForSurcharge($key);
        }

        
$expected = new DiscountPackageCollection([
            new DiscountPackage(
                new LineItemQuantityCollection([
                    new LineItemQuantity($matchingLineItem->getId(), 1),
                    new LineItemQuantity($matchingLineItem->getId(), 1),
                ])
            ),
        ]);

        static::assertEquals($expected$items);

        $priceDefinition = new PercentagePriceDefinition(42, new LineItemRule(Rule::OPERATOR_EQ, [Uuid::randomHex()]));
        $discount = new DiscountLineItem('foo', $priceDefinition['discountScope' => 'foo', 'discountType' => 'bar'], null);

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

        static::assertEquals(new DiscountPackageCollection([])$items);
    }
}
$currencyFactor = random_int(0, mt_getrandmax()) / mt_getrandmax();

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

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

        $expectedPriceDefinition = new PercentagePriceDefinition(-10, null);

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

    /** * This test verifies that we get a correct absolute price * definition if our promotion is based on absolute values. * Also, we must not have a filter rule for this, if our eligible item ID list is empty. * * @group promotions * * @throws CartException * @throws UnknownPromotionDiscountTypeException */
Home | Imprint | This part of the site doesn't use cookies.