setRuleIds example

$this->addCountriesToSalesChannel([$this->getValidCountryIdWithTaxes()]);
        $this->salesChannelContext = $this->getContainer()->get(SalesChannelContextFactory::class)->create(
            Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL,
            [
                SalesChannelContextService::CUSTOMER_ID => $this->customerId,
                SalesChannelContextService::SHIPPING_METHOD_ID => $shippingMethodId,
                SalesChannelContextService::PAYMENT_METHOD_ID => $paymentMethodId,
            ]
        );

        $this->salesChannelContext->setRuleIds([$priceRuleId]);
    }

    public function testPersistOrderAndConvertToCart(): void
    {
        $parentProductId = Uuid::randomHex();
        $childProductId = Uuid::randomHex();
        // to test the sorting, the parentId has to be greater than the rootId         $parentProductId = substr_replace($parentProductId, '0', 0, 1);
        $rootProductId = substr_replace($parentProductId, 'f', 0, 1);

        $cart = $this->generateDemoCart($parentProductId$rootProductId);

        
$response = json_decode((string) $this->browser->getResponse()->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        static::assertSame(200, $this->browser->getResponse()->getStatusCode());
        static::assertSame(750, $response['lineItems'][0]['price']['unitPrice']);
    }

    public function testUpdateCartShouldShowAdvancedPriceWithoutPriceDefinition(): void
    {
        $this->enableAdminAccess();

        Context::createDefaultContext()->setRuleIds([
            $this->ids->create('rule-a'),
            $this->ids->create('rule-b'),
        ]);

        $data = [
            'id' => $this->ids->create('product'),
            'productNumber' => $this->ids->get('product'),
            'stock' => 10,
            'name' => 'Test',
            'price' => [
                ['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false],
            ],
$this->validator->validate($this->cart, $errors$context);

        static::assertCount(1, $errors);
        $error = $errors->get('payment-method-blocked-');
        static::assertNotNull($error);
        static::assertStringContainsString('not allowed', $error->getMessage());
    }

    public function testValidateAvailabilityRuleNotMatched(): void
    {
        $context = $this->getSalesChannelContext();
        $context->setRuleIds([]);

        $errors = new ErrorCollection();

        $this->validator->validate($this->cart, $errors$context);

        static::assertCount(1, $errors);
        $error = $errors->get('payment-method-blocked-');
        static::assertNotNull($error);
        static::assertStringContainsString('rule not matching', $error->getMessage());
    }

    
$this->calculateAmount($context$cart);

            $cart->addErrors(
                ...$this->validator->validate($cart$context)
            );

            $cart->setTransactions(
                $this->transactionProcessor->process($cart$context)
            );

            $cart->setRuleIds($context->getRuleIds());

            return $cart;
        }, 'cart');
    }

    private function runProcessors(Cart $original, Cart $cart, SalesChannelContext $context, CartBehavior $behavior): void
    {
        if ($original->getLineItems()->count() <= 0) {
            $cart->addErrors(...array_values($original->getErrors()->getPersistent()->getElements()));

            $cart->setExtensions($original->getExtensions());

            
$this->salesChannelContext = $this->getContainer()->get(SalesChannelContextFactory::class)->create(
            Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL,
            [
                SalesChannelContextService::CUSTOMER_ID => $this->createCustomer(),
                SalesChannelContextService::SHIPPING_METHOD_ID => $shippingMethodId,
                SalesChannelContextService::PAYMENT_METHOD_ID => $paymentMethodId,
            ]
        );

        $this->salesChannelContext->setRuleIds([$priceRuleId]);
        $this->productRepository = $this->getContainer()->get('product.repository');
        $this->creditNoteRenderer = $this->getContainer()->get(CreditNoteRenderer::class);
        $this->cartService = $this->getContainer()->get(CartService::class);
        $this->documentGenerator = $this->getContainer()->get(DocumentGenerator::class);
    }

    /** * @dataProvider creditNoteRendererDataProvider * * @param array<int, int> $possibleTaxes * @param array<int, int> $creditPrices * @param array<string, int> $additionalConfig */
$actionSequences[] = $actionSequence;
            }
        }

        $context = Context::createDefaultContext();
        if ($actionSequencesTrueCase !== []) {
            $condition = new IfSequence();
            $condition->sequenceId = $ids->get('true_case');
            $condition->ruleId = $ids->get('ruleId');

            $context = Context::createDefaultContext();
            $context->setRuleIds([$ids->get('ruleId')]);

            foreach ($actionSequencesTrueCase as $actionSequenceTrueCase) {
                $actionSequence = new ActionSequence();
                $actionSequence->sequenceId = $ids->get($actionSequenceTrueCase);
                $actionSequence->action = $actionSequenceTrueCase;

                $condition->trueCase = $actionSequence;
            }

            $actionSequences[] = $condition;
        }

        
if (!\is_array($content)) {
            throw CartException::tokenNotFound($token);
        }

        $cart = $content['compressed'] ? CacheValueCompressor::uncompress($content['payload']) : unserialize((string) $content['payload']);

        if (!$cart instanceof Cart) {
            throw CartException::deserializeFailed();
        }

        $cart->setToken($token);
        $cart->setRuleIds(json_decode((string) $content['rule_ids'], true, 512, \JSON_THROW_ON_ERROR) ?? []);

        $this->eventDispatcher->dispatch(new CartLoadedEvent($cart$context));

        return $cart;
    }

    /** * @throws InvalidUuidException */
    public function save(Cart $cart, SalesChannelContext $context): void
    {
        
$priceRuleId = Uuid::randomHex();

        $this->salesChannelContext = $this->getContainer()->get(SalesChannelContextFactory::class)->create(
            Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL,
            [
                SalesChannelContextService::CUSTOMER_ID => $this->createCustomer(),
            ]
        );

        $this->salesChannelContext->setRuleIds([$priceRuleId]);
        $this->productRepository = $this->getContainer()->get('product.repository');
        $this->stornoRenderer = $this->getContainer()->get(StornoRenderer::class);
        $this->cartService = $this->getContainer()->get(CartService::class);
        $this->documentGenerator = $this->getContainer()->get(DocumentGenerator::class);
    }

    /** * @dataProvider stornoNoteRendererDataProvider * * @param array<string, string> $additionalConfig */
    


        if ($order->getItemRounding() !== null) {
            $salesChannelContext->setItemRounding($order->getItemRounding());
        }

        if ($order->getTotalRounding() !== null) {
            $salesChannelContext->setTotalRounding($order->getTotalRounding());
        }

        if ($order->getRuleIds() !== null) {
            $salesChannelContext->setRuleIds($order->getRuleIds());
        }

        $event = new SalesChannelContextAssembledEvent($order$salesChannelContext);
        $this->eventDispatcher->dispatch($event);

        return $salesChannelContext;
    }

    private function convertDeliveries(OrderDeliveryCollection $orderDeliveries, LineItemCollection $lineItems): DeliveryCollection
    {
        $cartDeliveries = new DeliveryCollection();

        
// Get customer from USA rule         $ruleCriteria = new Criteria();
        $ruleCriteria->addFilter(new EqualsFilter('name', 'Customers from USA'));

        $ruleRepository = $this->getContainer()->get('rule.repository');

        $ruleId = $ruleRepository->search($ruleCriteria$context->getContext())->first()->getId();

        $this->createCustomPaymentWithRule($context$ruleId);

        // Fake context rules for USA customers         $context->setRuleIds(array_merge($context->getRuleIds()[$ruleId]));

        $page = $this->getPageLoader()->load($request$context);

        static::assertInstanceOf(AccountEditOrderPage::class$page);
        static::assertSame($orderId$page->getOrder()->getId());
        static::assertCount(1, $page->getPaymentMethods());
    }

    public function testShouldSortAvailablePaymentMethodsByPreference(): void
    {
        $request = new Request();
        
$priceRuleId = Uuid::randomHex();

        $this->salesChannelContext = $this->getContainer()->get(SalesChannelContextFactory::class)->create(
            Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL,
            [
                SalesChannelContextService::CUSTOMER_ID => $this->createCustomer(),
            ]
        );

        $this->salesChannelContext->setRuleIds([$priceRuleId]);
        $this->productRepository = $this->getContainer()->get('product.repository');
        $this->invoiceRenderer = $this->getContainer()->get(InvoiceRenderer::class);
        $this->cartService = $this->getContainer()->get(CartService::class);
        self::$deLanguageId = $this->getDeDeLanguageId();
    }

    protected function tearDown(): void
    {
        if (self::$callback instanceof \Closure) {
            $this->getContainer()->get('event_dispatcher')->removeListener(DocumentTemplateRendererParameterEvent::class, self::$callback);
        }
    }
->visibility()
                ->variant((new ProductBuilder($ids, 'p3.1'))->price(50)->build())
                ->variant((new ProductBuilder($ids, 'p3.2'))->price(40)->build())
                ->build(),
        ];

        $this->getContainer()->get('product.repository')->create($products, Context::createDefaultContext());

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

        $salesChannelContext->getContext()->setRuleIds([$ids->get('rule-A')]);

        $products = $this->getContainer()->get('sales_channel.product.repository')
            ->search(new Criteria($ids->getList(['p1', 'p2', 'p3.1']))$salesChannelContext);

        $stubs = $this->getContainer()->get(ScriptPriceStubs::class);

        $p1 = $products->get($ids->get('p1'));
        $p2 = $products->get($ids->get('p2'));
        $p3 = $products->get($ids->get('p3.1'));

        static::assertInstanceOf(Entity::class$p1);
        
$priceRuleId = Uuid::randomHex();

        $this->salesChannelContext = $this->getContainer()->get(SalesChannelContextFactory::class)->create(
            Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL,
            [
                SalesChannelContextService::CUSTOMER_ID => $this->createCustomer(),
            ]
        );

        $this->salesChannelContext->setRuleIds([$priceRuleId]);
        $this->deliveryNoteRenderer = $this->getContainer()->get(DeliveryNoteRenderer::class);
        $this->cartService = $this->getContainer()->get(CartService::class);
    }

    /** * @dataProvider deliveryNoteRendererDataProvider */
    public function testRender(string $deliveryNoteNumber, \Closure $assertionCallback): void
    {
        $cart = $this->generateDemoCart(3);

        
$paymentMethodId = $this->createPaymentMethod($ruleId);
        $this->addCountriesToSalesChannel();

        $context = $this->salesChannelContextFactory->create(
            Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL,
            [
                SalesChannelContextService::CUSTOMER_ID => $customerId,
                SalesChannelContextService::PAYMENT_METHOD_ID => $paymentMethodId,
            ]
        );
        $context->setRuleIds(
            [$ruleId$context->getShippingMethod()->getAvailabilityRuleId()]
        );

        $cart = $this->createDemoCart($context);

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

        $id = $this->orderPersister->persist($cart$context);

        $versionId = $this->orderRepository->createVersion($id$this->context);

        
if (!\is_array($content)) {
            throw CartException::tokenNotFound($token);
        }

        $cart = $content['cart'];

        if (!$cart instanceof Cart) {
            throw CartException::deserializeFailed();
        }

        $cart->setToken($token);
        $cart->setRuleIds($content['rule_ids']);

        $this->eventDispatcher->dispatch(new CartLoadedEvent($cart$context));

        return $cart;
    }

    public function save(Cart $cart, SalesChannelContext $context): void
    {
        $shouldPersist = $this->shouldPersist($cart);

        $this->eventDispatcher->dispatch(new CartSavedEvent($context$cart));

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