diff --git a/lib/AutomaticEmails/WooCommerce/Events/PurchasedProduct.php b/lib/AutomaticEmails/WooCommerce/Events/PurchasedProduct.php index 6208fe57aa..3cdf55a1ce 100644 --- a/lib/AutomaticEmails/WooCommerce/Events/PurchasedProduct.php +++ b/lib/AutomaticEmails/WooCommerce/Events/PurchasedProduct.php @@ -128,17 +128,18 @@ class PurchasedProduct { $schedulingCondition = function(Newsletter $automaticEmail) use ($orderedProducts, $subscriber) { $meta = $automaticEmail->getMeta(); - if (empty($meta['option'])) return false; - if ($this->repository->wasScheduledForSubscriber($automaticEmail->id, $subscriber->id)) { - $sentAllProducts = $this->repository->alreadySentAllProducts($automaticEmail->id, $subscriber->id, 'orderedProducts', $orderedProducts); - if ($sentAllProducts) return false; - } $metaProducts = array_column($meta['option'], 'id'); $matchedProducts = array_intersect($metaProducts, $orderedProducts); + if (empty($matchedProducts)) return false; - return !empty($matchedProducts); + if ($this->repository->wasScheduledForSubscriber($automaticEmail->id, $subscriber->id)) { + $sentAllProducts = $this->repository->alreadySentAllProducts($automaticEmail->id, $subscriber->id, 'orderedProducts', $matchedProducts); + if ($sentAllProducts) return false; + } + + return true; }; $this->loggerFactory->getLogger(self::SLUG)->addInfo( diff --git a/tests/integration/AutomaticEmails/WooCommerce/Events/PurchasedProductTest.php b/tests/integration/AutomaticEmails/WooCommerce/Events/PurchasedProductTest.php index fac2f533b0..4e188678f4 100644 --- a/tests/integration/AutomaticEmails/WooCommerce/Events/PurchasedProductTest.php +++ b/tests/integration/AutomaticEmails/WooCommerce/Events/PurchasedProductTest.php @@ -162,9 +162,41 @@ class PurchasedProductTest extends \MailPoetTest { $event->scheduleEmailWhenProductIsPurchased($orderId); $queue1 = SendingQueue::where('newsletter_id', $newsletter->id)->findMany(); + // Create a second order with the same product and some additional product. + // This was a cause for a duplicate email: https://mailpoet.atlassian.net/browse/MAILPOET-3254 + $orderDetails = Stub::make( + new OrderDetails(), + [ + 'get_billing_email' => 'test@example.com', + 'get_items' => function() use ($productId) { + return [ + Stub::make( + \WC_Order_Item_Product::class, + [ + 'get_product_id' => $productId, + ] + ), + Stub::make( + \WC_Order_Item_Product::class, + [ + 'get_product_id' => '12345', // Dummy extra product ID + ] + ), + ]; + }, + ] + ); + $orderDetails->total = 'order_total'; + $orderId = 13; + $helper = Stub::make(WCHelper::class, [ + 'wcGetOrder' => $orderDetails, + ]); + + $event = new PurchasedProduct($helper); + $event->scheduleEmailWhenProductIsPurchased($orderId); $queue2 = SendingQueue::where('newsletter_id', $newsletter->id)->findMany(); - expect($queue1)->count(count($queue2)); + expect($queue2)->count(count($queue1)); } public function testItDoesNotScheduleEmailWhenPurchasedProductDoesNotMatchConfiguredProductIds() {