From 455147cabef497dc493e0140b9a6de3866e7b03b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?R=C3=A9gis=20Hanol?= <regis@hanol.fr>
Date: Fri, 29 Nov 2019 22:48:39 +0100
Subject: [PATCH] DEV: use DB.after_commit instead of delaying the job

---
 plugins/discourse-narrative-bot/plugin.rb | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/plugins/discourse-narrative-bot/plugin.rb b/plugins/discourse-narrative-bot/plugin.rb
index efa6ae8fead..5ea07c9090a 100644
--- a/plugins/discourse-narrative-bot/plugin.rb
+++ b/plugins/discourse-narrative-bot/plugin.rb
@@ -257,10 +257,12 @@ after_initialize do
       args[:old_trust_level] == TrustLevel[1]
 
     if SiteSetting.discourse_narrative_bot_enabled && promoted_from_tl1
-      # NOTE: since the `user_promoted` event is triggered from inside a transaction
-      #       we have to delay the job otherwise it might run before the transaction
-      #       is commited and the user will be invisible to the job
-      Jobs.enqueue_in(1.minute, :send_advanced_tutorial_message, user_id: args[:user_id])
+      # The event 'user_promoted' is sometimes called from inside a transaction.
+      # Use this helper to ensure the job is enqueued after commit to prevent
+      # any race conditions.
+      DB.after_commit do
+        Jobs.enqueue(:send_advanced_tutorial_message, user_id: args[:user_id])
+      end
     end
   end
 end