A platform for community discussion. Free, open, simple.
FEATURE: Implement ad impressions tracking (#35797)
Juan David Martínez Cubilloscc7f4743a5a3
diff --git a/plugins/discourse-adplugin/admin/assets/javascripts/admin/adplugin-route-map.js b/plugins/discourse-adplugin/admin/assets/javascripts/admin/adplugin-route-map.jsindex 6a45cfb978e..d1b0f6fa2ba 100644--- a/plugins/discourse-adplugin/admin/assets/javascripts/admin/adplugin-route-map.js+++ b/plugins/discourse-adplugin/admin/assets/javascripts/admin/adplugin-route-map.js@@ -4,7 +4,7 @@ export default {map() {this.route("houseAds", { path: "/pluginad/house_creatives" }, function () {this.route("index", { path: "/" });- this.route("show", { path: "/:ad_id" });+ this.route("show", { path: "/:id" });});},};diff --git a/plugins/discourse-adplugin/admin/assets/javascripts/admin/controllers/admin-plugins/house-ads/show.js b/plugins/discourse-adplugin/admin/assets/javascripts/admin/controllers/admin-plugins/house-ads/show.jsindex 3164f9c6099..8148bda3b70 100644--- a/plugins/discourse-adplugin/admin/assets/javascripts/admin/controllers/admin-plugins/house-ads/show.js+++ b/plugins/discourse-adplugin/admin/assets/javascripts/admin/controllers/admin-plugins/house-ads/show.js@@ -6,7 +6,6 @@ import { TrackedObject } from "@ember-compat/tracked-built-ins";import { observes } from "@ember-decorators/object";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";-import Category from "discourse/models/category";import { i18n } from "discourse-i18n";import Preview from "../../../components/modal/preview";@@ -26,13 +25,12 @@ export default class adminPluginsHouseAdsShow extends Controller {modelChanged() {this.buffered = new TrackedObject({ ...this.model });this.selectedCategories = this.model.categories || [];- this.selectedGroups = this.model.group_ids || [];+ this.selectedGroups = this.model.groups || [];}get disabledSave() {for (const key in this.buffered) {- // we don't want to compare the categories array- if (key !== "categories" && this.buffered[key] !== this.model[key]) {+ if (this.buffered[key] !== this.model[key]) {return false;}}@@ -54,8 +52,12 @@ export default class adminPluginsHouseAdsShow extends Controller {data.visible_to_logged_in_users =this.buffered.visible_to_logged_in_users;data.visible_to_anons = this.buffered.visible_to_anons;- data.category_ids = this.buffered.category_ids;- data.group_ids = this.buffered.group_ids;+ data.category_ids = this.buffered.categories+ ? this.buffered.categories.map((c) => c.id)+ : [];+ data.group_ids = this.buffered.groups+ ? this.buffered.groups.map((g) => g.id)+ : [];try {const ajaxData = await ajax(newRecord@@ -95,22 +97,20 @@ export default class adminPluginsHouseAdsShow extends Controller {@actionsetCategoryIds(categoryArray) {this.selectedCategories = categoryArray;- this.buffered.category_ids = categoryArray.map((c) => c.id);- this.setCategoriesForBuffered();+ this.buffered.categories = this.selectedCategories;}@actionsetGroupIds(groupIds) {this.selectedGroups = groupIds;- this.buffered.group_ids = groupIds.map((id) => id);+ this.buffered.groups = groupIds;}@actioncancel() {this.buffered = new TrackedObject({ ...this.model });this.selectedCategories = this.model.categories || [];- this.selectedGroups = this.model.group_ids || [];- this.setCategoriesForBuffered();+ this.selectedGroups = this.model.groups || [];}@action@@ -145,14 +145,4 @@ export default class adminPluginsHouseAdsShow extends Controller {},});}-- setCategoriesForBuffered() {- // we need to fetch the categories because the serializer is not being used- // to attach the category object to the house ads- this.buffered.categories = this.buffered.category_ids- ? this.buffered.category_ids.map((categoryId) =>- Category.findById(categoryId)- )- : [];- }}diff --git a/plugins/discourse-adplugin/admin/assets/javascripts/admin/routes/admin-plugins/house-ads/show.js b/plugins/discourse-adplugin/admin/assets/javascripts/admin/routes/admin-plugins/house-ads/show.jsindex 41b9b41b709..6b9316b66f7 100644--- a/plugins/discourse-adplugin/admin/assets/javascripts/admin/routes/admin-plugins/house-ads/show.js+++ b/plugins/discourse-adplugin/admin/assets/javascripts/admin/routes/admin-plugins/house-ads/show.js@@ -4,7 +4,7 @@ import { i18n } from "discourse-i18n";export default class AdminPluginsHouseAdsShow extends DiscourseRoute {model(params) {- if (params.ad_id === "new") {+ if (params.id === "new") {return new TrackedObject({name: i18n("admin.adplugin.house_ads.new_name"),html: "",@@ -12,11 +12,17 @@ export default class AdminPluginsHouseAdsShow extends DiscourseRoute {visible_to_anons: true,});} else {- return new TrackedObject(- this.modelFor("adminPlugins.houseAds").find(- (item) => item.id === parseInt(params.ad_id, 10)- )+ const houseAd = this.modelFor("adminPlugins.houseAds").find(+ (item) => item.id === parseInt(params.id, 10));++ if (houseAd.groups && Array.isArray(houseAd.groups)) {+ houseAd.groups = houseAd.groups.map((g) => {+ return g.id;+ });+ }++ return new TrackedObject(houseAd);}}}diff --git a/plugins/discourse-adplugin/admin/assets/javascripts/admin/templates/plugins-house-ads-show.gjs b/plugins/discourse-adplugin/admin/assets/javascripts/admin/templates/plugins-house-ads-show.gjsindex 1a292cfda69..21de779fe04 100644--- a/plugins/discourse-adplugin/admin/assets/javascripts/admin/templates/plugins-house-ads-show.gjs+++ b/plugins/discourse-adplugin/admin/assets/javascripts/admin/templates/plugins-house-ads-show.gjs@@ -55,8 +55,8 @@ export default <template><GroupChooser@content={{@controller.site.groups}}- @onChange={{@controller.setGroupIds}}@value={{@controller.selectedGroups}}+ @onChange={{@controller.setGroupIds}}class="banner-groups"/><div class="description">diff --git a/plugins/discourse-adplugin/app/controllers/ad_plugin/ad_impressions_controller.rb b/plugins/discourse-adplugin/app/controllers/ad_plugin/ad_impressions_controller.rbnew file mode 100644index 00000000000..aa195bee7e3--- /dev/null+++ b/plugins/discourse-adplugin/app/controllers/ad_plugin/ad_impressions_controller.rb@@ -0,0 +1,41 @@+# frozen_string_literal: true+module AdPlugin+ class AdImpressionsController < ::ApplicationController+ requires_plugin PLUGIN_NAME++ skip_before_action :check_xhr, :preload_json, only: [:update]++ def create+ impression =+ AdPlugin::AdImpression.create!(impression_params.merge(user_id: current_user&.id))++ render json: impression.as_json(only: %i[id ad_type placement user_id])+ end++ def update+ impression = AdPlugin::AdImpression.find(params[:id])++ result = impression.record_click!++ if result+ render json: { success: true, clicked_at: impression.clicked_at }+ else+ render json: {+ success: false,+ error: I18n.t("errors.already_clicked"),+ },+ status: :unprocessable_entity+ end+ end++ private++ def impression_params+ required_params =+ params.require(:ad_plugin_impression).permit(:ad_type, :ad_plugin_house_ad_id, :placement)++ required_params[:ad_type] = required_params[:ad_type].to_i+ required_params+ end+ end+enddiff --git a/plugins/discourse-adplugin/app/controllers/ad_plugin/house_ads_controller.rb b/plugins/discourse-adplugin/app/controllers/ad_plugin/house_ads_controller.rbindex 87964b42084..c2094925f30 100644--- a/plugins/discourse-adplugin/app/controllers/ad_plugin/house_ads_controller.rb+++ b/plugins/discourse-adplugin/app/controllers/ad_plugin/house_ads_controller.rb@@ -7,41 +7,78 @@ module AdPlugindef indexrender_json_dump(house_ads:- HouseAd.all.map do |ad|- ad.to_hash.merge!(categories: Category.secured(@guardian).where(id: ad.category_ids))- end,+ serialize_data(+ HouseAd.all,+ HouseAdSerializer,+ { include_categories: true, include_groups: true },+ ),settings: HouseAdSetting.all,)enddef show- house_ad_hash = HouseAd.find(params[:id])&.to_hash- if house_ad_hash- house_ad_hash.merge!(- categories: Category.secured(@guardian).where(id: house_ad_hash[:category_ids]),+ house_ad = HouseAd.find_by(id: params[:id])+ if house_ad+ render_json_dump(+ house_ad:+ serialize_data(+ house_ad,+ HouseAdSerializer,+ { include_categories: true, include_groups: true },+ ),)+ else+ render_json_error(I18n.t("not_found"), status: 404)end- render_json_dump(house_ad: house_ad_hash)enddef create- ad = HouseAd.create(house_ad_params)- ad.valid? ? render_json_dump(house_ad: ad.to_hash) : render_json_error(ad)+ ad = HouseAd.new(house_ad_params)+ if ad.save+ render_json_dump(+ serialize_data(ad, HouseAdSerializer, { include_categories: true, include_groups: true }),+ )+ else+ render_json_error(ad)+ endenddef update- if ad = HouseAd.find(house_ad_params[:id])- ad.update(house_ad_params)+ ad = HouseAd.find_by(id: house_ad_params[:id])++ if ad.nil?+ ad = HouseAd.new(house_ad_params.except(:id))+ if ad.save+ render_json_dump(+ serialize_data(+ ad,+ HouseAdSerializer,+ { include_categories: true, include_groups: true },+ ),+ )+ else+ render_json_error(ad)+ endelse- ad = HouseAd.create(house_ad_params.except(:id))+ if ad.update(house_ad_params.except(:id))+ render_json_dump(+ serialize_data(+ ad,+ HouseAdSerializer,+ { include_categories: true, include_groups: true },+ ),+ )+ else+ render_json_error(ad)+ endend-- ad.valid? ? render_json_dump(house_ad: ad.to_hash) : render_json_error(ad)enddef destroy- if ad = HouseAd.find(house_ad_params[:id])+ ad = HouseAd.find_by(id: house_ad_params[:id])+ if adad.destroy+ render json: success_jsonelserender_json_error(I18n.t("not_found"), status: 404)end@@ -68,6 +105,9 @@ module AdPluginpermitted[:visible_to_anons] = ActiveModel::Type::Boolean.new.cast(permitted[:visible_to_anons],)++ permitted[:group_ids] ||= [] if !params.key?(:group_ids)+ permitted[:category_ids] ||= [] if !params.key?(:category_ids)permittedendenddiff --git a/plugins/discourse-adplugin/app/models/ad_plugin/ad_impression.rb b/plugins/discourse-adplugin/app/models/ad_plugin/ad_impression.rbnew file mode 100644index 00000000000..d497027e7a2--- /dev/null+++ b/plugins/discourse-adplugin/app/models/ad_plugin/ad_impression.rb@@ -0,0 +1,71 @@+# frozen_string_literal: true++module AdPlugin+ class AdImpression < ActiveRecord::Base+ self.table_name = "ad_plugin_impressions"++ belongs_to :house_ad,+ class_name: "AdPlugin::HouseAd",+ foreign_key: "ad_plugin_house_ad_id",+ optional: true++ belongs_to :user, optional: true++ enum :ad_type, AdType.enum_hash++ validates :ad_type, presence: true+ validates :placement, presence: true++ validates :ad_plugin_house_ad_id, presence: true, if: :house?++ validate :house_ad_id_consistency++ def record_click!+ return false if clicked?++ update(clicked_at: Time.zone.now)+ end++ def clicked?+ clicked_at.present?+ end++ private++ def house_ad_id_consistency+ if house? && ad_plugin_house_ad_id.nil?+ errors.add(:ad_plugin_house_ad_id, "must be present for house ads")+ elsif !house? && ad_plugin_house_ad_id.present?+ errors.add(:ad_plugin_house_ad_id, "must be nil for external ads")+ end+ end+ end+end++# == Schema Information+#+# Table name: ad_plugin_impressions+#+# id :bigint not null, primary key+# ad_type :integer not null+# placement :string not null+# created_at :datetime not null+# updated_at :datetime not null+# ad_plugin_house_ad_id :bigint+# user_id :integer+# clicked_at :datetime+#+# Indexes+#+# index_ad_plugin_impressions_on_ad_plugin_house_ad_id (ad_plugin_house_ad_id)+# index_ad_plugin_impressions_on_ad_type (ad_type)+# index_ad_plugin_impressions_on_ad_type_and_placement (ad_type,placement)+# index_ad_plugin_impressions_on_clicked_at (clicked_at)+# index_ad_plugin_impressions_on_created_at (created_at)+# index_ad_plugin_impressions_on_user_id (user_id)+#+# Foreign Keys+#+# fk_rails_... (ad_plugin_house_ad_id => ad_plugin_house_ads.id) ON DELETE => cascade+# fk_rails_... (user_id => users.id) ON DELETE => nullify+#diff --git a/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rbindex a2d48eaf849..32e61753a97 100644--- a/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb+++ b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb@@ -1,154 +1,96 @@# frozen_string_literal: truemodule AdPlugin- class HouseAd- include ActiveModel::Validations-- attr_accessor :id,- :name,- :html,- :visible_to_logged_in_users,- :visible_to_anons,- :category_ids,- :group_ids+ class HouseAd < ActiveRecord::Base+ self.table_name = "ad_plugin_house_ads"NAME_REGEX = /\A[[:alnum:]\s\.,'!@#$%&\*\-\+\=:]*\z/i- validates :name, presence: true, format: { with: NAME_REGEX }- validates :html, presence: true+ has_many :impressions,+ class_name: "AdPlugin::AdImpression",+ foreign_key: "ad_plugin_house_ad_id",+ dependent: :destroy- validate do- if self.class.all.any? { |ad| ad.id != self.id && ad.name.downcase == self.name.downcase }- errors.add(:name, :taken) # unique name- end- end+ has_and_belongs_to_many :groups,+ join_table: "ad_plugin_house_ads_groups",+ foreign_key: "ad_plugin_house_ad_id",+ association_foreign_key: "group_id"- def initialize- @name = "New Ad"- @html = "<div class='house-ad'>New Ad</div>"- @visible_to_logged_in_users = true- @visible_to_anons = true- @group_ids = []- @category_ids = []- end+ has_and_belongs_to_many :categories,+ join_table: "ad_plugin_house_ads_categories",+ foreign_key: "ad_plugin_house_ad_id",+ association_foreign_key: "category_id"- def self.from_hash(h)- ad = self.new- ad.name = h[:name]- ad.html = h[:html]- ad.id = h[:id].to_i if h[:id]- ad.visible_to_logged_in_users = h[:visible_to_logged_in_users] if h.key?(- :visible_to_logged_in_users,- )- ad.visible_to_anons = h[:visible_to_anons] if h.key?(:visible_to_anons)- ad.group_ids = h[:group_ids].map(&:to_i) if h.key?(:group_ids)- ad.category_ids = h[:category_ids].map(&:to_i) if h.key?(:category_ids)- ad- end+ validates :name, presence: true, uniqueness: true, format: { with: NAME_REGEX }+ validates :html, presence: true- def self.create(attrs)- ad = from_hash(attrs)- ad.save- ad- end+ scope :for_anons, -> { where(visible_to_anons: true) }+ scope :for_logged_in, -> { where(visible_to_logged_in_users: true) }- def self.alloc_id- DistributedMutex.synchronize("adplugin-house-ad-id") do- max_id = AdPlugin.pstore_get("ad:_id")- max_id = 1 unless max_id- AdPlugin.pstore_set("ad:_id", max_id + 1)- max_id- end- end-- def self.find(id)- if r = AdPlugin.pstore_get("ad:#{id}")- from_hash(r)- else- nil- end- end-- def self.all- PluginStoreRow- .where(plugin_name: AdPlugin::PLUGIN_NAME)- .where("key LIKE 'ad:%'")- .where("key != 'ad:_id'")- .map { |psr| from_hash(PluginStore.cast_value(psr.type_name, psr.value)) }- .sort_by { |ad| ad.id }- end+ after_destroy :clear_cache+ after_save :clear_cachedef self.all_for_anons- self.all.select(&:visible_to_anons)+ for_anons.to_aenddef self.all_for_logged_in_users(scope)- if scope.nil?- # this is for our admin page, so we don't need to filter by group- self.all.select(&:visible_to_logged_in_users)- else- # otherwise, filter by group and visible categories- self.all.select do |ad|- (- ad.group_ids.any? { |group_id| scope.user.groups.pluck(:id).include?(group_id) } ||- ad.group_ids.include?(Group::AUTO_GROUPS[:everyone]) || ad.group_ids.empty?- ) && ad.visible_to_logged_in_users &&- (- ad.category_ids.any? do |category_id|- Category.secured(scope).pluck(:id).include?(category_id)- end || true- )- end- end+ query = for_logged_in+ return query if scope.nil?++ query =+ query+ .left_joins(:groups)+ .where(+ "ad_plugin_house_ads_groups.group_id IN (?) OR ad_plugin_house_ads_groups.group_id = ? OR ad_plugin_house_ads_groups.group_id IS NULL",+ scope.user.group_ids,+ Group::AUTO_GROUPS[:everyone],+ )+ .distinct++ category_ids = Category.secured(scope).pluck(:id)+ query =+ query+ .left_joins(:categories)+ .where(+ "ad_plugin_house_ads_categories.category_id IN (?) OR ad_plugin_house_ads_categories.category_id IS NULL",+ category_ids,+ )+ .distinct++ query.to_aend- def save- if self.valid?- self.id = self.class.alloc_id if self.id.to_i <= 0- AdPlugin.pstore_set("ad:#{id}", to_hash)- Site.clear_anon_cache!- self.class.publish_if_ads_enabled- true- else- false- end- end+ private- def update(attrs)- self.name = attrs[:name]- self.html = attrs[:html]- self.visible_to_logged_in_users = attrs[:visible_to_logged_in_users] if attrs.key?(- :visible_to_logged_in_users,- )- self.visible_to_anons = attrs[:visible_to_anons] if attrs.key?(:visible_to_anons)- # ensure that group_ids and category_ids can be set to an empty array- self.group_ids = attrs.key?(:group_ids) ? attrs[:group_ids].map(&:to_i) : []- self.category_ids = attrs.key?(:category_ids) ? attrs[:category_ids].map(&:to_i) : []- self.save- end-- def to_hash- {- id: @id,- name: @name,- html: @html,- visible_to_logged_in_users: @visible_to_logged_in_users,- visible_to_anons: @visible_to_anons,- group_ids: @group_ids,- category_ids: @category_ids,- }- end-- def destroy- AdPlugin.pstore_delete("ad:#{id}")+ def clear_cacheSite.clear_anon_cache!self.class.publish_if_ads_enabledenddef self.publish_if_ads_enabled- if AdPlugin::HouseAdSetting.all.any? { |_, adsToShow| adsToShow.present? }+ if AdPlugin::HouseAdSetting.all.any? { |_, ads_to_show| ads_to_show.present? }AdPlugin::HouseAdSetting.publish_settingsendendendend++# == Schema Information+#+# Table name: ad_plugin_house_ads+#+# id :bigint not null, primary key+# html :text not null+# name :string not null+# visible_to_anons :boolean default(TRUE), not null+# visible_to_logged_in_users :boolean default(TRUE), not null+# created_at :datetime not null+# updated_at :datetime not null+#+# Indexes+#+# index_ad_plugin_house_ads_on_name (name) UNIQUE+# index_ad_plugin_house_ads_on_visible_to_anons (visible_to_anons)+# index_ad_plugin_house_ads_on_visible_to_logged_in_users (visible_to_logged_in_users)+#diff --git a/plugins/discourse-adplugin/app/models/ad_plugin/house_ad_setting.rb b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad_setting.rbindex 5de9ec4bafe..83a018d70e1 100644--- a/plugins/discourse-adplugin/app/models/ad_plugin/house_ad_setting.rb+++ b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad_setting.rb@@ -41,7 +41,7 @@ module AdPlugin),creatives:ads.inject({}) do |h, ad|- h[ad.name] = { html: ad.html, category_ids: ad.category_ids }+ h[ad.name] = { id: ad.id, html: ad.html, category_ids: ad.category_ids }hend,}diff --git a/plugins/discourse-adplugin/app/models/concerns/reports/ad_plugin.rb b/plugins/discourse-adplugin/app/models/concerns/reports/ad_plugin.rbnew file mode 100644index 00000000000..55947a60c08--- /dev/null+++ b/plugins/discourse-adplugin/app/models/concerns/reports/ad_plugin.rb@@ -0,0 +1,443 @@+# frozen_string_literal: true+module Reports::AdPlugin+ extend ActiveSupport::Concern++ class_methods do+ # Ad Impressions Report - All ads by type and placement+ def report_ad_plugin_ad_impressions(report)+ report.icon = "rectangle-ad"+ report.modes = [:table]++ report.labels = [+ { type: :text, property: :ad_name, title: "Ad Name" },+ { type: :text, property: :ad_type, title: "Ad Type" },+ { type: :text, property: :placement, title: "Placement" },+ { type: :number, property: :impressions, title: "Impressions" },+ ]++ start_date = report.start_date+ end_date = report.end_date+ limit = report.limit || 50++ sql = <<~SQL+ SELECT+ COALESCE(ha.name,+ CASE ai.ad_type+ WHEN 1 THEN 'Google AdSense'+ WHEN 2 THEN 'Google DFP'+ WHEN 3 THEN 'Amazon Product Links'+ WHEN 4 THEN 'Carbon Ads'+ WHEN 5 THEN 'AdButler'+ END+ ) as ad_name,+ CASE ai.ad_type+ WHEN 0 THEN 'House Ad'+ WHEN 1 THEN 'AdSense'+ WHEN 2 THEN 'DFP'+ WHEN 3 THEN 'Amazon'+ WHEN 4 THEN 'Carbon'+ WHEN 5 THEN 'AdButler'+ END as ad_type,+ ai.placement,+ COUNT(*) as impressions+ FROM ad_plugin_impressions ai+ LEFT JOIN ad_plugin_house_ads ha ON ai.ad_plugin_house_ad_id = ha.id+ WHERE ai.created_at >= :start_date+ AND ai.created_at <= :end_date+ GROUP BY ha.name, ai.ad_type, ai.placement+ ORDER BY impressions DESC+ LIMIT :limit+ SQL++ results = DB.query(sql, start_date: start_date, end_date: end_date, limit: limit)++ report.data =+ results.map do |row|+ {+ ad_name: row.ad_name || "Unknown",+ ad_type: row.ad_type,+ placement: row.placement,+ impressions: row.impressions,+ }+ end+ end++ # House Ads Performance Report - Only house ads with detailed metrics+ def report_ad_plugin_house_ads_performance(report)+ report.icon = "rectangle-ad"+ report.modes = [:table]++ report.labels = [+ { type: :text, property: :ad_name, title: "House Ad" },+ { type: :text, property: :placement, title: "Placement" },+ { type: :number, property: :impressions, title: "Impressions" },+ { type: :number, property: :unique_users, title: "Unique Users" },+ ]++ house_ad_name_filter = report.filters.dig(:house_ad_name)++ house_ad_choices =+ ::AdPlugin::HouseAd.order(:name).pluck(:name).map { |name| { id: name, name: name } }+ house_ad_choices.unshift({ id: "any", name: "All House Ads" })++ placement_filter = report.filters.dig(:ad_placement)++ placement_choices =+ AdPlugin::HouseAdSetting::DEFAULTS.keys.map do |name|+ name = name.to_s.split("_").join("-")+ { id: name, name: name }+ end++ placement_choices.unshift({ id: "any", name: "All" })++ report.add_filter(+ "house_ad_name",+ type: "list",+ default: house_ad_name_filter || "any",+ choices: house_ad_choices,+ allow_any: false,+ auto_insert_none_item: false,+ )++ report.add_filter(+ "ad_placement",+ type: "list",+ default: placement_filter || "any",+ choices: placement_choices,+ allow_any: false,+ auto_insert_none_item: false,+ )++ user_type_filter = report.filters.dig(:user_type)++ user_type_choices = [+ { id: "all", name: "All Users" },+ { id: "logged_in", name: "Logged In Users" },+ { id: "anonymous", name: "Anonymous Users" },+ ]++ report.add_filter(+ "user_type",+ type: "list",+ default: user_type_filter || "all",+ choices: user_type_choices,+ allow_any: false,+ auto_insert_none_item: false,+ )++ start_date = report.start_date+ end_date = report.end_date+ limit = report.limit || 50++ user_type_condition =+ case user_type_filter+ when "logged_in"+ "AND ai.user_id IS NOT NULL"+ when "anonymous"+ "AND ai.user_id IS NULL"+ else+ "" # "all" - no filter+ end++ sql = <<~SQL+ SELECT+ ha.name as ad_name,+ ai.placement,+ COUNT(*) as impressions,+ COUNT(DISTINCT ai.user_id) as unique_users+ FROM ad_plugin_impressions ai+ INNER JOIN ad_plugin_house_ads ha ON ai.ad_plugin_house_ad_id = ha.id+ WHERE ai.created_at >= :start_date+ AND ai.created_at <= :end_date+ AND ai.ad_type = 0+ #{user_type_condition}+ #{house_ad_name_filter && house_ad_name_filter != "any" ? "AND ha.name = :house_ad_name" : ""}+ #{placement_filter && placement_filter != "any" ? "AND ai.placement = :ad_placement" : ""}+ GROUP BY ha.id, ha.name, ai.placement+ ORDER BY impressions DESC+ LIMIT :limit+ SQL++ query_params = { start_date: start_date, end_date: end_date, limit: limit }++ query_params[:house_ad_name] = house_ad_name_filter if house_ad_name_filter &&+ house_ad_name_filter != "any"++ query_params[:ad_placement] = placement_filter if placement_filter &&+ placement_filter != "any"++ results = DB.query(sql, query_params)++ report.data =+ results.map do |row|+ {+ ad_name: row.ad_name,+ placement: row.placement,+ impressions: row.impressions,+ unique_users: row.unique_users,+ }+ end+ end++ def report_ad_plugin_impressions_by_user(report)+ report.icon = "rectangle-ad"+ report.modes = [:table]++ report.labels = [+ {+ type: :user,+ properties: {+ username: :username,+ id: :user_id,+ avatar: :avatar_template,+ },+ title: "User",+ },+ { type: :number, property: :impressions, title: "Impressions" },+ ]++ # Add ad_type filter+ ad_type_filter = report.filters.dig(:ad_type)++ ad_type_choices =+ ::AdPlugin::AdType.types.map { |key, value| { id: value.to_s, name: key.to_s.titleize } }+ ad_type_choices.unshift({ id: "any", name: "All Ad Types" })++ report.add_filter(+ "ad_type",+ type: "list",+ default: ad_type_filter || "any",+ choices: ad_type_choices,+ allow_any: false,+ auto_insert_none_item: false,+ )+ start_date = report.start_date+ end_date = report.end_date+ limit = report.limit || 50++ # Build SQL with optional ad_type filter+ sql = <<~SQL+ SELECT+ u.username,+ u.id as user_id,+ u.uploaded_avatar_id,+ COUNT(*) as impressions+ FROM ad_plugin_impressions ai+ INNER JOIN users u ON u.id = ai.user_id+ WHERE ai.created_at >= :start_date+ AND ai.created_at <= :end_date+ #{ad_type_filter && ad_type_filter != "any" ? "AND ai.ad_type = :ad_type" : ""}+ GROUP BY u.id, u.username, u.uploaded_avatar_id+ ORDER BY impressions DESC+ LIMIT :limit+ SQL++ # Build query params+ query_params = { start_date: start_date, end_date: end_date, limit: limit }+ query_params[:ad_type] = ad_type_filter.to_i if ad_type_filter && ad_type_filter != "any"++ results = DB.query(sql, query_params)++ report.data =+ results.map do |row|+ {+ username: row.username,+ user_id: row.user_id,+ avatar_template: User.avatar_template(row.username, row.uploaded_avatar_id),+ impressions: row.impressions,+ }+ end+ end++ def report_ad_plugin_click_through_rate(report)+ report.icon = "rectangle-ad"+ report.modes = [:table]++ report.labels = [+ { type: :text, property: :ad_name, title: "Ad Name" },+ { type: :text, property: :ad_type, title: "Ad Type" },+ { type: :text, property: :placement, title: "Placement" },+ { type: :number, property: :impressions, title: "Impressions" },+ { type: :number, property: :clicks, title: "Clicks" },+ { type: :percent, property: :ctr, title: "CTR" },+ ]++ start_date = report.start_date+ end_date = report.end_date+ limit = report.limit || 50++ sql = <<~SQL+ WITH agg AS (+ SELECT+ ai.ad_plugin_house_ad_id,+ ai.ad_type,+ ai.placement,+ COUNT(*) AS impressions,+ SUM(CASE WHEN ai.clicked_at IS NOT NULL THEN 1 ELSE 0 END) AS clicks+ FROM ad_plugin_impressions ai+ WHERE ai.created_at BETWEEN :start_date AND :end_date+ GROUP BY ai.ad_plugin_house_ad_id, ai.ad_type, ai.placement+ )+ SELECT+ COALESCE(+ ha.name,+ CASE agg.ad_type+ WHEN 1 THEN 'Google AdSense'+ WHEN 2 THEN 'Google DFP'+ WHEN 3 THEN 'Amazon Product Links'+ WHEN 4 THEN 'Carbon Ads'+ WHEN 5 THEN 'AdButler'+ END+ ) AS ad_name,+ CASE agg.ad_type+ WHEN 0 THEN 'House Ad'+ WHEN 1 THEN 'AdSense'+ WHEN 2 THEN 'DFP'+ WHEN 3 THEN 'Amazon'+ WHEN 4 THEN 'Carbon'+ WHEN 5 THEN 'AdButler'+ END AS ad_type,+ agg.placement,+ agg.impressions,+ agg.clicks,+ ROUND(+ agg.clicks::numeric / NULLIF(agg.impressions, 0) * 100,+ 2+ ) AS ctr+ FROM agg+ LEFT JOIN ad_plugin_house_ads ha ON agg.ad_plugin_house_ad_id = ha.id+ ORDER BY agg.impressions DESC+ LIMIT :limit+ SQL++ results = DB.query(sql, start_date: start_date, end_date: end_date, limit: limit)++ report.data =+ results.map do |row|+ {+ ad_name: row.ad_name || "Unknown",+ ad_type: row.ad_type,+ placement: row.placement,+ impressions: row.impressions,+ clicks: row.clicks,+ ctr: row.ctr.round(2),+ }+ end+ end++ def report_ad_plugin_click_through_rate_by_placement(report)+ report.icon = "rectangle-ad"+ report.modes = [:table]++ report.labels = [+ { type: :text, property: :placement, title: "Placement" },+ { type: :number, property: :impressions, title: "Impressions" },+ { type: :number, property: :clicks, title: "Clicks" },+ { type: :percent, property: :ctr, title: "CTR" },+ ]++ start_date = report.start_date+ end_date = report.end_date++ sql = <<~SQL+ SELECT+ ai.placement,+ COUNT(*) as impressions,+ SUM(CASE WHEN ai.clicked_at IS NOT NULL THEN 1 ELSE 0 END) as clicks,+ ROUND(+ SUM(CASE WHEN ai.clicked_at IS NOT NULL THEN 1 ELSE 0 END)::numeric /+ NULLIF(COUNT(*), 0) * 100,+ 2+ ) as ctr+ FROM ad_plugin_impressions ai+ WHERE ai.created_at BETWEEN :start_date AND :end_date+ GROUP BY ai.placement+ ORDER BY impressions DESC+ SQL++ results = DB.query(sql, start_date: start_date, end_date: end_date)++ report.data =+ results.map do |row|+ {+ placement: row.placement,+ impressions: row.impressions,+ clicks: row.clicks,+ ctr: row.ctr || 0,+ }+ end+ end++ def report_ad_plugin_click_through_rate_by_ad_type(report)+ report.icon = "rectangle-ad"+ report.modes = [:table]++ report.labels = [+ { type: :text, property: :ad_name, title: "Ad Name" },+ { type: :text, property: :ad_type, title: "Ad Type" },+ { type: :number, property: :impressions, title: "Impressions" },+ { type: :number, property: :clicks, title: "Clicks" },+ { type: :percent, property: :ctr, title: "CTR" },+ ]++ start_date = report.start_date+ end_date = report.end_date+ limit = report.limit || 50++ sql = <<~SQL+ WITH agg AS (+ SELECT+ ai.ad_plugin_house_ad_id,+ ai.ad_type,+ COUNT(*) AS impressions,+ SUM(CASE WHEN ai.clicked_at IS NOT NULL THEN 1 ELSE 0 END) AS clicks+ FROM ad_plugin_impressions ai+ WHERE ai.created_at BETWEEN :start_date AND :end_date+ GROUP BY ai.ad_plugin_house_ad_id, ai.ad_type+ )+ SELECT+ COALESCE(+ ha.name,+ CASE agg.ad_type+ WHEN 1 THEN 'Google AdSense'+ WHEN 2 THEN 'Google DFP'+ WHEN 3 THEN 'Amazon Product Links'+ WHEN 4 THEN 'Carbon Ads'+ WHEN 5 THEN 'AdButler'+ END+ ) AS ad_name,+ CASE agg.ad_type+ WHEN 0 THEN 'House Ad'+ WHEN 1 THEN 'AdSense'+ WHEN 2 THEN 'DFP'+ WHEN 3 THEN 'Amazon'+ WHEN 4 THEN 'Carbon'+ WHEN 5 THEN 'AdButler'+ END AS ad_type,+ agg.impressions,+ agg.clicks,+ ROUND(+ agg.clicks::numeric / NULLIF(agg.impressions, 0) * 100,+ 2+ ) AS ctr+ FROM agg+ LEFT JOIN ad_plugin_house_ads ha ON agg.ad_plugin_house_ad_id = ha.id+ ORDER BY agg.impressions DESC+ LIMIT :limit+ SQL++ results = DB.query(sql, start_date: start_date, end_date: end_date, limit: limit)++ report.data =+ results.map do |row|+ {+ ad_name: row.ad_name || "Unknown",+ ad_type: row.ad_type,+ impressions: row.impressions,+ clicks: row.clicks,+ ctr: row.ctr || 0,+ }+ end+ end+ end+enddiff --git a/plugins/discourse-adplugin/app/serializers/ad_plugin/house_ad_serializer.rb b/plugins/discourse-adplugin/app/serializers/ad_plugin/house_ad_serializer.rbnew file mode 100644index 00000000000..351bbe6cff9--- /dev/null+++ b/plugins/discourse-adplugin/app/serializers/ad_plugin/house_ad_serializer.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++module AdPlugin+ class HouseAdSerializer < ApplicationSerializer+ attributes :id,+ :name,+ :html,+ :visible_to_logged_in_users,+ :visible_to_anons,+ :created_at,+ :updated_at++ has_many :groups, serializer: ::BasicGroupSerializer, embed: :objects+ has_many :categories, serializer: ::BasicCategorySerializer, embed: :objects++ def include_groups?+ @options[:include_groups]+ end++ def include_categories?+ @options[:include_categories]+ end+ end+enddiff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js b/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.jsindex f04d447a578..8409fa201be 100644--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js@@ -2,6 +2,8 @@import Component from "@ember/component";import { alias, or } from "@ember/object/computed";import { service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import { throwAjaxError } from "discourse/lib/ajax-error";import discourseComputed from "discourse/lib/decorators";import {isNthPost,@@ -10,29 +12,34 @@ import {export default class AdComponent extends Component {@service router;+ @service session;@or("router.currentRoute.attributes.category.id","router.currentRoute.parent.attributes.category_id")currentCategoryId;-@or("router.currentRoute.attributes.category.slug","router.currentRoute.parent.attributes.category.slug")currentCategorySlug;-// Server needs to compute this in case hidden tags are being used.@alias("router.currentRoute.parent.attributes.tags_disable_ads")topicTagsDisableAds;-@or("router.currentRoute.attributes.category.read_restricted","router.currentRoute.parent.attributes.category.read_restricted")isRestrictedCategory;+ _impressionId = null;+ _clickTracked = false;++ _handleAdClick = () => {+ this.trackClick();+ };+@discourseComputed("router.currentRoute.attributes.__type","router.currentRoute.attributes.id"@@ -94,4 +101,94 @@ export default class AdComponent extends Component {isNthTopicListItem(n) {return isNthTopicListItem(n, this.get("indexNumber"));}++ didInsertElement() {+ super.didInsertElement?.(...arguments);++ if (!this.get("showAd")) {+ return;+ }++ this.startVisibilityTracking();+ this.startClickTracking();+ }++ startClickTracking() {+ if (!this.siteSettings.ad_plugin_enable_tracking) {+ return;+ }++ this.element.addEventListener("click", this._handleAdClick);+ }++ async trackImpression() {+ const payload = this.buildImpressionPayload?.();+ if (!payload) {+ return;+ }++ try {+ const response = await ajax("/ad_plugin/ad_impressions", {+ type: "POST",+ data: JSON.stringify(payload),+ contentType: "application/json; charset=utf-8",+ });++ this._impressionId = response.id;+ } catch (e) {+ throwAjaxError(e);+ }+ }++ trackClick() {+ if (!this._impressionId || this._clickTracked) {+ return;+ }++ this._clickTracked = true;++ const url = `/ad_plugin/ad_impressions/${this._impressionId}`;++ if (navigator.sendBeacon && !this.site?.isTesting) {+ const formData = new FormData();+ formData.append("authenticity_token", this.session.csrfToken);+ navigator.sendBeacon(url, formData);+ } else {+ ajax(url, {+ type: "PATCH",+ contentType: "application/json; charset=utf-8",+ }).catch((e) => {+ // eslint-disable-next-line no-console+ console.error("Failed to track ad click:", e);+ });+ }+ }++ startVisibilityTracking() {+ if (!this.siteSettings.ad_plugin_enable_tracking) {+ return;+ }++ if ("IntersectionObserver" in window) {+ this._observer = new IntersectionObserver((entries) => {+ if (entries[0].isIntersecting) {+ this.trackImpression();+ this._observer.disconnect();+ }+ });+ this._observer.observe(this.element);+ } else {+ this.trackImpression();+ }+ }++ willDestroyElement() {+ super.willDestroyElement?.(...arguments);+ if (this._observer) {+ this._observer.disconnect();+ }+ if (this.element) {+ this.element.removeEventListener("click", this._handleAdClick);+ }+ }}diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/adbutler-ad.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/adbutler-ad.gjsindex f563df2f5bd..9f48ac7c70d 100644--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/adbutler-ad.gjs+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/adbutler-ad.gjs@@ -151,6 +151,16 @@ export default class AdbutlerAd extends AdComponent {return this.isNthPost(parseInt(this.siteSettings.adbutler_nth_post, 10));}+ buildImpressionPayload() {+ return {+ ad_plugin_impression: {+ ad_type: this.site.ad_types.adbutler,+ ad_plugin_house_ad_id: null,+ placement: this.placement,+ },+ };+ }+<template>{{#if this.showAd}}<div id={{this.divId}} class={{this.className}}></div>diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/amazon-product-links.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/amazon-product-links.gjsindex bc3c600cc11..4f15c095e11 100644--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/amazon-product-links.gjs+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/amazon-product-links.gjs@@ -188,6 +188,16 @@ export default class AmazonProductLinks extends AdComponent {return this.isNthPost(parseInt(this.siteSettings.amazon_nth_post_code, 10));}+ buildImpressionPayload() {+ return {+ ad_plugin_impression: {+ ad_type: this.site.ad_types.amazon,+ ad_plugin_house_ad_id: null,+ placement: this.placement,+ },+ };+ }+<template>{{#if this.showAd}}{{#if this.site.mobileView}}diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/carbonads-ad.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/carbonads-ad.gjsindex b57389dbd06..286b0e50ca8 100644--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/carbonads-ad.gjs+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/carbonads-ad.gjs@@ -41,6 +41,16 @@ export default class CarbonadsAd extends AdComponent {);}+ buildImpressionPayload() {+ return {+ ad_plugin_impression: {+ ad_type: this.site.ad_types.carbon,+ ad_plugin_house_ad_id: null,+ placement: this.placement,+ },+ };+ }+<template>{{#if this.showAd}}{{! template-lint-disable no-forbidden-elements }}diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-adsense.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-adsense.gjsindex c015835c0d8..704cec78cbd 100644--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-adsense.gjs+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-adsense.gjs@@ -249,6 +249,16 @@ export default class GoogleAdsense extends AdComponent {);}+ buildImpressionPayload() {+ return {+ ad_plugin_impression: {+ ad_type: this.site.ad_types.adsense,+ ad_plugin_house_ad_id: null,+ placement: this.placement,+ },+ };+ }+<template>{{#if this.showAd}}<div class="google-adsense-label"><h2>{{i18ndiff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-dfp-ad.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-dfp-ad.gjsindex 897820a3019..74189d2c964 100644--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-dfp-ad.gjs+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/google-dfp-ad.gjs@@ -417,6 +417,16 @@ export default class GoogleDfpAd extends AdComponent {});}+ buildImpressionPayload() {+ return {+ ad_plugin_impression: {+ ad_type: this.site.ad_types.dfp,+ ad_plugin_house_ad_id: null,+ placement: this.placement,+ },+ };+ }+willRender() {super.willRender(...arguments);diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjsindex a3bc49ee390..3d6bfaa17de 100644--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs@@ -21,6 +21,15 @@ const adIndex = {@attributeBindings("colspanAttribute:colspan")export default class HouseAd extends AdComponent {adHtml = "";+ currentAd = null;++ _handleAdClick = (event) => {+ // For house ads, only track clicks on <a> tags+ const link = event.target.closest("a");+ if (link && link.href) {+ this.trackClick();+ }+ };@discourseComputedcolspanAttribute() {@@ -93,8 +102,11 @@ export default class HouseAd extends AdComponent {}let ad = houseAds.creatives[filteredAds[adIndex[placement]]] || "";adIndex[placement] = (adIndex[placement] + 1) % filteredAds.length;+ this.currentAd = ad || null;return ad.html;}++ this.currentAd = null;}adsNamesForSlot(placement) {@@ -117,6 +129,16 @@ export default class HouseAd extends AdComponent {this.set("adHtml", this.chooseAdHtml());}+ buildImpressionPayload() {+ return {+ ad_plugin_impression: {+ ad_type: this.site.ad_types.house,+ ad_plugin_house_ad_id: this.currentAd?.id,+ placement: this.placement,+ },+ };+ }+didInsertElement() {super.didInsertElement(...arguments);diff --git a/plugins/discourse-adplugin/config/locales/client.en.yml b/plugins/discourse-adplugin/config/locales/client.en.ymlindex 34c31210191..fb299eab4af 100755--- a/plugins/discourse-adplugin/config/locales/client.en.yml+++ b/plugins/discourse-adplugin/config/locales/client.en.yml@@ -12,6 +12,18 @@ en:amazon_plugin: "Amazon"carbonads_plugin: "Carbon Ads"adbutler_plugin: "AdButler"+ dashboard:+ reports:+ filters:+ ad_type:+ label: "Ad Type"+ house_ad_name:+ label: "HouseAd Name"+ ad_placement:+ label: "Ad Placement"+ user_type:+ label: "User Type"+adplugin:house_ads:title: "House Ads"diff --git a/plugins/discourse-adplugin/config/locales/server.en.yml b/plugins/discourse-adplugin/config/locales/server.en.ymlindex 09e7012adc6..f3f436e0928 100755--- a/plugins/discourse-adplugin/config/locales/server.en.yml+++ b/plugins/discourse-adplugin/config/locales/server.en.yml@@ -1,4 +1,28 @@en:+ reports:+ ad_plugin_house_ads_performance:+ title: Adplugin House Ads impressions+ description: "House Ads impressions report"+ ad_plugin_ad_impressions:+ title: Adplugin Ad impressions+ description: "Ads impressions report"+ ad_plugin_impressions_by_user:+ title: Ad Plugin Impressions by User+ description: "Ad impressions grouped by user"+ ad_plugin_click_through_rate:+ title: Adplugin conversion performance+ description: "Ad performance report by ad and placement"+ ad_plugin_click_through_rate_by_placement:+ title: Adplugin performance by placement+ description: "Ad performance report by placement"+ ad_plugin_click_through_rate_by_ad_type:+ title: Adplugin performance by ad type+ description: "Ad performance report by ad type"+++ errors:+ already_clicked: "Click already recorded"+site_settings:discourse_adplugin_enabled: Enable the discourse-adplugin.diff --git a/plugins/discourse-adplugin/config/settings.yml b/plugins/discourse-adplugin/config/settings.ymlindex 751ec55fbd7..364bc9c4a36 100755--- a/plugins/discourse-adplugin/config/settings.yml+++ b/plugins/discourse-adplugin/config/settings.yml@@ -38,6 +38,9 @@ ad_plugin:client: falsedefault: ""textarea: true+ ad_plugin_enable_tracking:+ client: true+ default: falseadsense_plugin:adsense_publisher_code:diff --git a/plugins/discourse-adplugin/db/migrate/20251104121941_create_house_ads_tables.rb b/plugins/discourse-adplugin/db/migrate/20251104121941_create_house_ads_tables.rbnew file mode 100644index 00000000000..c54449e3111--- /dev/null+++ b/plugins/discourse-adplugin/db/migrate/20251104121941_create_house_ads_tables.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++class CreateHouseAdsTables < ActiveRecord::Migration[7.0]+ def change+ create_table :ad_plugin_house_ads do |t|+ t.string :name, null: false+ t.text :html, null: false+ t.boolean :visible_to_logged_in_users, default: true, null: false+ t.boolean :visible_to_anons, default: true, null: false+ t.timestamps+ end++ create_table :ad_plugin_house_ads_groups, id: false do |t|+ t.bigint :ad_plugin_house_ad_id, null: false+ t.bigint :group_id, null: false+ end++ create_table :ad_plugin_house_ads_categories, id: false do |t|+ t.bigint :ad_plugin_house_ad_id, null: false+ t.bigint :category_id, null: false+ end++ add_foreign_key :ad_plugin_house_ads_groups,+ :ad_plugin_house_ads,+ column: :ad_plugin_house_ad_id,+ on_delete: :cascade++ add_foreign_key :ad_plugin_house_ads_groups, :groups, column: :group_id, on_delete: :cascade++ add_foreign_key :ad_plugin_house_ads_categories,+ :ad_plugin_house_ads,+ column: :ad_plugin_house_ad_id,+ on_delete: :cascade++ add_foreign_key :ad_plugin_house_ads_categories,+ :categories,+ column: :category_id,+ on_delete: :cascade++ add_index :ad_plugin_house_ads, :name, unique: true+ add_index :ad_plugin_house_ads, :visible_to_logged_in_users+ add_index :ad_plugin_house_ads, :visible_to_anons+ add_index :ad_plugin_house_ads_groups,+ %i[ad_plugin_house_ad_id group_id],+ name: "index_house_ads_groups"+ add_index :ad_plugin_house_ads_categories,+ %i[ad_plugin_house_ad_id category_id],+ name: "index_house_ads_categories"+ end+enddiff --git a/plugins/discourse-adplugin/db/migrate/20251104121942_create_ad_analytics_tables.rb b/plugins/discourse-adplugin/db/migrate/20251104121942_create_ad_analytics_tables.rbnew file mode 100644index 00000000000..22dba157eed--- /dev/null+++ b/plugins/discourse-adplugin/db/migrate/20251104121942_create_ad_analytics_tables.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++class CreateAdAnalyticsTables < ActiveRecord::Migration[7.0]+ def change+ create_table :ad_plugin_impressions do |t|+ t.integer :ad_type, null: false+ t.bigint :ad_plugin_house_ad_id+ t.string :placement, null: false+ t.integer :user_id+ t.timestamps+ end++ add_index :ad_plugin_impressions, :ad_type+ add_index :ad_plugin_impressions, :ad_plugin_house_ad_id+ add_index :ad_plugin_impressions, :user_id+ add_index :ad_plugin_impressions, %i[ad_type placement]+ add_index :ad_plugin_impressions, :created_at++ add_foreign_key :ad_plugin_impressions,+ :ad_plugin_house_ads,+ column: :ad_plugin_house_ad_id,+ on_delete: :cascade+ add_foreign_key :ad_plugin_impressions, :users, column: :user_id, on_delete: :nullify+ end+enddiff --git a/plugins/discourse-adplugin/db/migrate/20251114164217_add_clicked_at_to_ad_plugin_impressions.rb b/plugins/discourse-adplugin/db/migrate/20251114164217_add_clicked_at_to_ad_plugin_impressions.rbnew file mode 100644index 00000000000..05d42cccaf1--- /dev/null+++ b/plugins/discourse-adplugin/db/migrate/20251114164217_add_clicked_at_to_ad_plugin_impressions.rb@@ -0,0 +1,8 @@+# frozen_string_literal: true++class AddClickedAtToAdPluginImpressions < ActiveRecord::Migration[7.0]+ def change+ add_column :ad_plugin_impressions, :clicked_at, :datetime+ add_index :ad_plugin_impressions, :clicked_at+ end+enddiff --git a/plugins/discourse-adplugin/db/post_migrate/20251104121943_migrate_house_ads_from_plugin_store.rb b/plugins/discourse-adplugin/db/post_migrate/20251104121943_migrate_house_ads_from_plugin_store.rbnew file mode 100644index 00000000000..149ccedb605--- /dev/null+++ b/plugins/discourse-adplugin/db/post_migrate/20251104121943_migrate_house_ads_from_plugin_store.rb@@ -0,0 +1,120 @@+# frozen_string_literal: true++class MigrateHouseAdsFromPluginStore < ActiveRecord::Migration[7.0]+ def up+ # Get all house ads from PluginStore+ plugin_store_ads =+ PluginStoreRow+ .where(plugin_name: "discourse-adplugin")+ .where("key LIKE 'ad:%'")+ .where("key != 'ad:_id'")++ return if plugin_store_ads.empty?++ existing_ids = DB.query_single("SELECT id FROM ad_plugin_house_ads").to_set++ ads_data = []+ groups_data = []+ categories_data = []++ plugin_store_ads.each do |psr|+ data = PluginStore.cast_value(psr.type_name, psr.value)++ next if existing_ids.include?(data[:id])++ ads_data << {+ id: data[:id],+ name: data[:name],+ html: data[:html],+ visible_to_logged_in_users: data[:visible_to_logged_in_users],+ visible_to_anons: data[:visible_to_anons],+ }++ if data[:group_ids].present?+ data[:group_ids].each { |group_id| groups_data << { ad_id: data[:id], group_id: group_id } }+ end++ if data[:category_ids].present?+ data[:category_ids].each do |category_id|+ categories_data << { ad_id: data[:id], category_id: category_id }+ end+ end+ end++ return if ads_data.empty?++ ads_values =+ ads_data+ .map do |ad|+ "(#{ad[:id]}, #{ActiveRecord::Base.connection.quote(ad[:name])}, #{ActiveRecord::Base.connection.quote(ad[:html])}, #{ad[:visible_to_logged_in_users]}, #{ad[:visible_to_anons]}, NOW(), NOW())"+ end+ .join(",")++ DB.exec(<<~SQL)+ INSERT INTO ad_plugin_house_ads (id, name, html, visible_to_logged_in_users, visible_to_anons, created_at, updated_at)+ VALUES #{ads_values}+ ON CONFLICT (id) DO NOTHING+ SQL++ if groups_data.any?+ groups_values = groups_data.map { |g| "(#{g[:ad_id]}, #{g[:group_id]})" }.join(",")++ DB.exec(<<~SQL)+ INSERT INTO ad_plugin_house_ads_groups (ad_plugin_house_ad_id, group_id)+ VALUES #{groups_values}+ ON CONFLICT DO NOTHING+ SQL+ end++ if categories_data.any?+ categories_values = categories_data.map { |c| "(#{c[:ad_id]}, #{c[:category_id]})" }.join(",")++ DB.exec(<<~SQL)+ INSERT INTO ad_plugin_house_ads_categories (ad_plugin_house_ad_id, category_id)+ VALUES #{categories_values}+ ON CONFLICT DO NOTHING+ SQL+ end++ max_id = DB.query_single("SELECT MAX(id) FROM ad_plugin_house_ads").first || 0+ DB.exec("SELECT setval('ad_plugin_house_ads_id_seq', ?)", max_id + 1) if max_id > 0+ end++ def down+ ads = DB.query(<<~SQL)+ SELECT+ ha.id,+ ha.name,+ ha.html,+ ha.visible_to_logged_in_users,+ ha.visible_to_anons,+ ARRAY_AGG(DISTINCT hag.group_id) FILTER (WHERE hag.group_id IS NOT NULL) as group_ids,+ ARRAY_AGG(DISTINCT hac.category_id) FILTER (WHERE hac.category_id IS NOT NULL) as category_ids+ FROM ad_plugin_house_ads ha+ LEFT JOIN ad_plugin_house_ads_groups hag ON ha.id = hag.ad_plugin_house_ad_id+ LEFT JOIN ad_plugin_house_ads_categories hac ON ha.id = hac.ad_plugin_house_ad_id+ GROUP BY ha.id, ha.name, ha.html, ha.visible_to_logged_in_users, ha.visible_to_anons+ SQL++ ads.each do |ad|+ PluginStore.set(+ "discourse-adplugin",+ "ad:#{ad.id}",+ {+ id: ad.id,+ name: ad.name,+ html: ad.html,+ visible_to_logged_in_users: ad.visible_to_logged_in_users,+ visible_to_anons: ad.visible_to_anons,+ group_ids: ad.group_ids || [],+ category_ids: ad.category_ids || [],+ },+ )+ end++ max_id = ads.map(&:id).max || 0+ PluginStore.set("discourse-adplugin", "ad:_id", max_id + 1) if max_id > 0++ puts "Migrated #{ads.count} house ads back to PluginStore"+ end+enddiff --git a/plugins/discourse-adplugin/lib/ad_plugin/ad_type.rb b/plugins/discourse-adplugin/lib/ad_plugin/ad_type.rbnew file mode 100644index 00000000000..c60301fa454--- /dev/null+++ b/plugins/discourse-adplugin/lib/ad_plugin/ad_type.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module AdPlugin+ class AdType+ def self.types+ @types ||= Enum.new(:house, :adsense, :dfp, :amazon, :carbon, :adbutler, start: 0)+ end++ def self.[](type)+ types[type]+ end++ def self.valid?(type)+ types.values.include?(type)+ end++ def self.enum_hash+ @enum_hash ||= types.to_h.freeze+ end+ end+enddiff --git a/plugins/discourse-adplugin/plugin.rb b/plugins/discourse-adplugin/plugin.rbindex d9a11d7c993..a611d81fba9 100755--- a/plugins/discourse-adplugin/plugin.rb+++ b/plugins/discourse-adplugin/plugin.rb@@ -18,19 +18,33 @@ module ::AdPluginendrequire_relative "lib/adplugin/engine"+require_relative "lib/ad_plugin/ad_type"after_initialize dorequire_relative "app/controllers/ad_plugin/house_ad_settings_controller"require_relative "app/controllers/ad_plugin/house_ads_controller"require_relative "app/controllers/adstxt_controller"+ require_relative "app/controllers/ad_plugin/ad_impressions_controller"+ require_relative "app/serializers/ad_plugin/house_ad_serializer"+require_relative "app/models/ad_plugin/house_ad_setting"require_relative "app/models/ad_plugin/house_ad"+ require_relative "app/models/ad_plugin/ad_impression"+ require_relative "app/models/concerns/reports/ad_plugin"require_relative "lib/adplugin/guardian_extensions"- reloadable_patch { Guardian.prepend AdPlugin::GuardianExtensions }+ reloadable_patch do+ Guardian.prepend AdPlugin::GuardianExtensions+ Report.include(Reports::AdPlugin)+ endDiscourse::Application.routes.append doget "/ads.txt" => "adstxt#index"++ post "/ad_plugin/ad_impressions/:id" => "ad_plugin/ad_impressions#update"+ patch "/ad_plugin/ad_impressions/:id" => "ad_plugin/ad_impressions#update"+ post "/ad_plugin/ad_impressions" => "ad_plugin/ad_impressions#create"+mount AdPlugin::Engine, at: "/admin/plugins/pluginad", constraints: AdminConstraint.newend@@ -38,6 +52,10 @@ after_initialize doAdPlugin::HouseAdSetting.settings_and_ads(for_anons: scope.anonymous?, scope: scope)end+ add_to_serializer :site, :ad_types do+ AdPlugin::AdType.types+ end+add_to_serializer :topic_view, :tags_disable_ads doreturn false if !SiteSetting.tagging_enabled || !SiteSetting.no_ads_for_tags.present?return false if object.topic.tags.empty?diff --git a/plugins/discourse-adplugin/spec/fabricators/ad_impressions_fabricator.rb b/plugins/discourse-adplugin/spec/fabricators/ad_impressions_fabricator.rbnew file mode 100644index 00000000000..693b9a53738--- /dev/null+++ b/plugins/discourse-adplugin/spec/fabricators/ad_impressions_fabricator.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++Fabricator(:house_ad_impression, from: "AdPlugin::AdImpression") do+ ad_type { AdPlugin::AdType.types[:house] }+ placement { AdPlugin::HouseAdSetting::DEFAULTS.keys[0].to_s }+ house_ad+ user+end++Fabricator(:anonymous_house_ad_impression, from: "AdPlugin::AdImpression") do+ ad_type { AdPlugin::AdType.types[:house] }+ placement { AdPlugin::HouseAdSetting::DEFAULTS.keys[0].to_s }+ house_ad+end++Fabricator(:external_ad_impression, from: "AdPlugin::AdImpression") do+ ad_type { AdPlugin::AdType.types[:amazon] }+ placement { AdPlugin::HouseAdSetting::DEFAULTS.keys[0].to_s }+enddiff --git a/plugins/discourse-adplugin/spec/fabricators/house_ad_fabricator.rb b/plugins/discourse-adplugin/spec/fabricators/house_ad_fabricator.rbnew file mode 100644index 00000000000..15258f5f0e8--- /dev/null+++ b/plugins/discourse-adplugin/spec/fabricators/house_ad_fabricator.rb@@ -0,0 +1,6 @@+# frozen_string_literal: true++Fabricator(:house_ad, from: AdPlugin::HouseAd) do+ name { sequence(:name) { |i| "Find A Mechanic #{i}" } }+ html '<div class="house-ad find-a-mechanic"><a href="https://mechanics.example.com">Find A Mechanic!</a></div>'+enddiff --git a/plugins/discourse-adplugin/spec/models/ad_impressions_spec.rb b/plugins/discourse-adplugin/spec/models/ad_impressions_spec.rbnew file mode 100644index 00000000000..f597d72c4ce--- /dev/null+++ b/plugins/discourse-adplugin/spec/models/ad_impressions_spec.rb@@ -0,0 +1,279 @@+# frozen_string_literal: true++describe AdPlugin::AdImpression do+ fab!(:house_ad)+ fab!(:user)+ fab!(:house_ad_impression) { Fabricate(:house_ad_impression, house_ad: house_ad, user: user) }+ fab!(:external_ad_impression)+ fab!(:anonymous_house_ad_impression)++ before { enable_current_plugin }++ describe "validations" do+ it "is valid with all required attributes for house ad" do+ impression =+ AdPlugin::AdImpression.new(+ ad_type: AdPlugin::AdType[:house],+ placement: "topic_list_top",+ house_ad: house_ad,+ )+ expect(impression).to be_valid+ end++ it "is valid with all required attributes for external ad" do+ impression =+ AdPlugin::AdImpression.new(ad_type: AdPlugin::AdType[:amazon], placement: "topic_list_top")+ expect(impression).to be_valid+ end++ it "requires ad_type" do+ impression = AdPlugin::AdImpression.new(placement: "topic_list_top", house_ad: house_ad)+ expect(impression).not_to be_valid+ expect(impression.errors[:ad_type]).to be_present+ end++ it "requires placement" do+ impression = AdPlugin::AdImpression.new(ad_type: AdPlugin::AdType[:house], house_ad: house_ad)+ expect(impression).not_to be_valid+ expect(impression.errors[:placement]).to be_present+ end++ it "requires house ad id when ad_type is house" do+ impression =+ AdPlugin::AdImpression.new(ad_type: AdPlugin::AdType[:house], placement: "topic_list_top")+ expect(impression).not_to be_valid+ expect(impression.errors[:ad_plugin_house_ad_id]).to be_present+ end++ it "does not require house ad id when ad_type is external" do+ impression =+ AdPlugin::AdImpression.new(ad_type: AdPlugin::AdType[:adsense], placement: "topic_list_top")+ expect(impression).to be_valid+ end++ it "rejects house ad id when ad_type is external" do+ impression =+ AdPlugin::AdImpression.new(+ ad_type: AdPlugin::AdType[:amazon],+ placement: "topic_list_top",+ house_ad: house_ad,+ )+ expect(impression).not_to be_valid+ expect(impression.errors[:ad_plugin_house_ad_id]).to be_present+ end+ end++ describe "associations" do+ it "belongs to house_ad" do+ expect(house_ad_impression.house_ad).to be_present+ expect(house_ad_impression.house_ad).to be_a(AdPlugin::HouseAd)+ end++ it "belongs to user" do+ expect(house_ad_impression.user).to eq(user)+ end++ it "allows nil user (anonymous impressions)" do+ expect(anonymous_house_ad_impression.user).to be_nil+ expect(anonymous_house_ad_impression).to be_valid+ end++ it "allows nil house_ad for external ads" do+ expect(external_ad_impression.house_ad).to be_nil+ expect(external_ad_impression).to be_valid+ end+ end++ describe "enum ad_type" do+ it "defines house ad type" do+ impression = Fabricate(:house_ad_impression)+ expect(house_ad_impression.house?).to eq(true)+ expect(house_ad_impression.adsense?).to eq(false)+ end++ it "defines adsense ad type" do+ impression =+ AdPlugin::AdImpression.create!(ad_type: AdPlugin::AdType[:adsense], placement: "test")+ expect(impression.adsense?).to eq(true)+ expect(impression.house?).to eq(false)+ end++ it "defines dfp ad type" do+ impression =+ AdPlugin::AdImpression.create!(ad_type: AdPlugin::AdType[:dfp], placement: "test")+ expect(impression.dfp?).to eq(true)+ expect(impression.house?).to eq(false)+ end++ it "defines amazon ad type" do+ impression =+ AdPlugin::AdImpression.create!(ad_type: AdPlugin::AdType[:amazon], placement: "test")+ expect(impression.amazon?).to eq(true)+ expect(impression.house?).to eq(false)+ end++ it "defines carbon ad type" do+ impression =+ AdPlugin::AdImpression.create!(ad_type: AdPlugin::AdType[:carbon], placement: "test")+ expect(impression.carbon?).to eq(true)+ expect(impression.house?).to eq(false)+ end++ it "defines adbutler ad type" do+ impression =+ AdPlugin::AdImpression.create!(ad_type: AdPlugin::AdType[:adbutler], placement: "test")+ expect(impression.adbutler?).to eq(true)+ expect(impression.house?).to eq(false)+ end++ it "provides scopes for each ad type" do+ expect(AdPlugin::AdImpression.house).to include(house_ad_impression)+ expect(AdPlugin::AdImpression.house).not_to include(external_ad_impression)++ expect(AdPlugin::AdImpression.amazon).to include(external_ad_impression)+ expect(AdPlugin::AdImpression.amazon).not_to include(house_ad_impression)+ end++ it "allows setting ad_type using bang method" do+ impression = Fabricate(:external_ad_impression)+ impression.adsense!+ expect(impression.adsense?).to eq(true)+ expect(impression.amazon?).to eq(false)+ end+ end++ describe "creating impressions" do+ it "creates house ad impression" do+ expect(house_ad_impression).to be_persisted+ expect(AdPlugin::AdType.types[house_ad_impression.ad_type.to_sym]).to eq(+ AdPlugin::AdType[:house],+ )+ expect(house_ad_impression.house_ad).to eq(house_ad)+ end++ it "creates external ad impression" do+ expect(external_ad_impression).to be_persisted+ expect(AdPlugin::AdType.types[external_ad_impression.ad_type.to_sym]).to eq(+ AdPlugin::AdType[:amazon],+ )+ expect(external_ad_impression.house_ad).to be_nil+ end++ it "creates impression with user" do+ expect(house_ad_impression.user).to eq(user)+ end++ it "creates impression without user (anonymous)" do+ house_ad_impression.user = nil+ house_ad_impression.save+ re_loaded_house_ad_impression = AdPlugin::AdImpression.find(house_ad_impression.id)+ expect(house_ad_impression.user).to be_nil+ end++ it "records placement" do+ expect(house_ad_impression.placement).to eq("topic_list_top")+ end++ it "records timestamps" do+ expect(house_ad_impression.created_at).to be_present+ expect(house_ad_impression.updated_at).to be_present+ end+ end++ describe "querying impressions" do+ fab!(:house_impression1) { Fabricate(:house_ad_impression, house_ad: house_ad, user: user) }+ fab!(:house_impression2) { Fabricate(:house_ad_impression, house_ad: house_ad, user: nil) }+ fab!(:external_impression) { Fabricate(:external_ad_impression, user: user) }++ it "finds all impressions" do+ expect(AdPlugin::AdImpression.all).to include(+ house_impression1,+ house_impression2,+ external_impression,+ )+ end++ it "filters by ad_type" do+ house_impressions = AdPlugin::AdImpression.house+ expect(house_impressions).to include(house_impression1, house_impression2)+ expect(house_impressions).not_to include(external_impression)+ end++ it "filters by user" do+ user_impressions = AdPlugin::AdImpression.where(user: user)+ expect(user_impressions).to include(house_impression1, external_impression)+ expect(user_impressions).not_to include(house_impression2)+ end++ it "filters by house_ad" do+ house_ad_impressions = AdPlugin::AdImpression.where(house_ad: house_ad)+ expect(house_ad_impressions).to include(house_impression1, house_impression2)+ expect(house_ad_impressions).not_to include(external_impression)+ end++ it "filters by placement" do+ placement = house_impression1.placement+ placement_impressions = AdPlugin::AdImpression.where(placement: placement)+ expect(placement_impressions.count).to be >= 1+ end+ end++ describe "cascade deletion" do+ fab!(:impression) { Fabricate(:house_ad_impression, house_ad: house_ad, user: user) }+ it "deletes impressions when house_ad is deleted" do+ impression_id = impression.id++ house_ad.destroy!++ expect { AdPlugin::AdImpression.find(impression_id) }.to raise_error(+ ActiveRecord::RecordNotFound,+ )+ end++ it "nullifies user_id when user is deleted" do+ user_id = user.id++ user.destroy!+ impression.reload++ expect(impression.user_id).to be_nil+ expect(impression).to be_persisted+ end+ end++ describe "#record_click!" do+ fab!(:impression, :house_ad_impression)++ it "records the click timestamp" do+ freeze_time++ expect(impression.clicked_at).to be_nil+ expect(impression.record_click!).to eq(true)++ impression.reload+ expect(impression.clicked_at).to be_within(1.second).of(Time.zone.now)+ end++ it "prevents duplicate clicks" do+ impression.record_click!+ original_time = impression.clicked_at++ expect(impression.record_click!).to eq(false)+ impression.reload+ expect(impression.clicked_at).to eq_time(original_time)+ end+ end++ describe "#clicked?" do+ fab!(:impression, :house_ad_impression)++ it "returns false when not clicked" do+ expect(impression.clicked?).to eq(false)+ end++ it "returns true when clicked" do+ impression.record_click!+ expect(impression.clicked?).to eq(true)+ end+ end+enddiff --git a/plugins/discourse-adplugin/spec/models/house_ad_setting_spec.rb b/plugins/discourse-adplugin/spec/models/house_ad_setting_spec.rbindex b6d2182af32..ddef8c58b9f 100644--- a/plugins/discourse-adplugin/spec/models/house_ad_setting_spec.rb+++ b/plugins/discourse-adplugin/spec/models/house_ad_setting_spec.rb@@ -69,25 +69,23 @@ describe AdPlugin::HouseAdSetting doenddescribe ".publish_settings" do- let!(:anon_ad) do- AdPlugin::HouseAd.create(+ fab!(:anon_ad) do+ Fabricate(+ :house_ad,name: "anon-ad",html: "<whatever-anon>",visible_to_anons: true,visible_to_logged_in_users: false,- group_ids: [],- category_ids: [],)end- let!(:logged_in_ad) do- AdPlugin::HouseAd.create(+ fab!(:logged_in_ad) do+ Fabricate(+ :house_ad,name: "logged-in-ad",html: "<whatever-logged-in>",visible_to_anons: false,visible_to_logged_in_users: true,- group_ids: [],- category_ids: [],)end@@ -100,19 +98,21 @@ describe AdPlugin::HouseAdSetting doanon_message = messages.find { |m| m.channel == "/site/house-creatives/anonymous" }logged_in_message = messages.find { |m| m.channel == "/site/house-creatives/logged-in" }- expect(anon_message.data[:creatives]).to eq(+ expect(anon_message.data[:creatives]).to match("anon-ad" => {html: "<whatever-anon>",category_ids: [],+ id: a_kind_of(Integer),},)expect(anon_message.group_ids).to eq(nil)expect(anon_message.user_ids).to eq(nil)- expect(logged_in_message.data[:creatives]).to eq(+ expect(logged_in_message.data[:creatives]).to match("logged-in-ad" => {html: "<whatever-logged-in>",category_ids: [],+ id: a_kind_of(Integer),},)expect(logged_in_message.group_ids).to eq([Group::AUTO_GROUPS[:trust_level_0]])diff --git a/plugins/discourse-adplugin/spec/models/house_ad_spec.rb b/plugins/discourse-adplugin/spec/models/house_ad_spec.rbindex d683d4f3512..07301ece855 100644--- a/plugins/discourse-adplugin/spec/models/house_ad_spec.rb+++ b/plugins/discourse-adplugin/spec/models/house_ad_spec.rb@@ -11,33 +11,11 @@ describe AdPlugin::HouseAd dobefore { enable_current_plugin }- def create_anon_ad- AdPlugin::HouseAd.create(- name: "anon-ad",- html: "<div>ANON</div>",- visible_to_logged_in_users: false,- visible_to_anons: true,- group_ids: [],- category_ids: [],- )- end-- def create_logged_in_ad- AdPlugin::HouseAd.create(- name: "logged-in-ad",- html: "<div>LOGGED IN</div>",- visible_to_logged_in_users: true,- visible_to_anons: false,- group_ids: [],- category_ids: [],- )- end-describe ".find" dolet!(:ad) { AdPlugin::HouseAd.create(valid_attrs) }- it "returns nil if no match" do- expect(AdPlugin::HouseAd.find(100)).to be_nil+ it "raises RecordNotFound if no match" do+ expect { AdPlugin::HouseAd.find(100) }.to raise_error(ActiveRecord::RecordNotFound)endit "can retrieve by id" do@@ -63,8 +41,12 @@ describe AdPlugin::HouseAd doenddescribe ".all_for_anons" do- let!(:anon_ad) { create_anon_ad }- let!(:logged_in_ad) { create_logged_in_ad }+ fab!(:anon_ad) do+ Fabricate(:house_ad, visible_to_logged_in_users: false, visible_to_anons: true)+ end+ fab!(:logged_in_ad) do+ Fabricate(:house_ad, visible_to_logged_in_users: true, visible_to_anons: false)+ endit "doesn't include ads for logged in users" doexpect(AdPlugin::HouseAd.all_for_anons.map(&:id)).to contain_exactly(anon_ad.id)@@ -72,9 +54,13 @@ describe AdPlugin::HouseAd doenddescribe ".all_for_logged_in_users" do- let!(:anon_ad) { create_anon_ad }- let!(:logged_in_ad) { create_logged_in_ad }- let!(:user) { Fabricate(:user) }+ fab!(:anon_ad) do+ Fabricate(:house_ad, visible_to_logged_in_users: false, visible_to_anons: true)+ end+ fab!(:logged_in_ad) do+ Fabricate(:house_ad, visible_to_logged_in_users: true, visible_to_anons: false)+ end+ fab!(:user)it "doesn't include ads for anonymous users" doexpect(@@ -85,12 +71,12 @@ describe AdPlugin::HouseAd dodescribe "#save" doit "assigns an id and attrs for new record" do- ad = AdPlugin::HouseAd.from_hash(valid_attrs)+ ad = AdPlugin::HouseAd.new(valid_attrs)expect(ad.save).to eq(true)expect(ad.name).to eq(valid_attrs[:name])expect(ad.html).to eq(valid_attrs[:html])expect(ad.id.to_i > 0).to eq(true)- ad2 = AdPlugin::HouseAd.from_hash(valid_attrs.merge(name: "Find Another Mechanic"))+ ad2 = AdPlugin::HouseAd.new(valid_attrs.merge(name: "Find Another Mechanic"))expect(ad2.save).to eq(true)expect(ad2.id).to_not eq(ad.id)end@@ -109,7 +95,7 @@ describe AdPlugin::HouseAd dodescribe "errors" doit "blank name" do- ad = AdPlugin::HouseAd.from_hash(valid_attrs.merge(name: ""))+ ad = AdPlugin::HouseAd.new(valid_attrs.merge(name: ""))expect(ad.save).to eq(false)expect(ad).to_not be_validexpect(ad.errors.full_messages).to be_present@@ -119,7 +105,7 @@ describe AdPlugin::HouseAd doit "duplicate name" doAdPlugin::HouseAd.create(valid_attrs)- ad = AdPlugin::HouseAd.from_hash(valid_attrs)+ ad = AdPlugin::HouseAd.new(valid_attrs)expect(ad.save).to eq(false)expect(ad).to_not be_validexpect(ad.errors.full_messages).to be_present@@ -129,7 +115,8 @@ describe AdPlugin::HouseAd doit "duplicate name, different case" doAdPlugin::HouseAd.create(valid_attrs.merge(name: "mechanic"))- ad = AdPlugin::HouseAd.create(valid_attrs.merge(name: "Mechanic"))+ ad = AdPlugin::HouseAd.create(valid_attrs.merge(name: "mechanic"))+expect(ad.save).to eq(false)expect(ad).to_not be_validexpect(ad.errors[:name]).to be_present@@ -137,7 +124,7 @@ describe AdPlugin::HouseAd doendit "blank html" do- ad = AdPlugin::HouseAd.from_hash(valid_attrs.merge(html: ""))+ ad = AdPlugin::HouseAd.new(valid_attrs.merge(html: ""))expect(ad.save).to eq(false)expect(ad).to_not be_validexpect(ad.errors.full_messages).to be_present@@ -146,7 +133,7 @@ describe AdPlugin::HouseAd doendit "invalid name" do- ad = AdPlugin::HouseAd.from_hash(valid_attrs.merge(name: "<script>"))+ ad = AdPlugin::HouseAd.new(valid_attrs.merge(name: "<script>"))expect(ad.save).to eq(false)expect(ad).to_not be_validexpect(ad.errors[:name]).to be_present@@ -177,7 +164,7 @@ describe AdPlugin::HouseAd doit "can delete a record" doad = AdPlugin::HouseAd.create(valid_attrs)ad.destroy- expect(AdPlugin::HouseAd.find(ad.id)).to be_nil+ expect { AdPlugin::HouseAd.find(ad.id) }.to raise_error(ActiveRecord::RecordNotFound)endenddiff --git a/plugins/discourse-adplugin/spec/requests/ad_impressions_controller_spec.rb b/plugins/discourse-adplugin/spec/requests/ad_impressions_controller_spec.rbnew file mode 100644index 00000000000..dc48fe68e5f--- /dev/null+++ b/plugins/discourse-adplugin/spec/requests/ad_impressions_controller_spec.rb@@ -0,0 +1,257 @@+# frozen_string_literal: true++describe AdPlugin::AdImpressionsController do+ fab!(:user)+ fab!(:house_ad)++ before { enable_current_plugin }++ describe "#create" do+ context "when creating house ad impression" do+ it "creates impression for logged in user" do+ sign_in(user)++ expect {+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:house],+ placement: "topic_list_top",+ ad_plugin_house_ad_id: house_ad.id,+ },+ }+ }.to change { AdPlugin::AdImpression.count }.by(1)++ expect(response.status).to eq(200)+ json = response.parsed_body+ expect(json["ad_type"]).to eq(AdPlugin::AdType[AdPlugin::AdType.types[:house]].to_s)+ expect(json["placement"]).to eq("topic_list_top")+ expect(json["user_id"]).to eq(user.id)++ impression = AdPlugin::AdImpression.last+ expect(impression.house?).to eq(true)+ expect(impression.house_ad).to eq(house_ad)+ expect(impression.user).to eq(user)+ end++ it "creates impression for anonymous user" do+ expect {+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:house],+ placement: "topic_list_top",+ ad_plugin_house_ad_id: house_ad.id,+ },+ }+ }.to change { AdPlugin::AdImpression.count }.by(1)++ expect(response.status).to eq(200)+ json = response.parsed_body+ expect(json["user_id"]).to be_nil++ impression = AdPlugin::AdImpression.last+ expect(impression.user).to be_nil+ end+ end++ context "when creating external ad impression" do+ it "creates impression for adsense" do+ sign_in(user)++ expect {+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:adsense],+ placement: "topic_above_post_stream",+ },+ }+ }.to change { AdPlugin::AdImpression.count }.by(1)++ expect(response.status).to eq(200)+ impression = AdPlugin::AdImpression.last+ expect(impression.adsense?).to eq(true)+ expect(impression.house_ad).to be_nil+ end++ it "creates impression for amazon" do+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:amazon],+ placement: "post_bottom",+ },+ }++ expect(response.status).to eq(200)+ impression = AdPlugin::AdImpression.last+ expect(impression.amazon?).to eq(true)+ end+ end++ context "when validation fails" do+ it "returns error for missing ad_type" do+ sign_in(user)++ expect {+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ placement: "topic_list_top",+ },+ }+ }.not_to change { AdPlugin::AdImpression.count }++ expect(response.status).to eq(422)+ end++ it "returns error for missing placement" do+ sign_in(user)++ expect {+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:house],+ ad_plugin_house_ad_id: house_ad.id,+ },+ }+ }.not_to change { AdPlugin::AdImpression.count }++ expect(response.status).to eq(422)+ end++ it "returns error when house ad missing house_ad_id" do+ sign_in(user)++ expect {+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:house],+ placement: "topic_list_top",+ },+ }+ }.not_to change { AdPlugin::AdImpression.count }++ expect(response.status).to eq(422)+ end++ it "returns error when external ad includes house_ad_id" do+ sign_in(user)++ expect {+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:adsense],+ placement: "topic_list_top",+ ad_plugin_house_ad_id: house_ad.id,+ },+ }+ }.not_to change { AdPlugin::AdImpression.count }++ expect(response.status).to eq(422)+ end+ end++ context "when recording different placements" do+ it "records topic_list_top placement" do+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:dfp],+ placement: "topic_list_top",+ },+ }++ impression = AdPlugin::AdImpression.last+ expect(impression.placement).to eq("topic_list_top")+ end++ it "records topic_above_post_stream placement" do+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:carbon],+ placement: "topic_above_post_stream",+ },+ }++ impression = AdPlugin::AdImpression.last+ expect(impression.placement).to eq("topic_above_post_stream")+ end++ it "records post_bottom placement" do+ post "/ad_plugin/ad_impressions.json",+ params: {+ ad_plugin_impression: {+ ad_type: AdPlugin::AdType.types[:adbutler],+ placement: "post_bottom",+ },+ }++ impression = AdPlugin::AdImpression.last+ expect(impression.placement).to eq("post_bottom")+ end+ end+ end++ describe "#update" do+ fab!(:impression) { Fabricate(:house_ad_impression, user: user, house_ad: house_ad) }++ it "records a click on an impression" do+ freeze_time++ patch "/ad_plugin/ad_impressions/#{impression.id}.json"++ expect(response.status).to eq(200)+ json = response.parsed_body+ expect(json["success"]).to eq(true)+ expect(json["clicked_at"]).to be_present++ impression.reload+ expect(impression.clicked_at).to be_within(1.second).of(Time.zone.now)+ expect(impression.clicked?).to eq(true)+ end++ it "prevents recording duplicate clicks" do+ impression.record_click!++ patch "/ad_plugin/ad_impressions/#{impression.id}.json"++ expect(response.status).to eq(422)+ json = response.parsed_body+ expect(json["success"]).to eq(false)+ expect(json["error"]).to eq(I18n.t("errors.already_clicked"))+ end++ it "works for external ad impressions" do+ external_impression = Fabricate(:external_ad_impression)++ freeze_time++ patch "/ad_plugin/ad_impressions/#{external_impression.id}.json"++ expect(response.status).to eq(200)++ external_impression.reload+ expect(external_impression.clicked_at).to be_within(1.second).of(Time.zone.now)+ end++ it "also accepts POST requests for sendBeacon compatibility" do+ freeze_time++ post "/ad_plugin/ad_impressions/#{impression.id}.json"++ expect(response.status).to eq(200)+ json = response.parsed_body+ expect(json["success"]).to eq(true)+ expect(json["clicked_at"]).to be_present++ impression.reload+ expect(impression.clicked_at).to be_within(1.second).of(Time.zone.now)+ end+ end+enddiff --git a/plugins/discourse-adplugin/spec/requests/house_ad_controller_spec.rb b/plugins/discourse-adplugin/spec/requests/house_ad_controller_spec.rbindex 9f2b16c4aca..0406757a34c 100644--- a/plugins/discourse-adplugin/spec/requests/house_ad_controller_spec.rb+++ b/plugins/discourse-adplugin/spec/requests/house_ad_controller_spec.rb@@ -33,15 +33,23 @@ describe AdPlugin::HouseAdsController dogroup_ids: [group.id],}expect(response.status).to eq(200)- expect(response.parsed_body["house_ad"].symbolize_keys).to eq(- id: ad.id,- name: ad.name,- html: ad.html,- visible_to_anons: false,- visible_to_logged_in_users: true,- category_ids: [category.id],- group_ids: [group.id],- )++ house_ad_response = JSON.parse(response.body, symbolize_names: true)[:house_ad]+ expect(house_ad_response[:id]).to eq(ad.id)+ expect(house_ad_response[:name]).to eq(ad.name)+ expect(house_ad_response[:html]).to eq(ad.html)+ expect(house_ad_response[:visible_to_anons]).to eq(false)+ expect(house_ad_response[:visible_to_logged_in_users]).to eq(true)++ serialized_category =+ BasicCategorySerializer.new(category, scope: Guardian.new(admin)).as_json+ expect(house_ad_response[:categories].length).to eq(1)+ expect(house_ad_response[:categories][0]).to eq(serialized_category[:basic_category])++ serialized_group = BasicGroupSerializer.new(group, scope: Guardian.new(admin)).as_json++ expect(house_ad_response[:groups].length).to eq(1)+ expect(house_ad_response[:groups][0]).to eq(serialized_group[:basic_group])ad_copy = AdPlugin::HouseAd.find(ad.id)expect(ad_copy.name).to eq(ad.name)diff --git a/plugins/discourse-adplugin/spec/serializer/house_ad_serializer_spec.rb b/plugins/discourse-adplugin/spec/serializer/house_ad_serializer_spec.rbnew file mode 100644index 00000000000..11305278116--- /dev/null+++ b/plugins/discourse-adplugin/spec/serializer/house_ad_serializer_spec.rb@@ -0,0 +1,121 @@+# frozen_string_literal: true++describe AdPlugin::HouseAdSerializer do+ fab!(:user)+ fab!(:house_ad) do+ Fabricate(+ :house_ad,+ name: "Test Ad",+ html: "<div>Test HTML</div>",+ visible_to_logged_in_users: true,+ visible_to_anons: false,+ )+ end+ fab!(:category)+ fab!(:group)++ let(:guardian) { Guardian.new(user) }++ before { enable_current_plugin }++ describe "basic serialization" do+ it "serializes basic attributes" do+ serializer = AdPlugin::HouseAdSerializer.new(house_ad, root: false)+ json = serializer.as_json++ expect(json[:id]).to eq(house_ad.id)+ expect(json[:name]).to eq("Test Ad")+ expect(json[:html]).to eq("<div>Test HTML</div>")+ expect(json[:visible_to_logged_in_users]).to eq(true)+ expect(json[:visible_to_anons]).to eq(false)+ expect(json[:created_at]).to be_present+ expect(json[:updated_at]).to be_present+ end++ it "does not include groups by default" do+ house_ad.update!(group_ids: [group.id])+ serializer = AdPlugin::HouseAdSerializer.new(house_ad, root: false)+ json = serializer.as_json++ expect(json).not_to have_key(:groups)+ end++ it "does not include categories by default" do+ house_ad.update!(category_ids: [category.id])+ serializer = AdPlugin::HouseAdSerializer.new(house_ad, root: false)+ json = serializer.as_json++ expect(json).not_to have_key(:categories)+ end+ end++ context "with include_groups option" do+ it "includes empty array when no groups" do+ serializer =+ AdPlugin::HouseAdSerializer.new(+ house_ad,+ scope: guardian,+ root: false,+ include_groups: true,+ )+ json = serializer.as_json++ expect(json[:groups]).to eq([])+ end++ it "includes multiple groups" do+ group2 = Fabricate(:group)+ house_ad.update!(group_ids: [group.id, group2.id])+ serializer =+ AdPlugin::HouseAdSerializer.new(+ house_ad,+ scope: guardian,+ root: false,+ include_groups: true,+ )+ json = serializer.as_json++ expect(json[:groups].length).to eq(2)+ expect(json[:groups].map { |g| g[:id] }).to contain_exactly(group.id, group2.id)+ end+ end++ context "with include_categories option" do+ it "includes empty array when no categories" do+ serializer = AdPlugin::HouseAdSerializer.new(house_ad, root: false, include_categories: true)+ json = serializer.as_json++ expect(json[:categories]).to eq([])+ end++ it "includes multiple categories" do+ category2 = Fabricate(:category)+ house_ad.update!(category_ids: [category.id, category2.id])+ serializer = AdPlugin::HouseAdSerializer.new(house_ad, root: false, include_categories: true)+ json = serializer.as_json++ expect(json[:categories].length).to eq(2)+ expect(json[:categories].map { |c| c[:id] }).to contain_exactly(category.id, category2.id)+ end+ end++ context "with both groups and categories" do+ it "includes both when both options are set" do+ house_ad.update!(category_ids: [category.id], group_ids: [group.id])+ serializer =+ AdPlugin::HouseAdSerializer.new(+ house_ad,+ scope: guardian,+ root: false,+ include_categories: true,+ include_groups: true,+ )+ json = serializer.as_json++ expect(json[:categories]).to be_present+ expect(json[:categories].length).to eq(1)+ expect(json[:groups]).to be_present+ expect(json[:groups].length).to eq(1)+ end+ end+enddiff --git a/plugins/discourse-adplugin/spec/system/ad_impression_spec.rb b/plugins/discourse-adplugin/spec/system/ad_impression_spec.rbnew file mode 100644index 00000000000..9867f6bafa1--- /dev/null+++ b/plugins/discourse-adplugin/spec/system/ad_impression_spec.rb@@ -0,0 +1,189 @@+# frozen_string_literal: true++describe "AdPlugin::AdImpression", type: :system do+ before { enable_current_plugin }++ describe "when a user sees an ad" do+ fab!(:house_ad)++ before do+ SiteSetting.house_ads_after_nth_topic = 1+ SiteSetting.ad_plugin_enable_tracking = true+ 10.times { Fabricate(:topic) }++ PluginStoreRow.create!(+ plugin_name: "discourse-adplugin",+ key: "ad-setting:topic_list_between",+ type_name: "JSON",+ value: house_ad.name,+ )+ end++ it "records the impression appropriately" do+ visit "/latest"++ impression = AdPlugin::AdImpression.last++ expect(impression.house_ad).to eq(house_ad)+ end+ end++ describe "house ad impression tracking visibility" do+ fab!(:house_ad)++ before do+ SiteSetting.ad_plugin_enable_tracking = true+ SiteSetting.house_ads_after_nth_topic = 20+ 20.times { Fabricate(:topic) }++ AdPlugin::HouseAdSetting.all["topic_list_between"] = house_ad.name+ AdPlugin::HouseAdSetting.publish_settings++ PluginStoreRow.create!(+ plugin_name: "discourse-adplugin",+ key: "ad-setting:topic_list_between",+ type_name: "JSON",+ value: house_ad.name,+ )+ end++ it "does not record impression before scrolling into view" do+ visit "/latest"++ expect(AdPlugin::AdImpression.count).to eq(0)++ page.execute_script("window.scrollTo(0, document.body.scrollHeight);")++ wait_for { AdPlugin::AdImpression.count == 1 }++ impression = AdPlugin::AdImpression.last+ expect(impression.house_ad).to eq(house_ad)+ end+ end++ describe "house ad impression tracking respects site setting" do+ fab!(:house_ad)++ before do+ 10.times { Fabricate(:topic) }+ SiteSetting.ad_plugin_enable_tracking = false+ SiteSetting.house_ads_after_nth_topic = 1++ AdPlugin::HouseAdSetting.all["topic_list_between"] = house_ad.name+ AdPlugin::HouseAdSetting.publish_settings+ end++ it "does not record an impression when ad_plugin_enable_tracking is false" do+ visit "/latest"++ page.execute_script("window.scrollTo(0, document.body.scrollHeight);")++ expect(AdPlugin::AdImpression.count).to eq(0)+ end+ end++ describe "house ad click tracking" do+ fab!(:house_ad) do+ Fabricate(+ :house_ad,+ html:+ '<a href="https://example.com/product" id="test-ad-link">Click here for great deals!</a>',+ )+ end++ let(:wait_for_impression) do+ wait_for { AdPlugin::AdImpression.count == 1 }+ AdPlugin::AdImpression.last+ end++ def prevent_link_navigation+ page.execute_script(<<~JS)+ document.addEventListener("click", function(e) {+ const a = e.target.closest("a");+ if (a) {+ e.preventDefault();+ }+ }, true);+ JS+ end++ before do+ SiteSetting.house_ads_after_nth_topic = 9+ SiteSetting.ad_plugin_enable_tracking = true+ 10.times { Fabricate(:topic) }++ PluginStoreRow.create!(+ plugin_name: "discourse-adplugin",+ key: "ad-setting:topic_list_between",+ type_name: "JSON",+ value: house_ad.name,+ )+ end++ it "records a click when user clicks on a link in the house ad" do+ visit "/latest"++ impression = wait_for_impression+ prevent_link_navigation++ expect(impression.clicked_at).to be_nil++ find("#test-ad-link").click+ wait_for { impression.reload.clicked_at.present? }++ expect(impression.clicked?).to eq(true)+ expect(impression.clicked_at).to be_within(5.seconds).of(Time.zone.now)+ end++ it "does not track clicks on non-link elements in house ads" do+ house_ad_with_text =+ Fabricate(:house_ad, html: '<div id="test-ad-div">Just text, no link</div>')++ PluginStoreRow.find_by(+ plugin_name: "discourse-adplugin",+ key: "ad-setting:topic_list_between",+ ).update!(value: house_ad_with_text.name)++ visit "/latest"++ impression = wait_for_impression+ find("#test-ad-div").click++ impression.reload+ expect(impression.clicked_at).to be_nil+ end++ it "only records one click per impression even with multiple clicks" do+ visit "/latest"++ impression = wait_for_impression+ prevent_link_navigation++ expect(page).to have_css("#test-ad-link")++ find("#test-ad-link").click+ wait_for { impression.reload.clicked_at.present? }++ first_click_time = impression.clicked_at++ find("#test-ad-link").click++ impression.reload+ expect(impression.clicked_at).to eq_time(first_click_time)+ end++ it "does not track clicks when ad_plugin_enable_tracking is false" do+ SiteSetting.ad_plugin_enable_tracking = false++ visit "/latest"++ expect(AdPlugin::AdImpression.count).to eq(0)++ prevent_link_navigation++ find("#test-ad-link").click++ expect(AdPlugin::AdImpression.count).to eq(0)+ end+ end+enddiff --git a/plugins/discourse-adplugin/spec/system/dfp_ads_spec.rb b/plugins/discourse-adplugin/spec/system/dfp_ads_spec.rbnew file mode 100644index 00000000000..3198482f2c4--- /dev/null+++ b/plugins/discourse-adplugin/spec/system/dfp_ads_spec.rb@@ -0,0 +1,44 @@+# frozen_string_literal: true++describe "DFP External Ads", type: :system do+ before { enable_current_plugin }++ fab!(:user) { Fabricate(:user, trust_level: 1) }+ fab!(:topic)++ before do+ SiteSetting.discourse_adplugin_enabled = true+ SiteSetting.dfp_publisher_id = "test_publisher_123"+ SiteSetting.dfp_through_trust_level = 2++ # Create 20 posts so we ca` n test nth post ads+ 20.times { Fabricate(:post, topic: topic) }+ end++ describe "DFP ads with impression tracking" do+ before do+ SiteSetting.ad_plugin_enable_tracking = true+ SiteSetting.dfp_topic_list_top_code = "topic_list_top_ad_unit"+ SiteSetting.dfp_topic_list_top_ad_sizes = "728*90 - leaderboard"+ 10.times { Fabricate(:topic) }+ end++ it "records impression when DFP ad is viewed" do+ sign_in(user)++ expect { visit "/latest" }.to change { AdPlugin::AdImpression.count }.by(1)++ impression = AdPlugin::AdImpression.last+ expect(impression.ad_type).to eq("dfp")+ expect(impression.house_ad).to be_nil+ expect(impression.placement).to eq("topic-list-top")+ end++ it "does not record impression if tracking is disabled" do+ SiteSetting.ad_plugin_enable_tracking = false+ sign_in(user)++ expect { visit "/latest" }.not_to change { AdPlugin::AdImpression.count }+ end+ end+end