diff --git a/commerce_stock_notifications.module b/commerce_stock_notifications.module --- a/commerce_stock_notifications.module +++ b/commerce_stock_notifications.module @@ -127,7 +127,7 @@ $variation_id = $notification->get('product_id')->getString(); /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */ $variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')->load($variation_id); - if ($variation) { + if (commerce_stock_notifications_variation_is_available($variation)) { if (commerce_stock_notifications_check_stock($variation)) { $queue->createItem($notification); } @@ -161,6 +161,23 @@ } /** + * Checks if the variation exists and it and its product are published. + * + * @param \Drupal\commerce_product\Entity\ProductVariationInterface|null $variation + * Product variation. + * + * @return bool + * Returns true if the variation can be notified about. + */ +function commerce_stock_notifications_variation_is_available(?ProductVariationInterface $variation): bool { + if (!$variation || !$variation->isPublished()) { + return FALSE; + } + $product = $variation->getProduct(); + return $product && $product->isPublished(); +} + +/** * Checks if the variation has stock. * * @param Drupal\commerce_product\Entity\ProductVariationInterface $variation diff --git a/src/Plugin/QueueWorker/CommerceStockNotifyQueue.php b/src/Plugin/QueueWorker/CommerceStockNotifyQueue.php --- a/src/Plugin/QueueWorker/CommerceStockNotifyQueue.php +++ b/src/Plugin/QueueWorker/CommerceStockNotifyQueue.php @@ -107,10 +107,12 @@ /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */ $variation = $this->entityTypeManager->getStorage('commerce_product_variation')->load($data->get('product_id')->getString()); - if (!$variation->isPublished() || !$variation->getProduct()->isPublished()) { - $sku = $variation->getSku(); - // The product or variation is inactive, ignore it. - throw new \Exception("Variation $sku (or it\'s parent product) is unpublished. Skipping for now."); + if (!commerce_stock_notifications_variation_is_available($variation)) { + // The variation (or its parent product) is deleted or unpublished: + // drop the queue item, but keep the notification. Throwing here would + // leave the item in the queue forever, and the cron would never queue + // new notifications while the queue is not empty. + return; } if (!commerce_stock_notifications_check_stock($variation)) { // There is no stock right now, do nothing.