Skip to content

A platform for community discussion. Free, open, simple.

103 KB
Raw Blame
# frozen_string_literal: true

RSpec.describe UserNotifications do
  let(:user) { Fabricate(:admin) }

  describe "#get_context_posts" do
    fab!(:category)

    it "does not include hidden/deleted/user_deleted posts in context" do
      post1 = create_post
      _post2 = Fabricate(:post, topic: post1.topic, deleted_at: 1.day.ago)
      _post3 = Fabricate(:post, topic: post1.topic, user_deleted: true)
      _post4 = Fabricate(:post, topic: post1.topic, hidden: true)
      _post5 = Fabricate(:post, topic: post1.topic, post_type: Post.types[:moderator_action])
      _post6 = Fabricate(:post, topic: post1.topic, post_type: Post.types[:small_action])
      _post7 = Fabricate(:post, topic: post1.topic, post_type: Post.types[:whisper])
      last = Fabricate(:post, topic: post1.topic)

      post1.user.user_option.email_previous_replies = UserOption.previous_replies_type[:always]

      # default is only post #1
      expect(UserNotifications.get_context_posts(last, nil, post1.user).count).to eq(1)
      # staff members can also see the whisper
      moderator = build(:moderator)
      moderator.user_option = UserOption.new
      moderator.user_option.email_previous_replies = UserOption.previous_replies_type[:always]
      tu = TopicUser.new(topic: post1.topic, user: moderator)
      expect(UserNotifications.get_context_posts(last, tu, tu.user).count).to eq(2)
    end

    it "allows users to control context" do
      post1 = create_post
      _post2 = Fabricate(:post, topic: post1.topic)
      post3 = Fabricate(:post, topic: post1.topic)

      user = Fabricate(:user)
      TopicUser.change(user.id, post1.topic_id, last_emailed_post_number: 1)
      topic_user = TopicUser.find_by(user_id: user.id, topic_id: post1.topic_id)
      # to avoid reloads after update_columns
      user = topic_user.user
      user.user_option.update_columns(
        email_previous_replies: UserOption.previous_replies_type[:unless_emailed],
      )

      expect(UserNotifications.get_context_posts(post3, topic_user, user).count).to eq(1)

      user.user_option.update_columns(
        email_previous_replies: UserOption.previous_replies_type[:never],
      )
      expect(UserNotifications.get_context_posts(post3, topic_user, user).count).to eq(0)

      user.user_option.update_columns(
        email_previous_replies: UserOption.previous_replies_type[:always],
      )
      expect(UserNotifications.get_context_posts(post3, topic_user, user).count).to eq(2)

      SiteSetting.private_email = true
      expect(UserNotifications.get_context_posts(post3, topic_user, user).count).to eq(0)
    end
  end

  describe ".signup" do
    subject(:email) { UserNotifications.signup(user) }

    let(:email_html) { Email::Renderer.new(email).html }

    it "addresses the signup email to the user with a subject and body" do
      expect(email.to).to eq([user.email])
      expect(email.subject).to be_present
      expect(email.from).to eq([SiteSetting.notification_email])
      expect(email.body).to be_present
    end

    it "shows the correct preview text in html" do
      preview_text = I18n.t("user_notifications.signup.preview")
      expect(email_html.scan(/#{preview_text}/).count).to eq(1)
    end
  end

  describe ".signup_after_approval" do
    before do
      SiteSetting.enable_local_logins_via_code = true
      SiteSetting.enable_local_logins = true
      SiteSetting.enable_local_logins_via_email = true
    end

    it "links a passwordless user to code login when it is available" do
      passwordless_user = Fabricate(:user, password: nil)
      body = UserNotifications.signup_after_approval(passwordless_user).body.to_s

      expect(body).to include("#{Discourse.base_url}/login?mode=code")
      expect(body).not_to include("code=")
      expect(body).to include("#{Discourse.base_url}/guidelines")
    end

    it "links a user with a password to the default destination" do
      body = UserNotifications.signup_after_approval(user).body.to_s

      expect(body).to include("logging in at:\n#{Discourse.base_url}")
      expect(body).not_to include("/login?mode=code")
    end

    it "uses the default destination when code login is unavailable" do
      SiteSetting.enable_local_logins_via_code = false
      passwordless_user = Fabricate(:user, password: nil)
      body = UserNotifications.signup_after_approval(passwordless_user).body.to_s

      expect(body).to include("logging in at:\n#{Discourse.base_url}")
      expect(body).not_to include("/login?mode=code")
    end

    it "uses the default destination when external login is required" do
      SiteSetting.discourse_connect_url = "https://www.example.com/sso"
      SiteSetting.discourse_connect_secret = "s" * 32
      SiteSetting.enable_discourse_connect = true
      passwordless_user = Fabricate(:user, password: nil)
      body = UserNotifications.signup_after_approval(passwordless_user).body.to_s

      expect(body).to include("logging in at:\n#{Discourse.base_url}")
      expect(body).not_to include("/login?mode=code")
    end
  end

  describe ".forgot_password" do
    subject(:email) { UserNotifications.forgot_password(user) }

    it "addresses the password reset email to the user with a subject and body" do
      expect(email.to).to eq([user.email])
      expect(email.subject).to be_present
      expect(email.from).to eq([SiteSetting.notification_email])
      expect(email.body).to be_present
    end

    context "when the dsa_reporting_enabled site setting is enabled" do
      before do
        enable_dsa_reporting
        SiteSetting.dsa_moderation_appeal_email = "[email protected]"
      end

      it "omits appeal instructions from the password reset email" do
        expect(email.body.decoded).not_to include(SiteSetting.dsa_moderation_appeal_email)
      end
    end

    it "shows the correct preview text in forgot password" do
      preview_text = I18n.t("user_notifications.forgot_password.preview")
      expect(Email::Renderer.new(email).html.scan(/#{preview_text}/).count).to eq(1)
    end

    it "shows the correct preview text when setting password" do
      email = UserNotifications.forgot_password(Fabricate(:user, password: nil))
      preview_text = I18n.t("user_notifications.set_password.preview")

      expect(Email::Renderer.new(email).html.scan(/#{preview_text}/).count).to eq(1)
    end
  end

  describe ".post_approved" do
    fab!(:post)

    context "when the dsa_reporting_enabled site setting is enabled" do
      before do
        enable_dsa_reporting
        SiteSetting.dsa_moderation_appeal_email = "[email protected]"
      end

      it "includes appeal instructions when DSA reporting and an appeal address are configured" do
        mail = UserNotifications.post_approved(user, notification_data_hash: { post_url: post.url })

        expect(mail.body.decoded).to include("To appeal this decision, contact [email protected]")
      end
    end

    it "addresses the post approval email to the user with a subject and body" do
      subject =
        UserNotifications.post_approved(user, { notification_data_hash: { post_url: post.url } })

      expect(subject.to).to eq([user.email])
      expect(subject.subject).to be_present
      expect(subject.from).to eq([SiteSetting.notification_email])
      expect(subject.body).to be_present
    end
  end

  describe ".confirm_new_email" do
    let(:opts) { { requested_by_admin: requested_by_admin, email_token: token } }
    let(:token) { "test123" }

    context "when requested by admin" do
      let(:requested_by_admin) { true }

      it "uses the requested by admin template" do
        expect(UserNotifications.confirm_new_email(user, opts).body).to include(
          "This email change was requested by a site admin.",
        )
      end
    end

    context "when not requested by admin" do
      let(:requested_by_admin) { false }

      it "uses the normal template" do
        expect(UserNotifications.confirm_new_email(user, opts).body).not_to include(
          "This email change was requested by a site admin.",
        )
      end
    end
  end

  describe ".email_login" do
    subject(:email) { UserNotifications.email_login(user, email_token: email_token) }

    let(:email_token) do
      Fabricate(:email_token, user: user, scope: EmailToken.scopes[:email_login]).token
    end

    let(:email_html) { Email::Renderer.new(email).html }

    before { SiteSetting.simple_email_subject = false }

    it "generates the right email" do
      expect(email.to).to eq([user.email])
      expect(email.from).to eq([SiteSetting.notification_email])

      expect(email.subject).to eq(
        I18n.t("user_notifications.email_login.subject_template", email_prefix: SiteSetting.title),
      )

      preview_text = I18n.t("user_notifications.email_login.preview")
      expect(email_html.scan(/#{preview_text}/).count).to eq(1)

      expect(email.body.to_s).to match(
        I18n.t(
          "user_notifications.email_login.text_body_template",
          site_name: SiteSetting.title,
          base_url: Discourse.base_url,
          email_token: email_token,
          email_preview: preview_text,
        ),
      )
    end
  end

  describe ".digest" do
    fab!(:category)
    subject(:email) { UserNotifications.digest(user) }

    before { SiteSetting.uncategorized_category_id = category.id }

    after { Discourse.redis.keys("summary-new-users:*").each { |key| Discourse.redis.del(key) } }

    context "without new topics" do
      it "doesn't send the email" do
        expect(email.to).to be_blank
      end
    end

    context "with a content modifier" do
      let(:plugin) { Plugin::Instance.new }

      it "skips sending when a modifier removes all content" do
        Fabricate(:topic, user: Fabricate(:admin))
        modifier = proc { |content| content.merge(topics: [], posts: []) }
        DiscoursePluginRegistry.register_modifier(plugin, :user_digest_content, &modifier)

        expect(email.to).to be_blank
      ensure
        DiscoursePluginRegistry.unregister_modifier(plugin, :user_digest_content, &modifier)
      end

      it "renders selected topics and replies with the standard digest preparation" do
        SiteSetting.content_localization_enabled = true
        SiteSetting.allow_user_locale = true
        user.update!(locale: "ja")
        topic = Fabricate(:topic, locale: "en")
        first_post = Fabricate(:post, topic: topic, locale: "en")
        reply = Fabricate(:post, topic: topic, locale: "en", post_number: 2)
        topic_translation = Fabricate(:topic_localization, topic: topic)
        post_translation = Fabricate(:post_localization, post: first_post)
        reply_translation = Fabricate(:post_localization, post: reply)
        modifier =
          proc { |content| content.merge(topics: [topic], posts: Post.where(id: reply.id)) }
        DiscoursePluginRegistry.register_modifier(plugin, :user_digest_content, &modifier)

        mail = UserNotifications.digest(user)

        [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
          expect(body).to include(topic_translation.title, reply_translation.raw)
        end
        expect(mail.html_part.body.to_s).to include(post_translation.raw)
        expect(mail.header["X-Discourse-Topic-Ids"].to_s).to eq(topic.id.to_s)
        expect(mail.header["X-Discourse-Post-Ids"].to_s).to eq(first_post.id.to_s)
      ensure
        DiscoursePluginRegistry.unregister_modifier(plugin, :user_digest_content, &modifier)
      end

      it "renders replies without new topics" do
        reply = Fabricate(:post, post_number: 2, raw: "A reply for the digest")
        modifier = proc { |content| content.merge(topics: Topic.none, posts: [reply]) }
        DiscoursePluginRegistry.register_modifier(plugin, :user_digest_content, &modifier)

        mail = UserNotifications.digest(user)

        expect(mail.to).to eq([user.email])
        expect(mail.html_part.body.to_s).to include(reply.raw)
        expect(mail.text_part.body.to_s).to include(reply.raw)
      ensure
        DiscoursePluginRegistry.unregister_modifier(plugin, :user_digest_content, &modifier)
      end

      it "renders custom content in both formats with the digest envelope" do
        require "action_view/testing/resolvers"
        original_view_paths = UserNotifications.view_paths
        UserNotifications.prepend_view_path(
          ActionView::FixtureResolver.new(
            "custom_digest.html.erb" => "<p><%= message %></p>",
            "custom_digest.text.erb" => "<%= message %>",
          ),
        )
        message = "Additional digest content"
        modifier =
          proc do |content, recipient, since|
            content.merge(
              topics: [],
              posts: [],
              template: "custom_digest",
              template_locals: {
                message: "#{message} for #{recipient.username} since #{since.to_date}",
              },
              subject_key: "user_notifications.digest.new_topics",
              has_custom_content: true,
            )
          end
        DiscoursePluginRegistry.register_modifier(plugin, :user_digest_content, &modifier)

        mail = UserNotifications.digest(user, since: 1.day.ago)

        expect(mail.to).to eq([user.email])
        expect(mail.subject).to eq(I18n.t("user_notifications.digest.new_topics"))
        [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
          expect(body).to include("#{message} for #{user.username} since #{1.day.ago.to_date}")
        end
        expect(mail.header["List-Unsubscribe"].to_s).to match(%r{/email/unsubscribe/\h{64}})
        expect(mail.header["List-Unsubscribe-Post"].to_s).to eq("List-Unsubscribe=One-Click")
        expect(mail.header["X-Discourse-Topic-Ids"]).to be_nil
      ensure
        UserNotifications.view_paths = original_view_paths
        DiscoursePluginRegistry.unregister_modifier(plugin, :user_digest_content, &modifier)
      end
    end

    context "with topics only from new users" do
      let!(:new_today) do
        Fabricate(
          :topic,
          user: Fabricate(:user, trust_level: TrustLevel[0], created_at: 10.minutes.ago),
          title: "Hey everyone look at me",
        )
      end
      let!(:new_yesterday) do
        Fabricate(
          :topic,
          user: Fabricate(:user, trust_level: TrustLevel[0], created_at: 25.hours.ago),
          created_at: 25.hours.ago,
          title: "This topic is of interest to you",
        )
      end

      it "returns topics from new users if they're more than 24 hours old" do
        expect(email.to).to eq([user.email])
        html = email.html_part.body.to_s
        expect(html).to include(new_yesterday.title)
        expect(html).to_not include(new_today.title)
      end
    end

    context "with new topics" do
      fab!(:coding_horror)

      let!(:popular_topic) { Fabricate(:topic, user: coding_horror, created_at: 1.hour.ago) }

      let!(:another_popular_topic) do
        Fabricate(:topic, user: coding_horror, created_at: 1.hour.ago)
      end

      let!(:post) { Fabricate(:post, topic: popular_topic, post_number: 1) }

      let!(:another_post) { Fabricate(:post, topic: another_popular_topic, post_number: 1) }

      it "builds the digest with content, topic headers, and unsubscribe headers" do
        expect(email.to).to eq([user.email])
        expect(email.subject).to be_present
        expect(email.from).to eq([SiteSetting.notification_email])
        expect(email.html_part.body.to_s).to be_present
        expect(email.text_part.body.to_s).to be_present
        expect(email.header["List-Unsubscribe"].to_s).to match(/\/email\/unsubscribe\/\h{64}/)
        expect(email.header["List-Unsubscribe-Post"].to_s).to eq("List-Unsubscribe=One-Click")
        expect(email.header["X-Discourse-Topic-Ids"].to_s).to eq(
          "#{another_popular_topic.id},#{popular_topic.id}",
        )
        expect(email.header["X-Discourse-Post-Ids"].to_s).to eq("#{another_post.id},#{post.id}")
        expect(email.html_part.body.to_s).to include("New Users")
      end

      it "doesn't include new user count if digest_after_minutes is low" do
        user.user_option.digest_after_minutes = 60
        expect(email.html_part.body.to_s).to_not include("New Users")
      end

      it "works with min_date string" do
        digest = UserNotifications.digest(user, since: 1.month.ago.to_date.to_s)
        expect(digest.html_part.body.to_s).to be_present
        expect(digest.text_part.body.to_s).to be_present
        expect(digest.html_part.body.to_s).to include("New Users")
      end

      it "includes email_prefix in email subject instead of site title" do
        SiteSetting.email_prefix = "Try Discourse"
        SiteSetting.title = "Discourse Meta"
        SiteSetting.simple_email_subject = false

        expect(email.subject).to match(/Try Discourse/)
        expect(email.subject).not_to match(/Discourse Meta/)
      end

      it "does not include site name or email prefix in simple email subject" do
        SiteSetting.simple_email_subject = true
        expect(email.subject).to eq(I18n.t("user_notifications.digest.subject_template_improved"))
      end

      it "includes unread likes received count within the since date" do
        Fabricate(
          :notification,
          user: user,
          notification_type: Notification.types[:liked],
          created_at: 2.months.ago,
        )
        Fabricate(
          :notification,
          user: user,
          notification_type: Notification.types[:liked],
          read: true,
        )
        Fabricate(:notification, user: user, notification_type: Notification.types[:liked])
        Fabricate(:notification, user: user, notification_type: Notification.types[:liked])
        digest = UserNotifications.digest(user, since: 1.month.ago.to_date.to_s)
        parsed_html = Nokogiri::HTML5.fragment(digest.html_part.body.to_s)
        expect(parsed_html.css(".header-stat-count #likes_received_stat_count strong").text).to eq(
          "2",
        )
        expect(
          parsed_html.css(".header-stat-description #likes_received_stat_description strong").text,
        ).to eq("Likes Received")
      end

      it "excludes deleted topics and their posts" do
        deleted =
          Fabricate(
            :topic,
            user: Fabricate(:user),
            title: "Delete this topic plz",
            created_at: 1.hour.ago,
          )
        post =
          Fabricate(
            :post,
            topic: deleted,
            score: 100.0,
            post_number: 2,
            raw: "Your wish is my command",
            created_at: 1.hour.ago,
          )
        deleted.trash!
        html = email.html_part.body.to_s
        expect(html).to_not include deleted.title
        expect(html).to_not include post.raw
      end

      it "excludes shared drafts" do
        cat = Fabricate(:category)
        SiteSetting.shared_drafts_category = cat.id
        topic =
          Fabricate(:topic, title: "This is a draft", category_id: cat.id, created_at: 1.hour.ago)
        post =
          Fabricate(
            :post,
            topic: topic,
            score: 100.0,
            post_number: 2,
            raw: "secret draft content",
            created_at: 1.hour.ago,
          )
        html = email.html_part.body.to_s
        expect(html).to_not include topic.title
        expect(html).to_not include post.raw
      end

      it "excludes whispers and other post types that don't belong" do
        t =
          Fabricate(
            :topic,
            user: Fabricate(:user),
            title: "Who likes the same stuff I like?",
            created_at: 1.hour.ago,
          )
        whisper =
          Fabricate(
            :post,
            topic: t,
            score: 100.0,
            post_number: 2,
            raw: "You like weird stuff",
            post_type: Post.types[:whisper],
            created_at: 1.hour.ago,
          )
        mod_action =
          Fabricate(
            :post,
            topic: t,
            score: 100.0,
            post_number: 3,
            raw: "This topic unlisted",
            post_type: Post.types[:moderator_action],
            created_at: 1.hour.ago,
          )
        small_action =
          Fabricate(
            :post,
            topic: t,
            score: 100.0,
            post_number: 4,
            raw: "A small action",
            post_type: Post.types[:small_action],
            created_at: 1.hour.ago,
          )
        html = email.html_part.body.to_s
        expect(html).to_not include whisper.raw
        expect(html).to_not include mod_action.raw
        expect(html).to_not include small_action.raw
      end

      it "excludes deleted and hidden posts" do
        t =
          Fabricate(
            :topic,
            user: Fabricate(:user),
            title: "Post objectionable stuff here",
            created_at: 1.hour.ago,
          )
        deleted =
          Fabricate(
            :post,
            topic: t,
            score: 100.0,
            post_number: 2,
            raw: "This post is uncalled for",
            deleted_at: 5.minutes.ago,
            created_at: 1.hour.ago,
          )
        hidden =
          Fabricate(
            :post,
            topic: t,
            score: 100.0,
            post_number: 3,
            raw: "Try to find this post",
            hidden: true,
            hidden_at: 5.minutes.ago,
            hidden_reason_id: Post.hidden_reasons[:flagged_by_tl3_user],
            created_at: 1.hour.ago,
          )
        user_deleted =
          Fabricate(
            :post,
            topic: t,
            score: 100.0,
            post_number: 4,
            raw: "I regret this post",
            user_deleted: true,
            created_at: 1.hour.ago,
          )
        html = email.html_part.body.to_s
        expect(html).to_not include deleted.raw
        expect(html).to_not include hidden.raw
        expect(html).to_not include user_deleted.raw
      end

      it "excludes posts that are newer than editing grace period" do
        SiteSetting.editing_grace_period = 5.minutes
        too_new =
          Fabricate(
            :topic,
            user: Fabricate(:user),
            title: "Oops I need to edit this",
            created_at: 1.minute.ago,
          )
        _too_new_post =
          Fabricate(
            :post,
            user: too_new.user,
            topic: too_new,
            score: 100.0,
            post_number: 1,
            created_at: 1.minute.ago,
          )
        html = email.html_part.body.to_s
        expect(html).to_not include too_new.title
      end

      it "uses theme color" do
        cs =
          Fabricate(
            :color_scheme,
            name: "Fancy",
            color_scheme_colors: [
              Fabricate(:color_scheme_color, name: "header_primary", hex: "F0F0F0"),
              Fabricate(:color_scheme_color, name: "header_background", hex: "1E1E1E"),
            ],
          )
        theme =
          Fabricate(:theme, user_selectable: true, user: Fabricate(:admin), color_scheme_id: cs.id)

        theme.set_default!

        html = email.html_part.body.to_s
        expect(html).to include "F0F0F0"
        expect(html).to include "1E1E1E"
      end

      it "supports subfolder" do
        set_subfolder "/forum"
        html = email.html_part.body.to_s
        text = email.text_part.body.to_s
        expect(html).to be_present
        expect(text).to be_present
        expect(html).to_not include("/forum/forum")
        expect(text).to_not include("/forum/forum")
        expect(email.header["List-Unsubscribe"].to_s).to match(
          /http:\/\/test.localhost\/forum\/email\/unsubscribe\/\h{64}/,
        )
        expect(email.header["List-Unsubscribe-Post"].to_s).to eq("List-Unsubscribe=One-Click")

        topic_url = "http://test.localhost/forum/t/#{popular_topic.slug}/#{popular_topic.id}"
        expect(html).to include(topic_url)
        expect(text).to include(topic_url)
      end

      it "applies lang/xml:lang html attributes" do
        SiteSetting.default_locale = "pl_PL"
        html = email.html_part.body.to_s

        expect(html).to match(' lang="pl-PL"')
        expect(html).to match(' xml:lang="pl-PL"')
      end

      it "uses digest_attempted_at when user hasn't been seen in a while" do
        user.update!(last_seen_at: 7.days.ago)
        user.user_stat.update!(digest_attempted_at: 30.minutes.ago)
        expect(email.to).to be_nil
      end

      it "uses last_seen_at when user has been sent a digest in a while" do
        user.update!(last_seen_at: 30.minutes.ago)
        user.user_stat.update!(digest_attempted_at: 7.days.ago)
        expect(email.to).to be_nil
      end

      it "caps at 1 month when user has never been seen or sent a digest" do
        old_topic = Fabricate(:topic, created_at: 2.months.ago)

        user.update!(last_seen_at: nil)
        user.user_stat.update!(digest_attempted_at: nil)
        expect(email.to).to contain_exactly(user.email)

        html = email.html_part.body.to_s
        expect(html).not_to include(old_topic.title)
      end
    end
  end

  describe "translated digest content" do
    fab!(:user) { Fabricate(:user, locale: "ja") }
    fab!(:author) { Fabricate(:user, trust_level: TrustLevel[2]) }
    fab!(:topic) { Fabricate(:topic, user: author, locale: "en", created_at: 1.hour.ago) }
    fab!(:other_topic) { Fabricate(:topic, user: author, locale: "en", created_at: 2.hours.ago) }
    fab!(:post) do
      Fabricate(:post, user: author, topic: topic, locale: "en", raw: "Original first post")
    end
    fab!(:reply) do
      Fabricate(
        :post,
        user: author,
        topic: topic,
        locale: "en",
        raw: "Original popular reply",
        score: 100,
        created_at: 1.hour.ago,
      )
    end
    fab!(:post_translation) { Fabricate(:post_localization, post: post) }
    fab!(:reply_translation) { Fabricate(:post_localization, post: reply) }
    fab!(:topic_translation) { Fabricate(:topic_localization, topic: topic) }
    fab!(:other_topic_translation) { Fabricate(:topic_localization, topic: other_topic) }

    before do
      SiteSetting.allow_user_locale = true
      SiteSetting.content_localization_enabled = true
      SiteSetting.digest_topics = 1
      SiteSetting.digest_other_topics = 1
      SiteSetting.digest_posts = 1
      topic.update!(bumped_at: 1.hour.ago)
      other_topic.update!(bumped_at: 2.hours.ago)
    end

    def digest_mail(recipient = user)
      UserNotifications.digest(recipient, since: 1.day.ago)
    end

    it "translates popular topics, popular posts, and other new topics in both parts" do
      mail = digest_mail
      html = mail.html_part.body.to_s
      text = mail.text_part.body.to_s
      [html, text].each do |body|
        expect(body).to include(
          topic_translation.title,
          other_topic_translation.title,
          reply_translation.raw,
        )
        expect(body).not_to include(topic.title, other_topic.title, reply.raw)
      end
      expect(html).to include(post_translation.raw)
      expect(text).not_to include(post.raw)
      expect(html).to include(I18n.t("user_notifications.digest.popular_topics", locale: "ja"))
      expect(I18n.locale).to eq(:en)
    end

    it "keeps content in the recipient's selected language and understood languages" do
      topic.update!(locale: "ja")
      post.update!(locale: "ja")
      reply.update!(locale: "en")
      other_topic.update!(locale: "fr")
      user.user_option.update!(understood_languages: ["en"])
      mail = digest_mail
      [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
        expect(body).to include(topic.title, reply.raw, other_topic_translation.title)
        expect(body).not_to include(
          topic_translation.title,
          reply_translation.raw,
          other_topic.title,
        )
      end
      expect(mail.html_part.body.to_s).to include(post.raw)
    end

    it "falls back for missing and stale post translations" do
      post_translation.destroy!
      topic_translation.destroy!
      reply_translation.update!(post_version: reply.version - 1)
      mail = digest_mail
      expect(mail.html_part.body.to_s).to include(topic.title, post.raw, reply.raw)
      expect(mail.text_part.body.to_s).to include(topic.title, reply.raw)
      expect(mail.html_part.body.to_s).not_to include(reply_translation.raw)
    end

    it "respects the automatic translation preference" do
      user.user_option.update!(automatically_translate: false)
      mail = digest_mail
      [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
        expect(body).to include(topic.title, other_topic.title, reply.raw)
        expect(body).not_to include(topic_translation.title, reply_translation.raw)
      end
    end

    it "keeps original content when localization is disabled" do
      SiteSetting.content_localization_enabled = false
      mail = digest_mail
      [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
        expect(body).to include(topic.title, reply.raw)
        expect(body).not_to include(topic_translation.title, reply_translation.raw)
      end
    end

    it "uses the effective locale when user locales are disabled" do
      SiteSetting.allow_user_locale = false
      mail = digest_mail
      [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
        expect(body).to include(topic.title, reply.raw)
        expect(body).not_to include(topic_translation.title, reply_translation.raw)
      end
    end

    it "uses normalized language matches and skips sources whose language is unknown" do
      user.update!(locale: "pt_BR")
      topic_translation.update!(locale: "pt")
      reply_translation.update!(locale: "pt")
      post.update!(locale: nil)
      mail = digest_mail
      [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
        expect(body).to include(topic_translation.title, reply_translation.raw)
      end
      expect(mail.html_part.body.to_s).to include(post.raw)
      expect(mail.html_part.body.to_s).not_to include(post_translation.raw)
    end

    it "escapes translated titles and sanitizes translated post content" do
      title = %(<img src="x" onerror="alert(1)"> Translated meeting)
      topic_translation.update!(title: title)
      PostLocalizationUpdater.update(
        post: reply,
        locale: "ja",
        user: author,
        raw:
          %(Safe localized reply\n\n<img src="x" onerror="alert(1)">\n\n<script>alert(1)</script>),
      )
      html = Nokogiri::HTML5.fragment(Email::Renderer.new(digest_mail).html)
      expect(html.text).to include(title, "Safe localized reply")
      expect(html.css("script, [onerror], [onload]")).to be_empty
    end

    it "formats translated links and redacts secure images from digest excerpts" do
      setup_s3
      SiteSetting.secure_uploads = true
      SiteSetting.login_required = true
      secure_url = "/secure-uploads/original/1X/translated.png"
      [post_translation, reply_translation].each do |translation|
        translation.update!(
          cooked: "<p>#{translation.raw}<a href='/u/admin'>Admin</a><img src='#{secure_url}'></p>",
        )
      end
      mail = digest_mail
      renderer = Email::Renderer.new(mail)
      html = Nokogiri::HTML5.fragment(renderer.html)
      expect(html.css("a").map { |link| link["href"] }).to include("#{Discourse.base_url}/u/admin")
      expect(html.at_css("[data-stripped-secure-upload]")).to be_present
      expect(html.css("img").map { |image| image["src"] }).not_to include(
        secure_url,
        "#{Discourse.base_url}#{secure_url}",
      )
    end

    it "loads translations in a bounded number of queries as the digest grows" do
      original_queries = track_sql_queries { digest_mail.html_part.body.to_s }
      additional_topic = Fabricate(:topic, user: author, locale: "en", created_at: 1.hour.ago)
      additional_post = Fabricate(:post, user: author, topic: additional_topic, locale: "en")
      Fabricate(:topic_localization, topic: additional_topic)
      Fabricate(:post_localization, post: additional_post)
      SiteSetting.digest_topics = 2
      expanded_queries = track_sql_queries { digest_mail.html_part.body.to_s }
      %w[post_localizations topic_localizations].each do |table|
        expect(expanded_queries.count { |query| query.include?(%(FROM "#{table}")) }).to eq(
          original_queries.count { |query| query.include?(%(FROM "#{table}")) },
        )
      end
    end
  end

  describe "translated notification content" do
    fab!(:user) { Fabricate(:user, locale: "ja") }
    fab!(:topic) { Fabricate(:topic, locale: "en") }
    fab!(:post) { Fabricate(:post, topic: topic, locale: "en") }
    fab!(:reply) { Fabricate(:post, topic: topic, locale: "en", reply_to_post_number: 1) }
    fab!(:post_translation) { Fabricate(:post_localization, post: post) }
    fab!(:reply_translation) { Fabricate(:post_localization, post: reply) }
    fab!(:topic_translation) { Fabricate(:topic_localization, topic: topic) }

    before do
      SiteSetting.allow_user_locale = true
      SiteSetting.content_localization_enabled = true
      user.user_option.update!(
        email_previous_replies: UserOption.previous_replies_type[:always],
        email_in_reply_to: true,
      )
    end

    def notification_mail(recipient = user)
      UserNotifications.user_replied(
        recipient,
        post: reply,
        notification_type: "replied",
        notification_data_hash: {
          original_username: reply.username,
          topic_title: topic.title,
        },
      )
    end

    it "uses the recipient's translations for the subject, post, and previous replies" do
      original_post_attributes = reply.attributes.slice("raw", "cooked")
      original_topic_title = topic.title
      mail = notification_mail
      expect(mail.subject).to include(topic_translation.title)
      [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
        expect(body).to include(reply_translation.raw, post_translation.raw)
        expect(body).not_to include(reply.raw, post.raw)
      end
      expect(reply.reload.attributes.slice("raw", "cooked")).to eq(original_post_attributes)
      expect(topic.reload.title).to eq(original_topic_title)
      expect(I18n.locale).to eq(:en)
    end

    it "uses translations for mailing list notifications" do
      mail = UserNotifications.mailing_list_notify(user, reply)
      expect(mail.subject).to include(topic_translation.title)
      expect(mail.html_part.body.to_s).to include(reply_translation.raw)
      expect(mail.text_part.body.to_s).to include(reply_translation.raw)
    end

    it "preserves the original PM subject when the topic has been renamed" do
      topic.update!(archetype: Archetype.private_message, category_id: nil)
      original_title = "Original PM title"
      mail =
        UserNotifications.user_private_message(
          user,
          post: reply,
          notification_type: "private_message",
          notification_data_hash: {
            original_username: reply.username,
            topic_title: original_title,
          },
        )
      expect(mail.subject).to include(original_title)
      expect(mail.html_part.body.to_s).to include(reply_translation.raw)
      expect(mail.text_part.body.to_s).to include(reply_translation.raw)
    end

    it "preserves plugin title and body overrides when translations are available" do
      plugin = Plugin::Instance.new
      custom_title = "Plugin supplied title"
      custom_raw = "Plugin supplied plain text"
      custom_cooked = "<p>Plugin supplied HTML</p>"
      modifier =
        proc do |options|
          options[:title] = custom_title
          options[:post].raw = custom_raw
          options[:post].cooked = custom_cooked
          options
        end
      DiscoursePluginRegistry.register_modifier(plugin, :user_notification_email_options, &modifier)

      mail = notification_mail
      aggregate_failures do
        expect(mail.subject).to include(custom_title)
        expect(mail.html_part.body.to_s).to include(custom_cooked)
        expect(mail.text_part.body.to_s).to include(custom_raw)
        expect(mail.html_part.body.to_s).to include(post_translation.raw)
        expect(mail.text_part.body.to_s).to include(post_translation.raw)
      end
    ensure
      DiscoursePluginRegistry.unregister_modifier(
        plugin,
        :user_notification_email_options,
        &modifier
      )
    end

    it "uses translated excerpts" do
      SiteSetting.post_excerpts_in_emails = true
      expect(notification_mail.html_part.body.to_s).to include(reply_translation.raw)
    end

    it "falls back to the original when translations are missing" do
      reply_translation.destroy!
      topic_translation.destroy!
      mail = notification_mail
      expect(mail.subject).to include(topic.title)
      expect(mail.html_part.body.to_s).to include(reply.raw)
      expect(mail.text_part.body.to_s).to include(reply.raw)
    end

    it "respects the automatic translation preference" do
      user.user_option.update!(automatically_translate: false)
      mail = notification_mail
      expect(mail.subject).to include(topic.title)
      expect(mail.html_part.body.to_s).to include(reply.raw)
      expect(mail.text_part.body.to_s).to include(reply.raw)
    end

    it "keeps content in languages the recipient understands" do
      user.user_option.update!(understood_languages: ["en"])
      mail = notification_mail
      expect(mail.subject).to include(topic.title)
      expect(mail.html_part.body.to_s).to include(reply.raw)
      expect(mail.text_part.body.to_s).to include(reply.raw)
    end

    it "keeps selected and understood languages while translating other context posts" do
      topic.update!(locale: "ja")
      reply.update!(locale: "ja", post_number: 4)
      french_post =
        Fabricate(:post, topic: topic, locale: "fr", post_number: 3, raw: "French context")
      french_translation = Fabricate(:post_localization, post: french_post)
      user.user_option.update!(understood_languages: ["en_GB"])
      mail = notification_mail
      expect(mail.subject).to include(topic.title)
      [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
        expect(body).to include(reply.raw, post.raw, french_translation.raw)
        expect(body).not_to include(
          topic_translation.title,
          reply_translation.raw,
          post_translation.raw,
          french_post.raw,
        )
      end
    end

    it "keeps original content when localization is disabled" do
      SiteSetting.content_localization_enabled = false
      mail = notification_mail
      expect(mail.subject).to include(topic.title)
      expect(mail.html_part.body.to_s).to include(reply.raw)
      expect(mail.text_part.body.to_s).to include(reply.raw)
    end

    it "keeps original content when the source language is unknown" do
      topic.update!(locale: nil)
      reply.update!(locale: nil)
      mail = notification_mail
      expect(mail.subject).to include(topic.title)
      expect(mail.html_part.body.to_s).to include(reply.raw)
      expect(mail.text_part.body.to_s).to include(reply.raw)
    end

    it "redacts translated content in private emails" do
      SiteSetting.private_email = true
      mail = notification_mail
      expect(mail.subject).not_to include(topic_translation.title, topic.title)
      [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
        expect(body).not_to include(
          reply_translation.raw,
          post_translation.raw,
          reply.raw,
          post.raw,
        )
      end
    end

    it "falls back to original content for stale translations" do
      reply_translation.update!(post_version: reply.version - 1)
      mail = notification_mail
      expect(mail.html_part.body.to_s).to include(reply.raw)
      expect(mail.text_part.body.to_s).to include(reply.raw)
    end

    it "uses normalized locale matches" do
      user.update!(locale: "pt_BR")
      reply_translation.update!(locale: "pt")
      mail = notification_mail
      expect(mail.html_part.body.to_s).to include(reply_translation.raw)
      expect(mail.text_part.body.to_s).to include(reply_translation.raw)
    end

    it "uses the effective locale when user locales are disabled" do
      SiteSetting.allow_user_locale = false
      mail = notification_mail
      expect(mail.subject).to include(topic.title)
      expect(mail.html_part.body.to_s).to include(reply.raw)
      expect(mail.text_part.body.to_s).to include(reply.raw)
    end

    it "uses translated content with customized email templates" do
      [SiteSetting.default_locale, user.locale].each do |locale|
        TranslationOverride.upsert!(
          locale,
          "user_notifications.user_replied.text_body_template",
          "%{topic_title}\n\n%{message}\n\n%{context}",
        )
      end
      mail = notification_mail
      renderer = Email::Renderer.new(mail)
      [renderer.html, renderer.text].each do |body|
        expect(body).to include(
          topic_translation.title,
          reply_translation.raw,
          post_translation.raw,
        )
      end
    end

    it "uses the translated title and excerpt when inviting a user to a topic" do
      mail =
        UserNotifications.user_invited_to_topic(
          user,
          post: post,
          notification_type: "invited_to_topic",
          notification_data_hash: {
            original_username: post.username,
            topic_title: topic.title,
          },
        )
      [mail.html_part.body.to_s, mail.text_part.body.to_s].each do |body|
        expect(body).to include(topic_translation.title, post_translation.raw)
      end
    end

    it "keeps original incoming email subjects for staged recipients" do
      user.update!(staged: true)
      incoming_email = Fabricate(:incoming_email, post: post, subject: "Original incoming subject")
      expect(notification_mail.subject).to include(incoming_email.subject)
    end

    it "formats translated links and redacts secure images" do
      setup_s3
      SiteSetting.secure_uploads = true
      SiteSetting.login_required = true
      secure_url = "/secure-uploads/original/1X/translated.png"
      reply_translation.update!(
        cooked:
          "<p>#{reply_translation.raw}<a href='/u/admin'>Admin</a><img src='#{secure_url}'></p>",
      )
      html = Nokogiri::HTML5.fragment(notification_mail.html_part.body.to_s)
      expect(html.css("a").map { |link| link["href"] }).to include("#{Discourse.base_url}/u/admin")
      expect(html.css("img").map { |image| image["src"] }).not_to include(
        secure_url,
        "#{Discourse.base_url}#{secure_url}",
      )
      expect(html.at_css("[data-stripped-secure-upload]")).to be_present
    end

    it "loads post translations in a bounded number of queries as context grows" do
      original_queries = track_sql_queries { notification_mail.html_part.body.to_s }
      3.times do
        context_post = Fabricate(:post, topic: topic, locale: "en")
        Fabricate(:post_localization, post: context_post)
      end
      latest_post = Fabricate(:post, topic: topic, locale: "en")
      latest_translation = Fabricate(:post_localization, post: latest_post)
      mail = nil
      expanded_queries =
        track_sql_queries do
          mail = UserNotifications.mailing_list_notify(user, latest_post)
          mail.html_part.body.to_s
        end
      expect(mail.html_part.body.to_s).to include(latest_translation.raw, reply_translation.raw)
      expect(expanded_queries.count { |query| query.include?('FROM "post_localizations"') }).to eq(
        original_queries.count { |query| query.include?('FROM "post_localizations"') },
      )
    end

    it "selects content independently for each recipient" do
      notification_mail.html_part.body.to_s
      other_user = Fabricate(:user, locale: "en")
      mail = notification_mail(other_user)
      expect(mail.subject).to include(topic.title)
      expect(mail.html_part.body.to_s).to include(reply.raw)
      expect(mail.text_part.body.to_s).to include(reply.raw)
    end
  end

  describe ".user_replied" do
    let(:response_by_user) { Fabricate(:user, name: "John Doe") }
    let(:category) { Fabricate(:category, name: "India") }
    let(:tag1) { Fabricate(:tag, name: "Taggo", public_topic_count: 1) }
    let(:tag2) { Fabricate(:tag, name: "Taggie", public_topic_count: 3) }
    let(:tag3) { Fabricate(:tag, name: "Teggo", public_topic_count: 2) }

    let(:hidden_tag) { Fabricate(:tag, name: "hidden") }
    let!(:hidden_tag_group) do
      Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])
    end

    let(:topic) do
      Fabricate(
        :topic,
        category: category,
        tags: [tag1, tag2, tag3, hidden_tag],
        title: "Super cool topic",
      )
    end
    let(:post) { Fabricate(:post, topic: topic, raw: "This is My super duper cool topic") }
    let(:response) { Fabricate(:basic_reply, topic: post.topic, user: response_by_user) }
    let(:user) { Fabricate(:user) }
    let(:notification) { Fabricate(:replied_notification, user: user, post: response) }

    it "lets admins add the site name to the sender name via the email_from override" do
      TranslationOverride.upsert!(
        SiteSetting.default_locale,
        "email_from",
        "%{user_name} via %{site_name}",
      )

      mail =
        UserNotifications.user_replied(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      expect(mail[:from].display_names).to eql(["John Doe via #{Email.site_title}"])
    end

    it "generates a correct email" do
      SiteSetting.default_email_in_reply_to = true

      # Fabricator is not fabricating this ...
      SiteSetting.email_subject =
        "[%{site_name}] %{optional_pm}%{optional_cat}%{optional_tags}%{topic_title}"
      SiteSetting.enable_names = true
      SiteSetting.display_name_on_posts = true
      mail =
        UserNotifications.user_replied(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      # from should include full user name
      expect(mail[:from].display_names).to eql(["John Doe"])

      # subject should include category name
      expect(mail.subject).to match(/India/)

      # subject should include tag names
      expect(mail.subject).to match(/Taggo/)
      expect(mail.subject).to match(/Taggie/)

      mail_html = mail.html_part.body.to_s
      preview_text = I18n.t("user_notifications.user_replied.preview")

      expect(mail_html.scan(/#{preview_text}/).count).to eq(1)

      expect(mail_html.scan(/My super duper cool topic/).count).to eq(1)
      expect(mail_html.scan(/In Reply To/).count).to eq(1)

      # 2 "visit topic" link
      expect(mail_html.scan(/Visit Topic/).count).to eq(2)

      # 2 respond to links cause we have 1 context post
      expect(mail_html.scan(/to respond/).count).to eq(2)

      # 1 unsubscribe
      expect(mail_html.scan(/To unsubscribe/).count).to eq(1)

      # side effect, topic user is updated with post number
      tu = TopicUser.get(post.topic_id, user)
      expect(tu.last_emailed_post_number).to eq(response.post_number)

      # no In Reply To if user opts out
      user.user_option.email_in_reply_to = false
      mail =
        UserNotifications.user_replied(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      expect(mail.html_part.body.to_s.scan(/In Reply To/).count).to eq(0)

      SiteSetting.enable_names = true
      SiteSetting.display_name_on_posts = true
      SiteSetting.prioritize_username_in_ux = false

      response.user.username = "bobmarley"
      response.user.name = "Bob Marley"
      response.user.save

      mail =
        UserNotifications.user_replied(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      mail_html = mail.html_part.body.to_s
      expect(mail_html.scan(/>Bob Marley/).count).to eq(1)
      expect(mail_html.scan(/>bobmarley/).count).to eq(0)

      expect(mail.subject.scan(/#{tag1.name}/).count).to eq(1)
      expect(mail.subject.scan(/#{hidden_tag.name}/).count).to eq(0)

      SiteSetting.prioritize_username_in_ux = true

      mail =
        UserNotifications.user_replied(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      mail_html = mail.html_part.body.to_s
      expect(mail_html.scan(/>Bob Marley/).count).to eq(0)
      expect(mail_html.scan(/>bobmarley/).count).to eq(1)
    end

    describe "number of tags shown in subject line" do
      describe "max_tags_per_email_subject siteSetting enabled" do
        before { SiteSetting.enable_max_tags_per_email_subject = true }

        it "limits subject tags to max_tags_per_email_subject" do
          SiteSetting.email_subject =
            "[%{site_name}] %{optional_pm}%{optional_cat}%{optional_tags}%{topic_title}"
          SiteSetting.max_tags_per_topic = 1
          SiteSetting.max_tags_per_email_subject = 2

          mail =
            UserNotifications.user_replied(
              user,
              post: response,
              notification_type: notification.notification_type,
              notification_data_hash: notification.data_hash,
            )

          expect(mail.subject).to eq(
            "[Discourse] [#{category.name}] #{tag2.name} #{tag3.name} #{topic.title}",
          )
        end
      end

      describe "max_tags_per_email_subject siteSetting disabled" do
        before { SiteSetting.enable_max_tags_per_email_subject = false }

        it "limits subject tags to max_tags_per_topic" do
          SiteSetting.email_subject =
            "[%{site_name}] %{optional_pm}%{optional_cat}%{optional_tags}%{topic_title}"
          SiteSetting.max_tags_per_topic = 2
          SiteSetting.max_tags_per_email_subject = 1

          mail =
            UserNotifications.user_replied(
              user,
              post: response,
              notification_type: notification.notification_type,
              notification_data_hash: notification.data_hash,
            )

          expect(mail.subject).to eq(
            "[Discourse] [#{category.name}] #{tag2.name} #{tag3.name} #{topic.title}",
          )
        end
      end
    end

    describe "optional placeholders in email body" do
      it "renders no body hashtags when the email tag limit is zero" do
        SiteSetting.enable_max_tags_per_email_subject = true
        SiteSetting.max_tags_per_email_subject = 0
        TranslationOverride.upsert!(
          I18n.locale,
          "user_notifications.user_replied.text_body_template",
          "Tags: %{optional_tags}\n\n",
        )

        mail =
          UserNotifications.user_replied(
            user,
            post: response,
            notification_type: notification.notification_type,
            notification_data_hash: notification.data_hash,
          )

        expect(Email::Renderer.new(mail).text.lines.first.strip).to eq("Tags:")
      end

      it "renders optional placeholders with tag links in the body and plain tags in the subject" do
        Fabricate(:category, name: tag2.name, slug: tag2.name.downcase)
        SiteSetting.email_subject = "%{optional_tags}%{topic_title}"
        custom_body = <<~BODY
          You got a reply!

          Category: %{optional_cat}
          Tags: %{optional_tags}
          PM marker: %{optional_pm}
          Re marker: %{optional_re}

          %{message}
        BODY

        TranslationOverride.upsert!(
          I18n.locale,
          "user_notifications.user_replied.text_body_template",
          custom_body,
        )

        mail =
          UserNotifications.user_replied(
            user,
            post: response,
            notification_type: notification.notification_type,
            notification_data_hash: notification.data_hash,
          )

        renderer = Email::Renderer.new(mail)
        links = Nokogiri::HTML5.parse(renderer.html).css("a.hashtag-cooked")

        expect(renderer.text).to include(
          "Category: [#{category.name}]",
          "Tags: ##{tag2.name}::tag ##{tag3.name} ##{tag1.name}",
          "PM marker: \nRe marker: \n",
        )
        expect(renderer.text).not_to include(hidden_tag.name)
        expect(links.map(&:text)).to eq([tag2, tag3, tag1].map { |tag| "##{tag.name}" })
        expect(links.map { |link| link["href"] }).to eq([tag2, tag3, tag1].map(&:full_url))
        expect(mail.subject).to eq("#{tag2.name} #{tag3.name} #{tag1.name} #{topic.title}")
        expect(mail["X-Discourse-Tags"].value).to eq("#{tag2.name} #{tag3.name} #{tag1.name}")
      end
    end

    it "doesn't include details when private_email is enabled" do
      SiteSetting.private_email = true
      mail =
        UserNotifications.user_replied(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      expect(mail.html_part.body.to_s).to_not include(response.raw)
      expect(mail.html_part.body.to_s).to_not include(topic.url)
      expect(mail.text_part.to_s).to_not include(response.raw)
      expect(mail.text_part.to_s).to_not include(topic.url)
    end

    it "includes excerpt when post_excerpts_in_emails is enabled" do
      paragraphs = [
        "This is the first paragraph, but you should read more.",
        "And here is its friend, the second paragraph.",
      ]
      SiteSetting.post_excerpts_in_emails = true
      SiteSetting.post_excerpt_maxlength = paragraphs.first.length
      response.update!(raw: paragraphs.join("\n\n"))
      mail =
        UserNotifications.user_replied(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      mail_html = mail.html_part.body.to_s
      expect(mail_html.scan(/#{paragraphs[0]}/).count).to eq(1)
      expect(mail_html.scan(/#{paragraphs[1]}/).count).to eq(0)
    end
  end

  describe ".user_posted" do
    let(:response_by_user) { Fabricate(:user, name: "John Doe", username: "john") }
    let(:topic) { Fabricate(:topic, title: "Super cool topic") }
    let(:post) { Fabricate(:post, topic: topic) }
    let(:response) { Fabricate(:post, topic: topic, user: response_by_user) }
    let(:user) { Fabricate(:user) }
    let(:notification) { Fabricate(:posted_notification, user: user, post: response) }

    it "generates a correct email" do
      SiteSetting.enable_names = false
      mail =
        UserNotifications.user_posted(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      # from should not include full user name if "show user full names" is disabled
      expect(mail[:from].display_names).to_not eql(["John Doe"])

      # from should include username if "show user full names" is disabled
      expect(mail[:from].display_names).to eql(["john"])

      # subject should not include category name
      expect(mail.subject).not_to match(/Uncategorized/)

      preview_text = I18n.t("user_notifications.user_posted.preview")
      expect(mail.html_part.body.to_s.scan(/#{preview_text}/).count).to eq(1)

      # 1 respond to links as no context by default
      expect(mail.html_part.body.to_s.scan(/to respond/).count).to eq(1)

      # 1 unsubscribe link
      expect(mail.html_part.body.to_s.scan(/To unsubscribe/).count).to eq(1)

      # side effect, topic user is updated with post number
      tu = TopicUser.get(post.topic_id, user)
      expect(tu.last_emailed_post_number).to eq(response.post_number)
    end

    it "doesn't include details when private_email is enabled" do
      SiteSetting.private_email = true
      mail =
        UserNotifications.user_posted(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      expect(mail.html_part.body.to_s).to_not include(response.raw)
      expect(mail.text_part.to_s).to_not include(response.raw)
    end

    it "uses the original subject for staged users" do
      incoming_email =
        Fabricate(
          :incoming_email,
          subject: "Original Subject",
          post: post,
          topic: post.topic,
          user: user,
        )

      mail =
        UserNotifications.user_posted(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      expect(mail.subject).to match(/Super cool topic/)

      user.update!(staged: true)
      mail =
        UserNotifications.user_posted(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      expect(mail.subject).to eq("Re: Original Subject")

      another_post = Fabricate(:post, topic: topic)
      incoming_email.update!(post_id: another_post.id)

      mail =
        UserNotifications.user_private_message(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      expect(mail.subject).to match(/Super cool topic/)
    end

    it "uses post author username when original_username is missing from notification data" do
      SiteSetting.enable_names = false

      notification_data = {
        topic_title: topic.title,
        original_post_id: response.id,
        original_post_type: response.post_type,
        display_username: I18n.t("embed.replies", count: 7),
      }

      mail =
        UserNotifications.user_posted(
          user,
          post: response,
          notification_type: Notification.types[:posted],
          notification_data_hash: notification_data,
        )

      expect(mail.header["X-Discourse-Sender"].value).to eq(response_by_user.username)
    end
  end

  describe ".user_private_message" do
    let(:response_by_user) { Fabricate(:user, name: "", username: "john") }
    let(:topic) { Fabricate(:private_message_topic, title: "Super cool topic") }
    let(:post) { Fabricate(:post, topic: topic) }
    let(:response) { Fabricate(:post, topic: topic, user: response_by_user) }
    let(:user) { Fabricate(:user) }
    let(:notification) { Fabricate(:private_message_notification, user: user, post: response) }

    context "when the dsa_reporting_enabled site setting is enabled" do
      before do
        enable_dsa_reporting
        SiteSetting.dsa_moderation_appeal_email = "[email protected]"
      end

      it "includes the stored moderation appeal once in each email part" do
        moderation_post =
          SystemMessage.create_from_system_user(
            user,
            :silenced_by_staff,
            message_title: "Moderation notice",
            message_raw: "Moderation outcome.",
            **Dsa::AppealInstructions.message_options,
          )
        moderation_notification =
          Fabricate(:private_message_notification, user:, post: moderation_post)
        appeal =
          I18n.t(
            "system_messages.moderation_appeal_instructions",
            email: SiteSetting.dsa_moderation_appeal_email,
          )

        mail =
          UserNotifications.user_private_message(
            user,
            post: moderation_post,
            notification_type: moderation_notification.notification_type,
            notification_data_hash: moderation_notification.data_hash,
          )

        html_text = Nokogiri::HTML5.fragment(mail.html_part.body.decoded).text
        expect(html_text.scan(appeal).size).to eq(1)
        expect(mail.text_part.body.decoded.scan(appeal).size).to eq(1)
      end
    end

    it "generates a correct email" do
      SiteSetting.enable_names = true
      mail =
        UserNotifications.user_private_message(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      # from should include username if full user name is not provided
      expect(mail[:from].display_names).to eql(["john"])

      # subject should include "[PM]"
      expect(mail.subject).to include("[PM] ")

      # note that translation key differs from method name (ie. user_posted_pm)
      preview_text = I18n.t("user_notifications.user_posted_pm.preview")
      expect(mail.html_part.body.to_s.scan(/#{preview_text}/).count).to eq(1)

      # 1 "visit message" link
      expect(mail.html_part.body.to_s.scan(/Visit Message/).count).to eq(1)

      # 1 respond to link
      expect(mail.html_part.body.to_s.scan(/to respond/).count).to eq(1)

      # 1 unsubscribe link
      expect(mail.html_part.body.to_s.scan(/To unsubscribe/).count).to eq(1)

      # side effect, topic user is updated with post number
      tu = TopicUser.get(topic.id, user)
      expect(tu.last_emailed_post_number).to eq(response.post_number)
    end

    it "doesn't include details when private_email is enabled" do
      SiteSetting.private_email = true
      mail =
        UserNotifications.user_private_message(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      expect(mail.html_part.body.to_s).to_not include(response.raw)
      expect(mail.html_part.body.to_s).to_not include(topic.url)
      expect(mail.text_part.to_s).to_not include(response.raw)
      expect(mail.text_part.to_s).to_not include(topic.url)
    end

    it "doesn't include group name in subject" do
      group = Fabricate(:group)
      topic.allowed_groups = [group]
      mail =
        UserNotifications.user_private_message(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      expect(mail.subject).to include("[PM] ")
    end

    it "includes a list of participants (except for the destination user), groups first with member lists" do
      group1 = Fabricate(:group, name: "group1")
      group2 = Fabricate(:group, name: "group2")

      user1 = Fabricate(:user, username: "one", groups: [group1, group2])
      user2 = Fabricate(:user, username: "two", groups: [group1], staged: true)

      topic.allowed_users = [user, user1, user2]
      topic.allowed_groups = [group1, group2]

      mail =
        UserNotifications.user_private_message(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )

      expect(mail.body).to include(
        "[group1 (2)](http://test.localhost/g/group1), [group2 (1)](http://test.localhost/g/group2), [one](http://test.localhost/u/one), [two](http://test.localhost/u/two)",
      )
    end

    context "when SiteSetting.group_name_in_subject is true" do
      before do
        SiteSetting.group_in_subject = true
        SiteSetting.simple_email_subject = true

        # Enabling simple_email_subject rewrites email_subject to a template
        # without %{optional_pm}, which is where the group name is rendered.
        SiteSetting.email_subject = "[%{site_name}] %{optional_pm}%{optional_cat}%{topic_title}"
      end

      let(:group) { Fabricate(:group, name: "my_group") }
      let(:mail) do
        UserNotifications.user_private_message(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      end

      shared_examples "includes first group name" do
        it "includes first group name in subject" do
          expect(mail.subject).to include("my_group: ")
        end

        context "when first group has full name" do
          it "includes full name in subject" do
            group.full_name = "My Group"
            group.save
            expect(mail.subject).to include("My Group: ")
          end
        end
      end

      context "with one group in pm" do
        before { topic.allowed_groups = [group] }

        include_examples "includes first group name"
      end

      context "with multiple groups in pm" do
        let(:group2) { Fabricate(:group) }

        before { topic.allowed_groups = [group, group2] }

        include_examples "includes first group name"
      end

      context "with no groups in pm" do
        it "includes %{optional_pm} in subject" do
          expect(mail.subject).to include("[PM] ")
        end
      end
    end

    it "uses the original subject for staged users when topic was started via email" do
      incoming_email =
        Fabricate(
          :incoming_email,
          subject: "Original Subject",
          post: post,
          topic: topic,
          user: user,
        )

      mail =
        UserNotifications.user_private_message(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      expect(mail.subject).to match(/Super cool topic/)

      user.update!(staged: true)
      mail =
        UserNotifications.user_private_message(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      expect(mail.subject).to eq("Re: Original Subject")

      another_post = Fabricate(:post, topic: topic)
      incoming_email.update!(post_id: another_post.id)

      mail =
        UserNotifications.user_private_message(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      expect(mail.subject).to match(/Super cool topic/)
    end
  end

  it "adds a warning when mail limit is reached" do
    SiteSetting.max_emails_per_day_per_user = 2
    user = Fabricate(:user)

    user.email_logs.create!(email_type: "blah", to_address: user.email, user_id: user.id)

    post = Fabricate(:post)
    reply = Fabricate(:post, topic_id: post.topic_id)

    notification =
      Fabricate(
        :notification,
        topic_id: post.topic_id,
        post_number: reply.post_number,
        user: post.user,
        data: { original_username: "bob" }.to_json,
      )

    mail =
      UserNotifications.user_replied(
        user,
        post: reply,
        notification_type: notification.notification_type,
        notification_data_hash: notification.data_hash,
      )

    # WARNING: you reached the limit of 100 email notifications per day. Further emails will be suppressed.
    # Consider watching less topics or disabling mailing list mode.
    expect(mail.html_part.body.to_s).to match(I18n.t("user_notifications.reached_limit", count: 2))
    expect(mail.body.to_s).to match(I18n.t("user_notifications.reached_limit", count: 2))
  end

  def expects_build_with(condition)
    UserNotifications.any_instance.expects(:build_email).with(user.email, condition)
    mailer =
      UserNotifications.public_send(
        mail_type,
        user,
        notification_type: Notification.types[notification.notification_type],
        notification_data_hash: notification.data_hash,
        post: notification.post,
      )

    mailer.message
  end

  shared_examples "supports reply by email" do
    context "with reply_by_email" do
      it "sets allow_reply_by_email when the feature is enabled" do
        expects_build_with(has_entry(:allow_reply_by_email, true))
      end
    end
  end

  shared_examples "no reply by email" do
    context "with reply_by_email" do
      it "doesn't support reply by email" do
        expects_build_with(Not(has_entry(:allow_reply_by_email, true)))
      end
    end
  end

  shared_examples "respect for private_email" do
    context "with private_email" do
      it "doesn't include topic title or slug for regular users" do
        SiteSetting.private_email = true

        mailer =
          UserNotifications.public_send(
            mail_type,
            user,
            notification_type: Notification.types[notification.notification_type],
            notification_data_hash: notification.data_hash,
            post: notification.post,
          )
        message = mailer.message

        topic = notification.post.topic
        expect(message.html_part.body.to_s).not_to include(topic.title)
        expect(message.html_part.body.to_s).not_to include(topic.slug)
        expect(message.text_part.body.to_s).not_to include(topic.title)
        expect(message.text_part.body.to_s).not_to include(topic.slug)
      end

      it "still links back to the topic for staged users" do
        skip_types = %i[linked quoted mentioned group_mentioned]
        if skip_types.include?(notification_type)
          skip "Staged users don't receive #{notification_type} emails"
        end

        invite_types = %i[invited_to_private_message invited_to_topic watching_first_post]
        if invite_types.include?(notification_type)
          skip "Invite-type emails use a different template structure"
        end

        SiteSetting.private_email = true
        user.update!(staged: true)

        mailer =
          UserNotifications.public_send(
            mail_type,
            user,
            notification_type: Notification.types[notification.notification_type],
            notification_data_hash: notification.data_hash,
            post: notification.post,
          )
        message = mailer.message

        slugless_path = notification.post.topic.slugless_url
        expect(message.html_part.body.to_s).to include(slugless_path)
        expect(message.text_part.body.to_s).to include(slugless_path)
      end
    end
  end

  # The parts of emails that are derived from templates are translated
  shared_examples "sets user locale" do
    context "with set locale for translating templates" do
      it "sets the locale" do
        expects_build_with(has_key(:locale))
      end
    end
  end

  shared_examples "notification email building" do |invitation: false|
    let(:post) { Fabricate(:post, user: user) }
    let(:mail_type) { "user_#{notification_type}" }
    let(:mail_template) { "user_notifications.#{mail_type}" }
    let(:username) { "walterwhite" }
    let(:notification) do
      Fabricate(
        :notification,
        user: user,
        topic: post.topic,
        notification_type: Notification.types[notification_type],
        post_number: post.post_number,
        data: { original_username: username }.to_json,
      )
    end

    describe "email building" do
      it "has a username" do
        expects_build_with(has_entry(:username, username))
      end

      it "has a url" do
        expects_build_with(has_key(:url))
      end

      it "has a template" do
        expects_build_with(has_entry(:template, mail_template))
      end

      it "overrides the html part" do
        expects_build_with(has_key(:html_override))
      end

      it "has a message" do
        expects_build_with(has_key(:message))
      end

      it "has a context" do
        expects_build_with(has_key(:context))
      end

      it "has an unsubscribe link" do
        expects_build_with(has_key(:add_unsubscribe_link))
      end

      it "has an post_id" do
        expects_build_with(has_key(:post_id))
      end

      it "has an topic_id" do
        expects_build_with(has_key(:topic_id))
      end

      it "uses the user's name as from_alias" do
        SiteSetting.enable_names = true
        SiteSetting.display_name_on_posts = true
        expects_build_with(has_entry(:from_alias, user.name))
      end

      it "omits the user's name from from_alias when display_name_on_posts is disabled" do
        SiteSetting.enable_names = false
        SiteSetting.display_name_on_posts = false
        expects_build_with(has_entry(:from_alias, "walterwhite"))
      end

      it "explains how to respond" do
        expects_build_with(Not(has_entry(:include_respond_instructions, false)))
      end

      it "omits response instructions for suspended users" do
        User.any_instance.stubs(:suspended?).returns(true)
        expects_build_with(has_entry(:include_respond_instructions, false))
      end

      if invitation
        {
          "the default body" => nil,
          "a customized message" => "%{message}",
          "a customized title and message" => "%{topic_title}\n\n%{message}",
        }.each do |description, custom_body|
          context "with #{description}" do
            before do
              if custom_body
                TranslationOverride.upsert!(
                  SiteSetting.default_locale,
                  "#{mail_template}.text_body_template",
                  custom_body,
                )
                TranslationOverride.upsert!(
                  SiteSetting.default_locale,
                  "#{mail_template}.subject_template",
                  "Invitation: %{topic_title}",
                )
              end
            end

            it "preserves the literal title and invitation link without changing the subject" do
              title = 'Planning *notes* `draft` [agenda] (updated) \ & <details>'
              post.topic.update!(title: title)
              notification.data_hash[:topic_title] = title
              mail =
                UserNotifications.public_send(
                  mail_type,
                  user,
                  notification_type: notification_type,
                  notification_data_hash: notification.data_hash,
                  post: post,
                )
              html = Nokogiri::HTML5.fragment(Email::Renderer.new(mail).html)

              expect(mail.subject).to include(title)
              expect(html.css("a[href='#{post.topic.url}']").map(&:text)).to include(title)
              expect(html.css("em, code, details")).to be_empty
              expect(html.text.scan(title).size).to eq(
                custom_body&.include?("%{topic_title}") ? 2 : 1,
              )
            end
          end
        end
      end

      context "when customized" do
        let(:custom_body) do
          body = +<<~BODY
            You are now officially notified.
            %{header_instructions}
            %{message} %{respond_instructions}
            %{topic_title_url_encoded}
            %{site_title_url_encoded}
          BODY

          body << "%{context}" if notification_type != :invited_to_topic
          body
        end

        before do
          TranslationOverride.upsert!(
            SiteSetting.default_locale,
            "#{mail_template}.text_body_template",
            custom_body,
          )
        end

        it "does not use the default html_override" do
          expects_build_with(Not(has_key(:html_override)))
        end
      end
    end
  end

  describe "user mentioned email" do
    include_examples "notification email building" do
      let(:notification_type) { :mentioned }

      include_examples "respect for private_email"
      include_examples "supports reply by email"
      include_examples "sets user locale"
    end
  end

  describe "group mentioned email" do
    include_examples "notification email building" do
      let(:notification_type) { :group_mentioned }
      let(:post) { Fabricate(:private_message_post) }
      let(:user) { post.user }
      let(:mail_type) { "group_mentioned" }
      let(:mail_template) { "user_notifications.user_#{notification_type}_pm" }

      include_examples "respect for private_email"
      include_examples "supports reply by email"
      include_examples "sets user locale"
    end
  end

  describe "user replied" do
    include_examples "notification email building" do
      let(:notification_type) { :replied }

      include_examples "respect for private_email"
      include_examples "supports reply by email"
      include_examples "sets user locale"
    end
  end

  describe "user quoted" do
    include_examples "notification email building" do
      let(:notification_type) { :quoted }

      include_examples "respect for private_email"
      include_examples "supports reply by email"
      include_examples "sets user locale"
    end
  end

  describe "user posted" do
    include_examples "notification email building" do
      let(:notification_type) { :posted }

      include_examples "respect for private_email"
      include_examples "supports reply by email"
      include_examples "sets user locale"
    end
  end

  describe "invitation email attribution" do
    fab!(:inviter) { Fabricate(:user, trust_level: TrustLevel[2], name: "Message Inviter") }
    fab!(:invitee, :user)

    %i[private_message topic].each do |destination|
      it "identifies the inviter when another user started the #{destination}" do
        SiteSetting.enable_names = true
        SiteSetting.display_name_on_email_from = true
        post =
          if destination == :private_message
            Fabricate(:private_message_post, recipient: inviter)
          else
            Fabricate(:post)
          end

        post.topic.invite(inviter, invitee.username)
        notification = invitee.notifications.find_by!(topic_id: post.topic_id)
        notification_type = "invited_to_#{destination}"
        mail =
          UserNotifications.public_send(
            "user_#{notification_type}",
            invitee,
            notification_type: notification_type,
            notification_data_hash: notification.data_hash,
            post: notification.post,
          )

        expect(mail.text_part.body.decoded).to include("#{inviter.username} invited you")
        expect(mail[:from].display_names).to eq([inviter.name])
      end
    end
  end

  describe "invitation email titles" do
    fab!(:inviter) { Fabricate(:user, trust_level: TrustLevel[2]) }
    fab!(:invitee, :user)

    %i[private_message topic].each do |destination|
      it "renders HTML in a #{destination} title as text" do
        post =
          if destination == :private_message
            Fabricate(:private_message_post, recipient: inviter)
          else
            Fabricate(:post)
          end
        post.topic.update!(title: %(<img src="x" onerror="alert(1)"> Meeting & planning))
        post.topic.invite(inviter, invitee.username)
        notification = invitee.notifications.find_by!(topic_id: post.topic_id)
        notification_type = "invited_to_#{destination}"
        mail =
          UserNotifications.public_send(
            "user_#{notification_type}",
            invitee,
            notification_type: notification_type,
            notification_data_hash: notification.data_hash,
            post: notification.post,
          )
        renderer = Email::Renderer.new(mail)
        html = Nokogiri::HTML5.fragment(renderer.html)

        expect(html.css("[onerror], img[src='x']")).to be_empty
        expect(html.text).to include(post.topic.title)
        expect(renderer.text).to include(post.topic.title)
        expect(html.css("a").map { |link| link["href"] }).to include(post.topic.url)
      end
    end
  end

  describe "user invited to a private message" do
    include_examples "notification email building", invitation: true do
      let(:notification_type) { :invited_to_private_message }
      let(:post) { Fabricate(:private_message_post) }
      let(:user) { post.user }
      let(:mail_template) { "user_notifications.user_#{notification_type}_pm" }

      include_examples "respect for private_email"
      include_examples "no reply by email"
      include_examples "sets user locale"
    end
  end

  describe "group invited to a private message" do
    include_examples "notification email building", invitation: true do
      let(:notification_type) { :invited_to_private_message }
      let(:post) { Fabricate(:private_message_post) }
      let(:user) { post.user }
      let(:group) { Fabricate(:group) }
      let(:mail_template) { "user_notifications.user_#{notification_type}_pm_group" }

      before do
        notification.data_hash[:group_id] = group.id
        notification.save!
      end

      it "includes the group name" do
        expects_build_with(has_entry(:group_name, group.name))
      end

      include_examples "respect for private_email"
      include_examples "no reply by email"
      include_examples "sets user locale"
    end
  end

  describe "user invited to a topic" do
    let(:notification_type) { :invited_to_topic }

    include_examples "notification email building", invitation: true do
      include_examples "respect for private_email"
      include_examples "no reply by email"
      include_examples "sets user locale"
    end

    context "when showing the right name in 'From' field" do
      let(:inviter) { Fabricate(:user) }
      let(:invitee) { Fabricate(:user) }

      let(:notification) do
        Fabricate(
          :notification,
          notification_type: Notification.types[:invited_to_topic],
          user: invitee,
          topic: post.topic,
          post_number: post.post_number,
          data: {
            topic_title: post.topic.title,
            display_username: inviter.username,
            original_user_id: inviter.id,
            original_username: inviter.username,
          }.to_json,
        )
      end

      let(:mailer) do
        UserNotifications.public_send(
          "user_invited_to_topic",
          invitee,
          notification_type: Notification.types[notification.notification_type],
          notification_data_hash: notification.data_hash,
          post: notification.post,
        )
      end

      it "uses the inviter's username when names are disabled" do
        SiteSetting.enable_names = false

        expect(mailer.message.to_s).to include(
          "From: #{inviter.username} <#{SiteSetting.notification_email}>",
        )
      end

      it "uses the inviter's name as the sender" do
        expect(mailer.message.to_s).to include(
          "From: #{inviter.name} <#{SiteSetting.notification_email}>",
        )
      end
    end
  end

  describe "watching first post" do
    include_examples "notification email building" do
      let(:notification_type) { :invited_to_topic }

      include_examples "respect for private_email"
      include_examples "no reply by email"
      include_examples "sets user locale"
    end
  end

  describe "#notification_email" do
    let!(:plugin) { Plugin::Instance.new }
    let(:response_by_user) { Fabricate(:user, name: "John Doe") }
    let(:category) { Fabricate(:category, name: "India") }

    let(:topic) { Fabricate(:topic, category: category, title: "Super cool topic") }

    let(:user) { Fabricate(:user) }
    let(:post) { Fabricate(:post, topic: topic, raw: "This is My super duper cool topic") }
    let(:response) do
      Fabricate(
        :basic_reply,
        topic: post.topic,
        user: response_by_user,
        raw: "@#{user.username} response to post",
      )
    end
    let(:notification) { Fabricate(:mentioned_notification, user: user, post: response) }
    let!(:modify_post) do
      Proc.new do |email_options|
        email_options[:post].cooked = "modified post"
        email_options
      end
    end

    it "allows plugins to control #notification_email" do
      DiscoursePluginRegistry.register_modifier(
        plugin,
        :user_notification_email_options,
        &modify_post
      )

      mail =
        UserNotifications.user_mentioned(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      mail_html = mail.html_part.body.to_s
      expect(mail_html.scan("modified post").count).to eq(1)
    ensure
      DiscoursePluginRegistry.unregister_modifier(
        plugin,
        :user_notification_email_options,
        &modify_post
      )
    end
  end

  describe "recipient_username" do
    fab!(:user)
    fab!(:topic)
    fab!(:post) { Fabricate(:post, topic: topic) }
    fab!(:response) { Fabricate(:basic_reply, topic: topic) }
    fab!(:notification) { Fabricate(:mentioned_notification, user: user, post: response) }

    it "includes recipient_username in notification emails" do
      TranslationOverride.upsert!(
        I18n.locale,
        "user_notifications.user_mentioned.text_body_template",
        "Hello %{recipient_username}, %{username} mentioned you on %{topic_title}",
      )

      mail =
        UserNotifications.user_mentioned(
          user,
          post: response,
          notification_type: notification.notification_type,
          notification_data_hash: notification.data_hash,
        )
      expect(mail.body.to_s).to include("Hello #{user.username}")
    end
  end

  # notification emails derived from templates are translated into the user's locale
  shared_context "with notification derived from template" do
    let(:user) { Fabricate(:user, locale: locale) }
    let(:mail_type) { mail_type }
    let(:notification) { Fabricate(:notification, user: user) }
  end

  describe "notifications from template" do
    context "when user locale is allowed" do
      before { SiteSetting.allow_user_locale = true }

      %w[
        signup
        signup_after_approval
        confirm_old_email
        notify_old_email
        confirm_new_email
        forgot_password
        admin_login
        account_created
      ].each do |mail_type|
        include_examples "with notification derived from template" do
          let(:locale) { "fr" }
          let(:mail_type) { mail_type }

          it "sets the locale" do
            expects_build_with(has_entry(:locale, "fr"))
          end
        end
      end
    end

    context "when user locale is not allowed" do
      before { SiteSetting.allow_user_locale = false }

      %w[
        signup
        signup_after_approval
        notify_old_email
        confirm_old_email
        confirm_new_email
        forgot_password
        admin_login
        account_created
      ].each do |mail_type|
        include_examples "with notification derived from template" do
          let(:locale) { "fr" }
          let(:mail_type) { mail_type }

          it "sets the locale" do
            expects_build_with(has_entry(:locale, "en"))
          end
        end
      end
    end
  end

  describe "#participants" do
    fab!(:group1) { Fabricate(:group, name: "group1") }
    fab!(:group2) { Fabricate(:group, name: "group2") }
    fab!(:group3) { Fabricate(:group, name: "group3") }
    fab!(:user1) { Fabricate(:user, username: "one", name: nil, groups: [group1, group2]) }
    fab!(:user2) { Fabricate(:user, username: "two", name: nil, groups: [group1]) }
    fab!(:user3) { Fabricate(:user, username: "three", name: nil, groups: [group3]) }
    fab!(:user4) { Fabricate(:user, username: "four", name: nil, groups: [group1, group3]) }
    fab!(:admin) { Fabricate(:admin, username: "admin", name: nil) }

    fab!(:topic) do
      t = Fabricate(:private_message_topic, title: "Super cool topic")
      t.allowed_users = [user1, user2, user3, user4, admin]
      t.allowed_groups = [group1]
      t
    end
    fab!(:posts) do
      [
        Fabricate(:post, topic: topic, post_number: 1, user: user2),
        Fabricate(:post, topic: topic, post_number: 2, user: user1),
        Fabricate(:post, topic: topic, post_number: 3, user: user2),
        Fabricate(:small_action, topic: topic, post_number: 4, user: admin),
        Fabricate(:post, topic: topic, post_number: 5, user: user4),
        Fabricate(:post, topic: topic, post_number: 6, user: user3),
        Fabricate(:post, topic: topic, post_number: 7, user: user4),
      ]
    end

    it "returns a list of participants (except for the recipient), groups first, followed by users in order of their last reply" do
      expect(UserNotifications.participants(posts.last, user3)).to eq(
        "[group1 (3)](http://test.localhost/g/group1), " \
          "[four](http://test.localhost/u/four), [two](http://test.localhost/u/two), [one](http://test.localhost/u/one), " \
          "[admin](http://test.localhost/u/admin)",
      )
    end

    it "caps the list according to site setting" do
      SiteSetting.max_participant_names = 3
      list =
        "[group1 (3)](http://test.localhost/g/group1), [four](http://test.localhost/u/four), [two](http://test.localhost/u/two)"
      expect(UserNotifications.participants(posts.last, user3)).to eq(
        I18n.t("user_notifications.more_pm_participants", participants: list, count: 2),
      )
    end

    it "orders groups by user count" do
      SiteSetting.max_participant_names = 3
      topic.allowed_groups = [group1, group2, group3]

      list =
        "[group1 (3)](http://test.localhost/g/group1), [group3 (2)](http://test.localhost/g/group3), [group2 (1)](http://test.localhost/g/group2)"
      expect(UserNotifications.participants(posts.last, user3)).to eq(
        I18n.t("user_notifications.more_pm_participants", participants: list, count: 4),
      )
    end

    it "orders users by their last reply and user id" do
      expect(UserNotifications.participants(posts[-3], user4)).to eq(
        "[group1 (3)](http://test.localhost/g/group1), " \
          "[two](http://test.localhost/u/two), [one](http://test.localhost/u/one), [three](http://test.localhost/u/three), " \
          "[admin](http://test.localhost/u/admin)",
      )
    end

    it "prefers full group names when available" do
      SiteSetting.max_participant_names = 2
      topic.allowed_groups = [group1, group2]

      group2.update!(full_name: "Awesome Group")

      list =
        "[group1 (3)](http://test.localhost/g/group1), [Awesome Group (1)](http://test.localhost/g/group2)"
      expect(UserNotifications.participants(posts.last, user3)).to eq(
        I18n.t("user_notifications.more_pm_participants", participants: list, count: 4),
      )
    end

    it "always uses usernames when prioritize_username_in_ux is enabled" do
      user4.update!(name: "James Bond")
      user1.update!(name: "Indiana Jones")

      SiteSetting.prioritize_username_in_ux = true
      expect(UserNotifications.participants(posts.last, user3)).to eq(
        "[group1 (3)](http://test.localhost/g/group1), " \
          "[four](http://test.localhost/u/four), [two](http://test.localhost/u/two), [one](http://test.localhost/u/one), " \
          "[admin](http://test.localhost/u/admin)",
      )

      SiteSetting.prioritize_username_in_ux = false
      expect(UserNotifications.participants(posts.last, user3)).to eq(
        "[group1 (3)](http://test.localhost/g/group1), " \
          "[James Bond](http://test.localhost/u/four), [two](http://test.localhost/u/two), [Indiana Jones](http://test.localhost/u/one), " \
          "[admin](http://test.localhost/u/admin)",
      )
    end

    it "reveals the email address of staged users if enabled" do
      user4.update!(staged: true, email: "[email protected]")
      user1.update!(staged: true, email: "[email protected]")

      SiteSetting.prioritize_username_in_ux = true
      expect(UserNotifications.participants(posts.last, user3, reveal_staged_email: true)).to eq(
        "[group1 (3)](http://test.localhost/g/group1), [email protected], [two](http://test.localhost/u/two), " \
          "[email protected], [admin](http://test.localhost/u/admin)",
      )
    end

    it "does only include human users" do
      topic.allowed_users << Discourse.system_user

      expect(UserNotifications.participants(posts.last, user3)).to eq(
        "[group1 (3)](http://test.localhost/g/group1), " \
          "[four](http://test.localhost/u/four), [two](http://test.localhost/u/two), [one](http://test.localhost/u/one), " \
          "[admin](http://test.localhost/u/admin)",
      )
    end
  end

  describe ".account_silenced" do
    fab!(:user_history) { Fabricate(:user_history, action: UserHistory.actions[:silence_user]) }

    context "when the dsa_reporting_enabled site setting is enabled" do
      before do
        enable_dsa_reporting
        SiteSetting.dsa_moderation_appeal_email = "[email protected]"
      end

      it "includes appeal instructions for temporary and permanent silences without a reviewable" do
        [1.day.from_now, 1000.years.from_now].each do |deadline|
          user.silenced_till = deadline

          mail = UserNotifications.account_silenced(user, user_history:)

          expect(mail.body.decoded).to include(
            "To appeal this decision, contact [email protected]",
          )
        end
      end
    end

    it "adds the silenced_till date in user's timezone" do
      user.user_option.timezone = "Asia/Tbilisi" # GMT+4
      user.silenced_till = DateTime.parse("May 25, 2020, 12:00pm")

      mail = UserNotifications.account_silenced(user, { user_history: user_history })

      expect(mail.body).to include("May 25, 2020,  4:00pm (UTC+04:00)")
    end

    it "uses the offset at the silence end date across daylight saving changes" do
      user.user_option.timezone = "America/New_York"

      {
        "2027-01-15T17:00:00Z" => "UTC-05:00",
        "2027-07-15T17:00:00Z" => "UTC-04:00",
      }.each do |deadline, offset|
        user.silenced_till = Time.iso8601(deadline)
        email = UserNotifications.account_silenced(user, user_history:)

        expect(email.body.decoded).to include(offset)
      end
    end

    it "falls back to UTC for an unrecognized timezone" do
      user.user_option.timezone = "Not/A_Timezone"
      user.silenced_till = Time.iso8601("2027-01-15T17:00:00Z")

      email = UserNotifications.account_silenced(user, user_history:)

      expect(email.body.decoded).to include("UTC+00:00")
    end

    it "uses the recipient locale and customized date format and wrapper" do
      SiteSetting.allow_user_locale = true
      user.locale = "fr"
      user.user_option.timezone = "Asia/Kolkata"
      user.silenced_till = Time.iso8601("2027-01-15T12:00:00Z")
      TranslationOverride.upsert!(:fr, "time.formats.long", "%d/%m/%Y à %H:%M")
      TranslationOverride.upsert!(
        :fr,
        "user_notifications.account_silenced.date_with_timezone",
        "%{date} (heure UTC%{offset})",
      )

      email = UserNotifications.account_silenced(user, user_history:)

      expect(email.body.decoded).to include("15/01/2027 à 17:30 (heure UTC+05:30)")
    end

    it "keeps permanent silences free of an expiry date" do
      user.silenced_till = 1000.years.from_now

      email = UserNotifications.account_silenced(user, user_history:)

      expect(email.body.decoded).not_to include("UTC", "until")
    end

    context "when user doesn't have timezone set" do
      before { user.user_option.timezone = nil }

      it "doesn't raise error" do
        expect { UserNotifications.account_silenced(user) }.not_to raise_error
      end

      it "adds the silenced_till date in UTC" do
        date = "May 25, 2020, 12:00pm"
        user.silenced_till = DateTime.parse(date)

        mail = UserNotifications.account_silenced(user, { user_history: user_history })

        expect(mail.body).to include("#{date} (UTC+00:00)")
      end
    end

    context "when user timezone is blank" do
      before { user.user_option.timezone = "" }

      it "doesn't raise error" do
        expect { UserNotifications.account_silenced(user) }.not_to raise_error
      end

      it "adds the silenced_till date in UTC" do
        date = "May 25, 2020, 12:00pm"
        user.silenced_till = DateTime.parse(date)

        mail = UserNotifications.account_silenced(user, { user_history: user_history })

        expect(mail.body).to include("#{date} (UTC+00:00)")
      end
    end
  end

  describe ".account_deleted" do
    fab!(:reviewable) { Fabricate(:reviewable_flagged_post, reviewable_scores: []) }

    context "when the dsa_reporting_enabled site setting is enabled" do
      before do
        enable_dsa_reporting
        SiteSetting.dsa_moderation_appeal_email = "[email protected]"
      end

      it "includes appeal instructions in account deletion emails" do
        mail = UserNotifications.account_deleted("[email protected]", reviewable)

        expect(mail.body.decoded).to include("To appeal this decision, contact [email protected]")
      end
    end

    it "includes flag reason for standard flags" do
      Fabricate(
        :reviewable_score,
        reviewable: reviewable,
        reviewable_score_type: PostActionType.types[:spam],
      )

      reviewable.reload
      mail = UserNotifications.account_deleted("[email protected]", reviewable)

      expect(mail.body).to include(I18n.t("flag_reasons.spam"))
      expect(mail.body).to_not include(I18n.t("flag_reasons.illegal"))
    end

    it "includes flag reason for automated system flags" do
      Fabricate(
        :reviewable_score,
        reviewable: reviewable,
        reviewable_score_type: ReviewableScore.types[:needs_approval],
      )
      reviewable.reload

      mail = UserNotifications.account_deleted("[email protected]", reviewable)

      expect(mail.body).to include(I18n.t("flag_reasons.needs_approval"))
      expect(mail.body).to_not include(I18n.t("flag_reasons.spam"))
    end

    it "falls back to the default spam reason if no score is present" do
      mail = UserNotifications.account_deleted("[email protected]", reviewable)

      expect(mail.body).to include(I18n.t("flag_reasons.spam"))
      expect(mail.body).to_not include(I18n.t("flag_reasons.illegal"))
    end

    it "falls back to the flag's description for custom flags" do
      custom_flag =
        Fabricate(
          :flag,
          name_key: "custom_delete_flag",
          description: "This is a custom deletion reason.",
          applies_to: %w[Post],
        )

      Fabricate(:reviewable_score, reviewable: reviewable, reviewable_score_type: custom_flag.id)
      reviewable.reload

      mail = UserNotifications.account_deleted("[email protected]", reviewable)

      expect(mail.body).to include(custom_flag.description)
      expect(mail.body).to_not include(I18n.t("flag_reasons.spam"))
    end
  end

  describe ".account_associated" do
    it "names the provider the account was linked to" do
      mail = UserNotifications.account_associated(user, provider_name: "Google")

      expect(mail.to).to contain_exactly(user.email)
      expect(mail.subject).to include(
        I18n.t("user_notifications.account_associated.title", locale: :en),
      )
      expect(mail.body.encoded).to include("A Google account was just linked")
    end
  end

  describe ".account_suspended" do
    fab!(:user_history) { Fabricate(:user_history, action: UserHistory.actions[:suspend_user]) }

    context "when the dsa_reporting_enabled site setting is enabled" do
      before do
        enable_dsa_reporting
        SiteSetting.dsa_moderation_appeal_email = "[email protected]"
      end

      it "includes appeal instructions for temporary and permanent suspensions without a reviewable" do
        [1.day.from_now, 1000.years.from_now].each do |deadline|
          user.suspended_till = deadline

          mail = UserNotifications.account_suspended(user, user_history:)

          expect(mail.body.decoded).to include(
            "To appeal this decision, contact [email protected]",
          )
        end
      end
    end

    it "adds the suspended_till date in user's timezone" do
      user.user_option.timezone = "Asia/Tbilisi" # GMT+4
      user.suspended_till = DateTime.parse("May 25, 2020, 12:00pm")

      mail = UserNotifications.account_suspended(user, { user_history: user_history })

      expect(mail.body).to include("May 25, 2020,  4:00pm (UTC+04:00)")
    end

    it "uses the offset at the suspension end date across daylight saving changes" do
      user.user_option.timezone = "America/New_York"

      {
        "2027-01-15T17:00:00Z" => "UTC-05:00",
        "2027-07-15T17:00:00Z" => "UTC-04:00",
      }.each do |deadline, offset|
        user.suspended_till = Time.iso8601(deadline)
        email = UserNotifications.account_suspended(user, user_history:)
        expect(email.body.decoded).to include(offset)
      end
    end

    it "falls back to UTC for an unrecognized timezone" do
      user.user_option.timezone = "Not/A_Timezone"
      user.suspended_till = Time.iso8601("2027-01-15T17:00:00Z")

      email = UserNotifications.account_suspended(user, user_history:)

      expect(email.body.decoded).to include("UTC+00:00")
    end

    it "uses the recipient locale and customized date format" do
      SiteSetting.allow_user_locale = true
      user.locale = "fr"
      user.user_option.timezone = "Asia/Kolkata"
      user.suspended_till = Time.iso8601("2027-01-15T12:00:00Z")
      TranslationOverride.upsert!(:fr, "time.formats.long", "%d/%m/%Y à %H:%M")

      email = UserNotifications.account_suspended(user, user_history:)

      expect(email.body.decoded).to include("15/01/2027 à 17:30 (UTC+05:30)")
    end

    it "keeps permanent suspensions free of an expiry date" do
      user.suspended_till = 1000.years.from_now

      email = UserNotifications.account_suspended(user, user_history:)

      expect(email.body.decoded).to include("your account has been suspended.")
      expect(email.body.decoded).not_to include("UTC")
    end

    context "when user doesn't have timezone set" do
      before { user.user_option.timezone = nil }

      it "doesn't raise error" do
        expect { UserNotifications.account_suspended(user) }.not_to raise_error
      end

      it "adds the suspended_till date in UTC" do
        date = "May 25, 2020, 12:00pm"
        user.suspended_till = DateTime.parse(date)

        mail = UserNotifications.account_suspended(user, { user_history: user_history })

        expect(mail.body).to include("#{date} (UTC+00:00)")
      end
    end

    context "when user timezone is blank" do
      before { user.user_option.timezone = "" }

      it "doesn't raise error" do
        expect { UserNotifications.account_suspended(user) }.not_to raise_error
      end

      it "adds the suspended_till date in UTC" do
        date = "May 25, 2020, 12:00pm"
        user.suspended_till = DateTime.parse(date)

        mail = UserNotifications.account_suspended(user, { user_history: user_history })

        expect(mail.body).to include("#{date} (UTC+00:00)")
      end
    end
  end

  describe ".signup_after_reject" do
    context "when the dsa_reporting_enabled site setting is enabled" do
      before do
        enable_dsa_reporting
        SiteSetting.dsa_moderation_appeal_email = "[email protected]"
      end

      it "includes the DSA appeal address in signup rejection emails" do
        mail = UserNotifications.signup_after_reject(user, reject_reason: "Account not approved.")

        expect(mail.body.decoded).to include("To appeal this decision, contact [email protected]")
      end
    end
  end

  describe "improved email subject templates" do
    def assert_improved_template_format(base_key)
      original = I18n.t("user_notifications.#{base_key}.subject_template")
      improved = I18n.t("user_notifications.#{base_key}.subject_template_improved")

      # subject changed from "[Discourse] my topic title" to "Discourse: my topic title"
      expect(original).to include("[%{email_prefix}]")
      expect(improved).to include("%{email_prefix}:")
      expect(improved).not_to match(/\[.*\]/)
    end

    describe "notification email templates" do
      %w[
        user_replied
        user_replied_pm
        user_quoted
        user_mentioned
        user_mentioned_pm
        user_posted
        user_posted_pm
      ].each do |template_key|
        it "has improved version for #{template_key}" do
          assert_improved_template_format(template_key)
        end
      end
    end

    describe "account-related email templates" do
      %w[account_exists account_suspended account_silenced].each do |template_key|
        it "has improved version for #{template_key} without email_prefix" do
          improved = I18n.t("user_notifications.#{template_key}.subject_template_improved")

          expect(improved).not_to include("%{email_prefix}")
        end
      end
    end
  end
end