Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shopware PWA: Disable buying Product before it is Released

Is there a way to disable a product for buying before the release date.

We added a release date for a product, the product has also an available stock. By doing this it is possible to add the product to the cart and buy it. Even if the release date is still in the future. The reason is that the product should automatically become availalbe when the release date (time) is reached, without the requirement to update the stock or anything. Also disableing the product is no option, because it should be shown as coming soon.

The question is about how to disable it in a shopware-pwa setup, the store should not be allowed to add products to a chart nor to sell them before the release date. Disabeling this on the UI side only does not solve the problem because bots/scripts would still be able to do it by calling the API.

I did not find a setting for this. Does it require to update the logic of the shop?

like image 613
Tanja Bayer Avatar asked Jan 23 '26 23:01

Tanja Bayer


1 Answers

To secure this server-side you could register your own data collector for the cart and validate the line item in there. Then if the release date has not yet been reached, you can add an error and prevent the product from being added to the cart. It's important to have this collect the data after the ProductCartProcessor, hence the priority lower than 5000, otherwise the release date won't be available in the payload.

<service id="Foo\MyPlugin\Content\Product\Cart\CustomCartCollector">
    <tag name="shopware.cart.collector" priority="4999"/>
</service>
class CustomCartCollector implements CartDataCollectorInterface
{
    public function collect(CartDataCollection $data, Cart $original, SalesChannelContext $context, CartBehavior $behavior): void
    {
        foreach ($original->getLineItems() as $lineItem) {
            $releaseDate = $lineItem->getPayloadValue('releaseDate');
            if (!$releaseDate) {
                continue;
            }

            $releaseDate = new \DateTime($releaseDate);
            $now = new \DateTime();
            if ($releaseDate > $now) {
                $original->addErrors(new ProductNotFoundError($lineItem->getLabel() ?: $lineItem->getId()));

                $original->getLineItems()->remove($lineItem->getId());
            }
        }
    }
}
like image 197
dneustadt Avatar answered Jan 27 '26 00:01

dneustadt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!