Cart example

$this->paymentMethodRepository,
            $stateMachineRegistry
        );
    }

    public function testCreateOrderWithDigitalGoodsNeedsRevocationConfirm(): void
    {
        $dataBag = new DataBag();
        $dataBag->set('tos', true);
        $context = $this->createMock(SalesChannelContext::class);

        $cart = new Cart('test');
        $cart->add((new LineItem('a', 'test'))->setStates([State::IS_PHYSICAL]));

        $this->cartService->method('getCart')->willReturn($cart);
        $this->cartService->expects(static::exactly(2))->method('order');

        $idSearchResult = new IdSearchResult(0, []new Criteria(), Context::createDefaultContext());
        $this->paymentMethodRepository->method('searchIds')->willReturn($idSearchResult);

        $this->orderService->createOrder($dataBag$context);

        $cart->add((new LineItem('b', 'test'))->setStates([State::IS_DOWNLOAD]));

        
'name' => 'Test',
                'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false]],
                'manufacturer' => ['id' => $this->ids->create('manufacturerId'), 'name' => 'test'],
                'tax' => ['id' => $this->ids->create('tax'), 'taxRate' => 17, 'name' => 'with id'],
                'active' => true,
                'visibilities' => [
                    ['salesChannelId' => $this->ids->get('sales-channel'), 'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL],
                ],
            ],
        ], Context::createDefaultContext());

        $cart = new Cart($this->ids->create('token'));
        $cart->add(new LineItem($this->ids->create('productId'), LineItem::PRODUCT_LINE_ITEM_TYPE, $this->ids->get('productId')));

        $context = $this->salesChannelFactory->create($this->ids->get('token')$this->ids->get('sales-channel'));
        $this->cartPersister->save($cart$context);

        if ($ruleConditions !== null) {
            $this->paymentMethodRepository->update([[
                'id' => $context->getPaymentMethod()->getId(),
                'availabilityRule' => [
                    'name' => 'Test Rule',
                    'priority' => 0,
                    
private OrderConverter $orderConverter;

    protected function setUp(): void
    {
        $this->orderPersister = $this->getContainer()->get(OrderPersister::class);
        $this->cartProcessor = $this->getContainer()->get(Processor::class);
        $this->orderConverter = $this->getContainer()->get(OrderConverter::class);
    }

    public function testSave(): void
    {
        $cart = new Cart(Uuid::randomHex());
        $cart->add(
            (new LineItem('test', 'test'))
                ->setPrice(new CalculatedPrice(1, 1, new CalculatedTaxCollection()new TaxRuleCollection()))
                ->setLabel('test')
        )->add(
            (new LineItem('test2', 'test'))
                ->setPrice(new CalculatedPrice(1, 1, new CalculatedTaxCollection()new TaxRuleCollection()))
                ->setLabel('test2')
        );
        $positionByIdentifier = [
            'test' => 1,
            
static::assertInstanceOf(SalesChannelContextRestoredEvent::class$salesChannelRestoredEvent);
    }

    public function testGuestContextAndCartAreDeleted(): void
    {
        $currentContextToken = Random::getAlphanumericString(32);

        $currentContext = $this->createSalesChannelContext($currentContextToken);

        $this->contextPersister->save($currentContextToken[]$currentContext->getSalesChannel()->getId()$this->customerId);

        $cart = new Cart($currentContextToken);

        $cart->add(new LineItem(Uuid::randomHex(), LineItem::CUSTOM_LINE_ITEM_TYPE));
        $this->getContainer()->get(CartPersister::class)->save($cart$currentContext);

        static::assertTrue($this->cartExists($currentContextToken));
        static::assertTrue($this->contextExists($currentContextToken));

        $newContext = $this->cartRestorer->restore($this->customerId, $currentContext);

        static::assertTrue($this->cartExists($newContext->getToken()));
        static::assertTrue($this->contextExists($newContext->getToken()));

        
'name' => 'Test',
                'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false]],
                'manufacturer' => ['id' => $this->ids->create('manufacturerId'), 'name' => 'test'],
                'tax' => ['id' => $this->ids->create('tax'), 'taxRate' => 17, 'name' => 'with id'],
                'active' => true,
                'visibilities' => [
                    ['salesChannelId' => $this->ids->get('sales-channel'), 'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL],
                ],
            ],
        ], Context::createDefaultContext());

        $cart = new Cart($this->ids->get('token'));
        $cart->add(new LineItem($this->ids->create('productId'), LineItem::PRODUCT_LINE_ITEM_TYPE, $this->ids->get('productId')));

        $this->cartPersister->save($cart$this->salesChannelFactory->create($this->ids->get('token')$this->ids->get('sales-channel')));

        // Check         $this->browser
            ->request(
                'GET',
                '/store-api/checkout/cart',
                [
                ]
            );
new SalesChannelContextServiceParameters(
                TestDefaults::SALES_CHANNEL,
                Uuid::randomHex()
            )
        );
    }

    public function testCalculateDoesNotAddDiscountItemsWithoutScope(): void
    {
        $discountItem = new LineItem(Uuid::randomHex(), PromotionProcessor::LINE_ITEM_TYPE);
        $discountItems = new LineItemCollection([$discountItem]);
        $original = new Cart(Uuid::randomHex());
        $toCalculate = new Cart(Uuid::randomHex());

        $this->promotionCalculator->calculate($discountItems$original$toCalculate$this->salesChannelContext, new CartBehavior());
        static::assertEmpty($toCalculate->getLineItems());
    }

    public function testCalculateDoesNotAddDiscountItemsWithDeliveryScope(): void
    {
        $discountItem = new LineItem(Uuid::randomHex(), PromotionProcessor::LINE_ITEM_TYPE);
        $discountItem->setPayloadValue('discountScope', PromotionDiscountEntity::SCOPE_DELIVERY);
        $discountItem->setPayloadValue('exclusions', []);
        
$this->cartDeleteRoute->expects(static::once())
            ->method('delete')
            ->with($context)
        ;

        $this->cartService->deleteCart($context);
    }

    public function testRemoveItemsCallsRemoveRoute(): void
    {
        $context = $this->createMock(SalesChannelContext::class);
        $cart = new Cart(Uuid::randomHex());

        $id1 = Uuid::randomHex();
        $id2 = Uuid::randomHex();
        $ids = [$id1$id2];

        $this->cartItemRemoveRoute->expects(static::once())
            ->method('remove')
            ->with(static::callback(function DRequest $actualRequest) use ($ids) {
                static::assertEquals($ids$actualRequest->request->all('ids'));

                return true;
            }),


    public function testProcessShouldRecalculateAll(): void
    {
        $deliveryProcessor = $this->getContainer()->get(DeliveryProcessor::class);

        $cartDataCollection = new CartDataCollection();
        $cartDataCollection->set(
            DeliveryProcessor::buildKey($this->salesChannelContext->getShippingMethod()->getId()),
            $this->salesChannelContext->getShippingMethod()
        );
        $originalCart = new Cart('original');
        $calculatedCart = new Cart('calculated');

        $lineItem = new LineItem('test', LineItem::PRODUCT_LINE_ITEM_TYPE);
        $lineItem->setDeliveryInformation(new DeliveryInformation(5, 0, false));
        $lineItem->setPrice(new CalculatedPrice(5.0, 5.0, new CalculatedTaxCollection([
            new CalculatedTax(5, 19, 5),
        ])new TaxRuleCollection()));

        $calculatedCart->setLineItems(new LineItemCollection([$lineItem]));

        $cartBehavior = new CartBehavior();

        
private readonly AmountCalculator $amountCalculator,
        private readonly TransactionProcessor $transactionProcessor,
        private readonly iterable $processors,
        private readonly iterable $collectors,
        private readonly ScriptExecutor $executor
    ) {
    }

    public function process(Cart $original, SalesChannelContext $context, CartBehavior $behavior): Cart
    {
        return Profiler::trace('cart::process', function D) use ($original$context$behavior) {
            $cart = new Cart($original->getToken());
            $cart->setCustomerComment($original->getCustomerComment());
            $cart->setAffiliateCode($original->getAffiliateCode());
            $cart->setCampaignCode($original->getCampaignCode());
            $cart->setSource($original->getSource());
            $cart->setBehavior($behavior);
            $cart->addState(...$original->getStates());

            if ($behavior->hookAware()) {
                // reset modified state that apps always have the same entry state                 foreach ($original->getLineItems()->getFlat() as $item) {
                    $item->markUnModifiedByApp();
                }

class PaymentMethodValidatorTest extends TestCase
{
    private PaymentMethodValidator $validator;

    private Cart $cart;

    protected function setUp(): void
    {
        $this->validator = new PaymentMethodValidator();
        $this->cart = new Cart('cart-token');
    }

    public function testValidateWithoutErrors(): void
    {
        $context = $this->getSalesChannelContext();
        $errors = new ErrorCollection();

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

        static::assertCount(0, $errors, \print_r($errors, true));
    }

    
public function testRuleWithExactAmountMatch(): void
    {
        $rule = (new LineItemUnitPriceRule())->assign(['amount' => 100, 'operator' => Rule::OPERATOR_EQ]);

        $context = $this->createMock(SalesChannelContext::class);

        static::assertTrue(
            $rule->match(new LineItemScope($this->lineItem, $context))
        );

        $cart = new Cart('test');
        $cart->add($this->lineItem);
        static::assertTrue(
            $rule->match(new CartRuleScope($cart$context))
        );
    }

    public function testRuleWithExactAmountNotMatch(): void
    {
        $rule = (new LineItemUnitPriceRule())->assign(['amount' => 99, 'operator' => Rule::OPERATOR_EQ]);

        $context = $this->createMock(SalesChannelContext::class);

        
'min' => 1,
            'max' => 3,
            'unit' => 'day',
            'name' => '1-3 days',
        ]);
    }

    public function testCalculateWithEmptyDelivery(): void
    {
        $context = $this->createMock(SalesChannelContext::class);
        $context->expects(static::never())->method(static::anything());
        $this->deliveryCalculator->calculate(new CartDataCollection()new Cart('test')new DeliveryCollection()$context);
    }

    public function testCalculateWithAlreadyCalculatedCosts(): void
    {
        $context = $this->createMock(SalesChannelContext::class);
        $context->method('getContext')->willReturn(Context::createDefaultContext());
        $context->method('getItemRounding')->willReturn(new CashRoundingConfig(2, 0.01, true));

        $positions = new DeliveryPositionCollection();
        $positions->add(
            new DeliveryPosition(
                
$controller->setTwig($twig);
        $controller->setContainer($this->getContainer());
        $controller->setTemplateFinder($twig->getExtension(NodeExtension::class)->getFinder());

        $rendered = $controller->testRenderViewInheritance('@Storefront/storefront/page/plugin/index.html.twig');

        static::assertEquals('plugin', $rendered);
    }

    public static function cartProvider(): \Generator
    {
        $cart = new Cart('test');
        $cart->setErrors(new ErrorCollection(self::getErrors()));

        yield 'cart with salutation errors' => [
            $cart,
        ];
    }

    /** * @return array{ * 0: 'request_stack', * 1: ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, * 2: Stub&RequestStack * } */

#[Package('business-ops')] class IsNewCustomerRuleTest extends TestCase
{
    public function testIsNewCustomer(): void
    {
        Feature::skipTestIfActive('v6.6.0.0', $this);

        $rule = new IsNewCustomerRule();

        $cart = new Cart('test');

        $customer = new CustomerEntity();
        $customer->setFirstLogin(new \DateTime());

        $context = $this->createMock(SalesChannelContext::class);

        $context
            ->method('getCustomer')
            ->willReturn($customer);

        static::assertTrue(
            

#[Package('business-ops')] class GoodsPriceRuleTest extends TestCase
{
    public function testRuleWithExactPriceMatch(): void
    {
        $rule = (new GoodsPriceRule())->assign(['amount' => 270.0, 'operator' => Rule::OPERATOR_EQ]);

        $cart = new Cart('test');
        $cart->add(
            (new LineItem('a', 'a'))
                ->setPrice(new CalculatedPrice(270, 270, new CalculatedTaxCollection()new TaxRuleCollection()))
        );

        $context = $this->createMock(SalesChannelContext::class);

        static::assertTrue(
            $rule->match(new CartRuleScope($cart$context))
        );
    }

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