Skip to content

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

Feature page routes for house ads (#36932)

Bannon Tanner91bcd2a35d59
diff --git a/plugins/discourse-adplugin/admin/assets/javascripts/admin/components/house-ads-route-selector.gjs b/plugins/discourse-adplugin/admin/assets/javascripts/admin/components/house-ads-route-selector.gjs
new file mode 100644
index 00000000000..139766eeaac
--- /dev/null
+++ b/plugins/discourse-adplugin/admin/assets/javascripts/admin/components/house-ads-route-selector.gjs
@@ -0,0 +1,17 @@
+import { classNames } from "@ember-decorators/component";
+import MultiSelectComponent from "discourse/select-kit/components/multi-select";
+import { HOUSE_AD_ROUTES } from "../lib/house-ad-routes";
+
+@classNames("route-selector")
+export default class HouseAdsRouteSelector extends MultiSelectComponent {
+ filterable = true;
+ filterPlaceholder = "admin.adplugin.house_ads.filter_placeholder";
+ allowCreate = false;
+ allowAny = false;
+ valueAttribute = "id";
+ nameProperty = "name";
+
+ get content() {
+ return HOUSE_AD_ROUTES;
+ }
+}
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.js
index 0584bbe5371..464d81f8a31 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
@@ -13,11 +13,13 @@ import Preview from "../../../components/modal/preview";
export default class adminPluginsHouseAdsShow extends Controller {
@service router;
@service modal;
+ @service siteSettings;
@controller("adminPlugins.houseAds") houseAdsController;
@tracked selectedCategories = [];
@tracked selectedGroups = [];
+ @tracked selectedRoutes = [];
@tracked saving = false;
@tracked savingStatus = "";
@tracked buffered;
@@ -27,6 +29,7 @@ export default class adminPluginsHouseAdsShow extends Controller {
this.buffered = new TrackedObject({ ...this.model });
this.selectedCategories = this.model.categories || [];
this.selectedGroups = this.model.groups || [];
+ this.selectedRoutes = this.model.routes || [];
}
get disabledSave() {
@@ -38,6 +41,10 @@ export default class adminPluginsHouseAdsShow extends Controller {
return true;
}
+ get routesEnabled() {
+ return this.siteSettings.ad_plugin_routes_enabled;
+ }
+
@action
async save() {
if (!this.saving) {
@@ -59,6 +66,7 @@ export default class adminPluginsHouseAdsShow extends Controller {
data.group_ids = this.buffered.groups
? this.buffered.groups.map((g) => g.id)
: [];
+ data.routes = this.buffered.routes || [];
try {
const ajaxData = await ajax(
newRecord
@@ -107,6 +115,12 @@ export default class adminPluginsHouseAdsShow extends Controller {
this.buffered.groups = groupIds;
}
+ @action
+ setRoutes(routes) {
+ this.selectedRoutes = routes;
+ this.buffered.routes = routes;
+ }
+
@action
cancel() {
this.buffered = new TrackedObject({ ...this.model });
diff --git a/plugins/discourse-adplugin/admin/assets/javascripts/admin/lib/house-ad-routes.js b/plugins/discourse-adplugin/admin/assets/javascripts/admin/lib/house-ad-routes.js
new file mode 100644
index 00000000000..e279f065f3a
--- /dev/null
+++ b/plugins/discourse-adplugin/admin/assets/javascripts/admin/lib/house-ad-routes.js
@@ -0,0 +1,4 @@
+export const HOUSE_AD_ROUTES = [
+ { id: "discovery.latest", name: "/latest" },
+ { id: "categories", name: "/categories" },
+];
diff --git a/plugins/discourse-adplugin/admin/assets/javascripts/admin/templates/admin-plugins/house-ads/show.gjs b/plugins/discourse-adplugin/admin/assets/javascripts/admin/templates/admin-plugins/house-ads/show.gjs
index e967eee83e1..ba0469707ea 100644
--- a/plugins/discourse-adplugin/admin/assets/javascripts/admin/templates/admin-plugins/house-ads/show.gjs
+++ b/plugins/discourse-adplugin/admin/assets/javascripts/admin/templates/admin-plugins/house-ads/show.gjs
@@ -6,6 +6,7 @@ import TextField from "discourse/components/text-field";
import GroupChooser from "discourse/select-kit/components/group-chooser";
import { i18n } from "discourse-i18n";
import HouseAdsCategorySelector from "../../../components/house-ads-category-selector";
+import HouseAdsRouteSelector from "../../../components/house-ads-route-selector";
export default <template>
<section class="edit-house-ad content-body">
@@ -50,9 +51,25 @@ export default <template>
class="house-ads-categories"
/>
<div class="description">
- {{i18n "admin.adplugin.house_ads.category_chooser_description"}}
+ {{#if @controller.routesEnabled}}
+ {{i18n
+ "admin.adplugin.house_ads.category_chooser_description_with_routes"
+ }}
+ {{else}}
+ {{i18n "admin.adplugin.house_ads.category_chooser_description"}}
+ {{/if}}
</div>
+ {{#if @controller.routesEnabled}}
+ <HouseAdsRouteSelector
+ @value={{@controller.selectedRoutes}}
+ @onChange={{@controller.setRoutes}}
+ />
+ <div class="description">
+ {{i18n "admin.adplugin.house_ads.route_chooser_description"}}
+ </div>
+ {{/if}}
+
<GroupChooser
@content={{@controller.site.groups}}
@value={{@controller.selectedGroups}}
diff --git a/plugins/discourse-adplugin/app/controllers/ad_plugin/house_ads_controller.rb b/plugins/discourse-adplugin/app/controllers/ad_plugin/house_ads_controller.rb
index c2094925f30..04182b8e872 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
@@ -35,6 +35,7 @@ module AdPlugin
def create
ad = HouseAd.new(house_ad_params)
if ad.save
+ sync_routes(ad, house_ad_params[:routes])
render_json_dump(
serialize_data(ad, HouseAdSerializer, { include_categories: true, include_groups: true }),
)
@@ -47,8 +48,9 @@ module AdPlugin
ad = HouseAd.find_by(id: house_ad_params[:id])
if ad.nil?
- ad = HouseAd.new(house_ad_params.except(:id))
+ ad = HouseAd.new(house_ad_params.except(:id, :routes))
if ad.save
+ sync_routes(ad, house_ad_params[:routes])
render_json_dump(
serialize_data(
ad,
@@ -60,7 +62,8 @@ module AdPlugin
render_json_error(ad)
end
else
- if ad.update(house_ad_params.except(:id))
+ if ad.update(house_ad_params.except(:id, :routes))
+ sync_routes(ad, house_ad_params[:routes])
render_json_dump(
serialize_data(
ad,
@@ -98,6 +101,7 @@ module AdPlugin
:visible_to_logged_in_users,
group_ids: [],
category_ids: [],
+ routes: [],
)
permitted[:visible_to_logged_in_users] = ActiveModel::Type::Boolean.new.cast(
permitted[:visible_to_logged_in_users],
@@ -108,8 +112,17 @@ module AdPlugin
permitted[:group_ids] ||= [] if !params.key?(:group_ids)
permitted[:category_ids] ||= [] if !params.key?(:category_ids)
+ permitted[:routes] ||= [] if !params.key?(:routes)
permitted
end
end
+
+ def sync_routes(ad, route_names)
+ return if route_names.nil?
+
+ ad.routes.delete_all
+
+ route_names.each { |route_name| ad.routes.create!(route_name: route_name) }
+ end
end
end
diff --git a/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb
index 32e61753a97..018391a0d85 100644
--- a/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb
+++ b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad.rb
@@ -11,6 +11,11 @@ module AdPlugin
foreign_key: "ad_plugin_house_ad_id",
dependent: :destroy
+ has_many :routes,
+ class_name: "AdPlugin::HouseAdRoute",
+ foreign_key: "ad_plugin_house_ad_id",
+ dependent: :delete_all
+
has_and_belongs_to_many :groups,
join_table: "ad_plugin_house_ads_groups",
foreign_key: "ad_plugin_house_ad_id",
@@ -61,6 +66,10 @@ module AdPlugin
query.to_a
end
+ def route_names
+ routes.pluck(:route_name)
+ end
+
private
def clear_cache
diff --git a/plugins/discourse-adplugin/app/models/ad_plugin/house_ad_route.rb b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad_route.rb
new file mode 100644
index 00000000000..250eba6f8f5
--- /dev/null
+++ b/plugins/discourse-adplugin/app/models/ad_plugin/house_ad_route.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module AdPlugin
+ class HouseAdRoute < ActiveRecord::Base
+ self.table_name = "ad_plugin_house_ads_routes"
+
+ belongs_to :house_ad, class_name: "AdPlugin::HouseAd", foreign_key: "ad_plugin_house_ad_id"
+
+ validates :route_name, presence: true
+ end
+end
+
+# == Schema Information
+#
+# Table name: ad_plugin_house_ads_routes
+#
+# route_name :string not null
+# ad_plugin_house_ad_id :bigint not null
+#
+# Indexes
+#
+# index_house_ads_pages (ad_plugin_house_ad_id,route_name) UNIQUE
+#
+# Foreign Keys
+#
+# fk_rails_... (ad_plugin_house_ad_id => ad_plugin_house_ads.id)
+#
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.rb
index 83a018d70e1..61a00eee7a6 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,12 @@ module AdPlugin
),
creatives:
ads.inject({}) do |h, ad|
- h[ad.name] = { id: ad.id, html: ad.html, category_ids: ad.category_ids }
+ h[ad.name] = {
+ id: ad.id,
+ html: ad.html,
+ category_ids: ad.category_ids,
+ routes: ad.routes.pluck(:route_name),
+ }
h
end,
}
diff --git a/plugins/discourse-adplugin/app/serializers/ad_plugin/house_ad_serializer.rb b/plugins/discourse-adplugin/app/serializers/ad_plugin/house_ad_serializer.rb
index 351bbe6cff9..c20c1d82411 100644
--- a/plugins/discourse-adplugin/app/serializers/ad_plugin/house_ad_serializer.rb
+++ b/plugins/discourse-adplugin/app/serializers/ad_plugin/house_ad_serializer.rb
@@ -8,11 +8,20 @@ module AdPlugin
:visible_to_logged_in_users,
:visible_to_anons,
:created_at,
- :updated_at
+ :updated_at,
+ :routes
has_many :groups, serializer: ::BasicGroupSerializer, embed: :objects
has_many :categories, serializer: ::BasicCategorySerializer, embed: :objects
+ def routes
+ object.route_names
+ end
+
+ def include_routes?
+ SiteSetting.ad_plugin_routes_enabled
+ end
+
def include_groups?
@options[:include_groups]
end
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js b/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js
index 8409fa201be..27203653a66 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/ad-component.js
@@ -32,6 +32,7 @@ export default class AdComponent extends Component {
"router.currentRoute.parent.attributes.category.read_restricted"
)
isRestrictedCategory;
+ @alias("router.currentRoute.name") currentRouteName;
_impressionId = null;
_clickTracked = false;
diff --git a/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs b/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs
index 3d6bfaa17de..519fcaf4e9c 100644
--- a/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs
+++ b/plugins/discourse-adplugin/assets/javascripts/discourse/components/house-ad.gjs
@@ -90,11 +90,25 @@ export default class HouseAd extends AdComponent {
// filter out ads that should not be shown on the current page
const filteredAds = adNames.filter((adName) => {
const ad = houseAds.creatives[adName];
- return (
- ad &&
- (!ad.category_ids?.length ||
- ad.category_ids.includes(this.currentCategoryId))
- );
+ if (!ad) {
+ return false;
+ }
+
+ const hasCategoryScope = ad.category_ids?.length > 0;
+ const hasRouteScope =
+ this.siteSettings.ad_plugin_routes_enabled && ad.routes?.length > 0;
+
+ // Global ad: no scopes
+ if (!hasCategoryScope && !hasRouteScope) {
+ return true;
+ }
+
+ // Scoped ad: match category or route
+ const matchesCategory =
+ hasCategoryScope && ad.category_ids.includes(this.currentCategoryId);
+ const matchesRoute =
+ hasRouteScope && ad.routes.includes(this.currentRouteName);
+ return matchesCategory || matchesRoute;
});
if (filteredAds.length > 0) {
if (!adIndex[placement]) {
diff --git a/plugins/discourse-adplugin/assets/stylesheets/adplugin.scss b/plugins/discourse-adplugin/assets/stylesheets/adplugin.scss
index 58444e25447..c0031fd3425 100644
--- a/plugins/discourse-adplugin/assets/stylesheets/adplugin.scss
+++ b/plugins/discourse-adplugin/assets/stylesheets/adplugin.scss
@@ -271,8 +271,10 @@
}
.category-selector,
- .group-chooser {
+ .group-chooser,
+ .route-selector {
margin-top: 1em;
+ margin-bottom: 0.2em;
}
}
diff --git a/plugins/discourse-adplugin/config/locales/client.en.yml b/plugins/discourse-adplugin/config/locales/client.en.yml
index fb299eab4af..21431589d68 100755
--- a/plugins/discourse-adplugin/config/locales/client.en.yml
+++ b/plugins/discourse-adplugin/config/locales/client.en.yml
@@ -39,6 +39,8 @@ en:
show_to_anons: "Show to anonymous users"
show_to_logged_in_users: "Show to logged in users"
category_chooser_description: "Choose the categories where this ad should be displayed or leave empty to show the ad everywhere. The `no_ads_for_categories` site setting has priority over this setting."
+ category_chooser_description_with_routes: "Choose the categories where this ad should be displayed. Leave this and route selections empty to show the ad everywhere. The `no_ads_for_categories` site setting has priority over this setting."
+ route_chooser_description: "Choose the pages/routes where this ad should be displayed. Leave this and category selections empty to show the ad everywhere."
group_chooser_description: "Choose the groups that can view this ad or leave empty to show the ad to all signed in users."
preview: "Preview"
diff --git a/plugins/discourse-adplugin/config/locales/server.en.yml b/plugins/discourse-adplugin/config/locales/server.en.yml
index f3f436e0928..b78b178f775 100755
--- a/plugins/discourse-adplugin/config/locales/server.en.yml
+++ b/plugins/discourse-adplugin/config/locales/server.en.yml
@@ -35,6 +35,7 @@ en:
house_ads_after_nth_post: 'If "Between posts" house ads are defined, show an ad after every N posts, where N is this value.'
house_ads_frequency: "If other ad networks are configured to show in an ad slot, how often should house ads be shown, as a percentage."
ads_txt: "Contents of your ads.txt file. More details available at <a href='https://support.google.com/adsense/answer/7532444?hl=en' target='_blank'>this Google AdSense help page</a>."
+ ad_plugin_routes_enabled: "Enable route targeting for house ads"
dfp_publisher_id: "Input your Google Ad Manager (formerly called DFP) network code, which is found in your network settings. NOTE: You will need to update the 'content security policy script src' setting. See <a href='https://meta.discourse.org/t/33734' target='_blank'>this topic</a> for the latest instructions."
dfp_publisher_id_mobile: "(Optional) If you want to use a different Ad Manager publisher id for the mobile version of the site, enter it here. Leave blank to use dfp_publisher_id on mobile."
diff --git a/plugins/discourse-adplugin/config/settings.yml b/plugins/discourse-adplugin/config/settings.yml
index 364bc9c4a36..954f80f13cb 100755
--- a/plugins/discourse-adplugin/config/settings.yml
+++ b/plugins/discourse-adplugin/config/settings.yml
@@ -41,6 +41,9 @@ ad_plugin:
ad_plugin_enable_tracking:
client: true
default: false
+ ad_plugin_routes_enabled:
+ client: true
+ default: false
adsense_plugin:
adsense_publisher_code:
diff --git a/plugins/discourse-adplugin/db/migrate/20251231190601_create_house_ads_routes_table.rb b/plugins/discourse-adplugin/db/migrate/20251231190601_create_house_ads_routes_table.rb
new file mode 100644
index 00000000000..7adf511eef4
--- /dev/null
+++ b/plugins/discourse-adplugin/db/migrate/20251231190601_create_house_ads_routes_table.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+class CreateHouseAdsRoutesTable < ActiveRecord::Migration[7.0]
+ def change
+ create_table :ad_plugin_house_ads_routes, id: false do |t|
+ t.bigint :ad_plugin_house_ad_id, null: false
+ t.string :route_name, null: false
+ end
+
+ add_foreign_key :ad_plugin_house_ads_routes,
+ :ad_plugin_house_ads,
+ column: :ad_plugin_house_ad_id
+
+ add_index :ad_plugin_house_ads_routes,
+ %i[ad_plugin_house_ad_id route_name],
+ unique: true,
+ name: "index_house_ads_pages"
+ end
+end
diff --git a/plugins/discourse-adplugin/spec/models/house_ad_setting_spec.rb b/plugins/discourse-adplugin/spec/models/house_ad_setting_spec.rb
index ddef8c58b9f..01d39d10cbe 100644
--- a/plugins/discourse-adplugin/spec/models/house_ad_setting_spec.rb
+++ b/plugins/discourse-adplugin/spec/models/house_ad_setting_spec.rb
@@ -103,6 +103,7 @@ describe AdPlugin::HouseAdSetting do
html: "<whatever-anon>",
category_ids: [],
id: a_kind_of(Integer),
+ routes: [],
},
)
expect(anon_message.group_ids).to eq(nil)
@@ -113,6 +114,7 @@ describe AdPlugin::HouseAdSetting do
html: "<whatever-logged-in>",
category_ids: [],
id: a_kind_of(Integer),
+ routes: [],
},
)
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.rb
index 07301ece855..38ca6208c9f 100644
--- a/plugins/discourse-adplugin/spec/models/house_ad_spec.rb
+++ b/plugins/discourse-adplugin/spec/models/house_ad_spec.rb
@@ -190,4 +190,30 @@ describe AdPlugin::HouseAd do
expect(ad.errors.count).to eq(2)
end
end
+
+ describe "routes" do
+ let(:ad) { AdPlugin::HouseAd.create(valid_attrs) }
+
+ it "returns route names" do
+ ad.routes.create!(route_name: "discovery.latest")
+ ad.routes.create!(route_name: "topic.show")
+
+ expect(ad.route_names).to contain_exactly("discovery.latest", "topic.show")
+ end
+
+ it "replaces routes cleanly" do
+ ad.routes.create!(route_name: "discovery.latest")
+
+ ad.routes.delete_all
+ ad.routes.create!(route_name: "discovery.top")
+
+ expect(ad.reload.route_names).to eq(["discovery.top"])
+ end
+
+ it "deletes routes when the ad is destroyed" do
+ ad.routes.create!(route_name: "discovery.latest")
+
+ expect { ad.destroy }.to change { AdPlugin::HouseAdRoute.count }.by(-1)
+ end
+ end
end
diff --git a/plugins/discourse-adplugin/spec/requests/house_ad_controller_spec.rb b/plugins/discourse-adplugin/spec/requests/house_ad_controller_spec.rb
index 0406757a34c..f92825d023a 100644
--- a/plugins/discourse-adplugin/spec/requests/house_ad_controller_spec.rb
+++ b/plugins/discourse-adplugin/spec/requests/house_ad_controller_spec.rb
@@ -17,6 +17,7 @@ describe AdPlugin::HouseAdsController do
end
before { enable_current_plugin }
+ before { SiteSetting.ad_plugin_routes_enabled = true }
describe "#update" do
context "when used by admins" do
@@ -31,6 +32,7 @@ describe AdPlugin::HouseAdsController do
visible_to_logged_in_users: "true",
category_ids: [category.id],
group_ids: [group.id],
+ routes: %w[discovery.latest topic.show],
}
expect(response.status).to eq(200)
@@ -40,6 +42,7 @@ describe AdPlugin::HouseAdsController do
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)
+ expect(house_ad_response[:routes]).to contain_exactly("discovery.latest", "topic.show")
serialized_category =
BasicCategorySerializer.new(category, scope: Guardian.new(admin)).as_json
@@ -58,6 +61,27 @@ describe AdPlugin::HouseAdsController do
expect(ad_copy.visible_to_logged_in_users).to eq(true)
expect(ad_copy.category_ids).to eq([category.id])
expect(ad_copy.group_ids).to eq([group.id])
+ expect(ad_copy.route_names).to contain_exactly("discovery.latest", "topic.show")
+ end
+
+ it "replaces routes on update" do
+ ad.routes.create!(route_name: "discovery.latest")
+
+ put "/admin/plugins/pluginad/house_creatives/#{ad.id}.json",
+ params: {
+ name: ad.name,
+ html: ad.html,
+ visible_to_anons: ad.visible_to_anons.to_s,
+ visible_to_logged_in_users: ad.visible_to_logged_in_users.to_s,
+ category_ids: [],
+ group_ids: [],
+ routes: ["discovery.top"],
+ }
+
+ expect(response.status).to eq(200)
+
+ ad_copy = AdPlugin::HouseAd.find(ad.id)
+ expect(ad_copy.reload.route_names).to eq(["discovery.top"])
end
end
@@ -73,6 +97,7 @@ describe AdPlugin::HouseAdsController do
visible_to_logged_in_users: "true",
group_ids: [group.id],
category_ids: [category.id],
+ routes: ["discovery.top"],
}
expect(response.status).to eq(404)
@@ -83,6 +108,7 @@ describe AdPlugin::HouseAdsController do
expect(ad_copy.visible_to_logged_in_users).to eq(false)
expect(ad_copy.category_ids).to eq([])
expect(ad_copy.group_ids).to eq([])
+ expect(ad_copy.route_names).to eq([])
end
end
end