Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬
Ruby actioncablechat-widgetconversationcustomer-supportdashboarddesigndockerdocker-imageherokuintercomjavascriptlivechatopensourcerailsrubysassvuejswhatsappzendesk
feat: preserve help center context across locale switches (#15594)
Sojan Josef0039f26682e
diff --git a/AGENTS.md b/AGENTS.mdindex 1f0b7f89ed0..1ace039de85 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -57,6 +57,9 @@- Prefer existing repo dependencies/client libraries over hand-rolled protocol code for auth, signing, parsing, or API plumbing.- Avoid one-use private helpers unless they hide real complexity or make the main flow meaningfully easier to read.- Prefer minimal, readable code over elaborate abstractions; clarity beats cleverness+- Optimize for human-readable, idiomatic Rails code. Prefer clear model methods, associations, scopes, and named route helpers over dense controller chains or manually assembled paths.+- Keep record relationships, association traversal, and reusable database queries in models or model scopes. Return an ActiveRecord relation when callers need to filter or order the result.+- Controllers should coordinate requests and prepare responses. Keep request-specific URL generation and presentation logic in controllers or view helpers. Before finalizing controller changes, check that relationship and traversal logic lives in the model layer.- Break down complex tasks into small, testable units- Iterate after confirmation- Avoid writing specs unless explicitly askeddiff --git a/app/controllers/public/api/v1/portals/articles_controller.rb b/app/controllers/public/api/v1/portals/articles_controller.rbindex 6a83d08fb7f..5ef20254aab 100644--- a/app/controllers/public/api/v1/portals/articles_controller.rb+++ b/app/controllers/public/api/v1/portals/articles_controller.rb@@ -22,6 +22,7 @@ class Public::Api::V1::Portals::ArticlesController < Public::Api::V1::Portals::Benddef show+ set_locale_switch_urls@og_image_url = helpers.set_og_image_url(@portal.name, @article.title)@parsed_content = render_article_content(@article.content.to_s)end@@ -70,7 +71,16 @@ class Public::Api::V1::Portals::ArticlesController < Public::Api::V1::Portals::Benddef set_article- @article = @portal.articles.find_by(slug: permitted_params[:article_slug])+ @article = @portal.articles.find_by!(slug: permitted_params[:article_slug])+ end++ def set_locale_switch_urls+ articles = @article.translation_family.published.includes(:category)++ @locale_switch_urls = articles.to_h do |article|+ url = helpers.generate_article_link(@portal.slug, article.slug, @theme_from_params, @is_plain_layout_enabled)+ [article.public_locale, url]+ endenddef set_categorydiff --git a/app/controllers/public/api/v1/portals/categories_controller.rb b/app/controllers/public/api/v1/portals/categories_controller.rbindex d1ebe92c60f..34335db4bae 100644--- a/app/controllers/public/api/v1/portals/categories_controller.rb+++ b/app/controllers/public/api/v1/portals/categories_controller.rb@@ -16,6 +16,7 @@ class Public::Api::V1::Portals::CategoriesController < Public::Api::V1::Portals:enddef show+ set_locale_switch_urls@og_image_url = helpers.set_og_image_url(@portal.name, @category.name)end@@ -28,6 +29,19 @@ class Public::Api::V1::Portals::CategoriesController < Public::Api::V1::Portals:render_404 && return if @category.blank?end+ def set_locale_switch_urls+ @locale_switch_urls = @category.translation_family.to_h do |category|+ url = helpers.generate_category_link(+ portal_slug: @portal.slug,+ category_locale: category.locale,+ category_slug: category.slug,+ theme: @theme_from_params,+ is_plain_layout_enabled: @is_plain_layout_enabled+ )+ [category.locale, url]+ end+ end+def load_category_articles@articles = @category.articles.published.order(:position).includes(:author)@category_authors = @articles.filter_map(&:author).uniqdiff --git a/app/javascript/portal/portalHelpers.js b/app/javascript/portal/portalHelpers.jsindex 1d2ae2e4299..4ee8eb97bc0 100644--- a/app/javascript/portal/portalHelpers.js+++ b/app/javascript/portal/portalHelpers.js@@ -72,8 +72,13 @@ export const InitializationHelpers = {const localeSwitcher = e.target.closest('.locale-switcher');if (!localeSwitcher) return;- const { portalSlug } = localeSwitcher.dataset;- window.location.href = `/hc/${encodeURIComponent(portalSlug)}/${encodeURIComponent(localeSwitcher.value)}/`;+ const targetUrl = new URL(localeSwitcher.value, window.location.origin);+ const isHelpCenterUrl = targetUrl.pathname.startsWith('/hc/');++ if (targetUrl.origin !== window.location.origin || !isHelpCenterUrl)+ return;++ window.location.assign(targetUrl.href);});},diff --git a/app/javascript/portal/specs/portal.spec.js b/app/javascript/portal/specs/portal.spec.jsindex c3577ec3b16..5e674043cb4 100644--- a/app/javascript/portal/specs/portal.spec.js+++ b/app/javascript/portal/specs/portal.spec.js@@ -12,7 +12,7 @@ describe('InitializationHelpers.navigateToLocalePage', () => {beforeEach(() => {dom = new JSDOM(- '<!DOCTYPE html><html><body><div class="locale-switcher" data-portal-slug="test-slug"><select><option value="en">English</option><option value="fr">French</option></select></div></body></html>',+ '<!DOCTYPE html><html><body><select class="locale-switcher"><option value="/hc/test-slug/en">English</option><option value="/hc/test-slug/fr">French</option></select></body></html>',{ url: 'http://localhost/' });document = dom.window.document;@@ -45,6 +45,36 @@ describe('InitializationHelpers.navigateToLocalePage', () => {expect(documentSpy).toHaveBeenCalledWith('change', expect.any(Function));documentSpy.mockRestore();});++ it('navigates to a same-origin help center URL', () => {+ const documentSpy = vi.spyOn(document, 'addEventListener');+ const assign = vi.fn();+ global.window = { location: { origin: 'http://localhost', assign } };++ InitializationHelpers.navigateToLocalePage();+ const changeHandler = documentSpy.mock.calls[0][1];+ changeHandler({+ target: { closest: () => ({ value: '/hc/test-slug/fr' }) },+ });++ expect(assign).toHaveBeenCalledWith('http://localhost/hc/test-slug/fr');+ documentSpy.mockRestore();+ });++ it('ignores URLs outside the current help center', () => {+ const documentSpy = vi.spyOn(document, 'addEventListener');+ const assign = vi.fn();+ global.window = { location: { origin: 'http://localhost', assign } };++ InitializationHelpers.navigateToLocalePage();+ const changeHandler = documentSpy.mock.calls[0][1];+ ['https://example.com/hc/phishing', '/app/accounts/1'].forEach(value => {+ changeHandler({ target: { closest: () => ({ value }) } });+ });++ expect(assign).not.toHaveBeenCalled();+ documentSpy.mockRestore();+ });});describe('openExternalLinksInNewTab', () => {diff --git a/app/models/article.rb b/app/models/article.rbindex 555992f59c5..b2842c846d8 100644--- a/app/models/article.rb+++ b/app/models/article.rb@@ -130,6 +130,17 @@ class Article < ApplicationRecordarticle.associated_article_id || article.idend+ def translation_family+ root_id = associated_article_id || id+ articles = portal.articles++ articles.where(id: root_id).or(articles.where(associated_article_id: root_id))+ end++ def public_locale+ category.present? ? category.locale : locale+ end+def draft!update(status: :draft)enddiff --git a/app/models/category.rb b/app/models/category.rbindex 35237219178..cb55fd7f7ca 100644--- a/app/models/category.rb+++ b/app/models/category.rb@@ -73,6 +73,13 @@ class Category < ApplicationRecordparams[:page] || 1end+ def translation_family+ root_id = associated_category_id || id+ categories = portal.categories++ categories.where(id: root_id).or(categories.where(associated_category_id: root_id))+ end+def self.update_positions(portal:, positions_hash:)return if positions_hash.blank?diff --git a/app/views/public/api/v1/portals/_header.html.erb b/app/views/public/api/v1/portals/_header.html.erbindex 5e784f8a538..8be3b19151e 100644--- a/app/views/public/api/v1/portals/_header.html.erb+++ b/app/views/public/api/v1/portals/_header.html.erb@@ -83,14 +83,14 @@<div class="flex items-center gap-1 px-1 py-2 cursor-pointer"><%= render partial: 'icons/globe' %><select- data-portal-slug="<%= @portal.slug %>"class="w-24 overflow-hidden text-sm font-medium leading-tight bg-white appearance-none cursor-pointer dark:bg-slate-900 text-ellipsis whitespace-nowrap focus:outline-none focus:shadow-outline locale-switcher"><% if @portal.draft_locale?(@locale) %><option selected disabled value="<%= @locale %>"><%= "#{language_name(@locale)} (#{@locale})" %></option><% end %><% @portal.public_locale_codes.each do |locale| %>- <option <%= locale == @locale ? 'selected': '' %> value="<%= locale %>"><%= "#{language_name(locale)} (#{locale})" %></option>+ <% switch_url = @locale_switch_urls&.[](locale) || generate_home_link(@portal.slug, locale, @theme_from_params, @is_plain_layout_enabled) %>+ <option <%= locale == @locale ? 'selected': '' %> value="<%= switch_url %>"><%= "#{language_name(locale)} (#{locale})" %></option><% end %></select><%= render partial: 'icons/chevron-down' %>diff --git a/app/views/public/api/v1/portals/_mobile_menu.html.erb b/app/views/public/api/v1/portals/_mobile_menu.html.erbindex 2624d4e61a9..e7a59568a3d 100644--- a/app/views/public/api/v1/portals/_mobile_menu.html.erb+++ b/app/views/public/api/v1/portals/_mobile_menu.html.erb@@ -60,14 +60,14 @@<div class="flex items-center gap-3 py-2 cursor-pointer stroke-slate-800 dark:stroke-slate-100"><%= render partial: 'icons/globe' %><select- data-portal-slug="<%= @portal.slug %>"class="flex-1 bg-transparent text-lg font-medium cursor-pointer focus:outline-none locale-switcher text-slate-800 dark:text-slate-100 hover:text-slate-700 dark:hover:text-slate-200"><% if @portal.draft_locale?(@locale) %><option selected disabled value="<%= @locale %>"><%= "#{language_name(@locale)} (#{@locale})" %></option><% end %><% @portal.public_locale_codes.each do |locale| %>- <option <%= locale == @locale ? 'selected': '' %> value="<%= locale %>"><%= "#{language_name(locale)} (#{locale})" %></option>+ <% switch_url = @locale_switch_urls&.[](locale) || generate_home_link(@portal.slug, locale, @theme_from_params, @is_plain_layout_enabled) %>+ <option <%= locale == @locale ? 'selected': '' %> value="<%= switch_url %>"><%= "#{language_name(locale)} (#{locale})" %></option><% end %></select></div>diff --git a/app/views/public/api/v1/portals/documentation_layout/_topbar.html.erb b/app/views/public/api/v1/portals/documentation_layout/_topbar.html.erbindex 00f408d705e..ea80a33c69d 100644--- a/app/views/public/api/v1/portals/documentation_layout/_topbar.html.erb+++ b/app/views/public/api/v1/portals/documentation_layout/_topbar.html.erb@@ -54,7 +54,8 @@<div class="px-2.5 pt-2 pb-1.5 text-xs font-semibold text-n-slate-10 uppercase tracking-wider"><%= I18n.t('public_portal.sidebar.language') %></div><% portal.public_locale_codes.each do |code| %><% is_current = code == locale %>- <a href="/hc/<%= portal.slug %>/<%= code %>/"+ <% switch_url = @locale_switch_urls&.[](code) || generate_home_link(portal.slug, code, @theme_from_params, @is_plain_layout_enabled) %>+ <a href="<%= switch_url %>"data-turbo="false"class="flex items-center gap-2.5 px-2.5 py-2 text-sm rounded-md transition <%= is_current ? 'bg-n-portal-soft text-n-portal' : 'text-n-slate-11 hover:bg-n-alpha-2 hover:text-n-slate-12' %>"><span class="text-xs font-semibold uppercase min-w-9 text-center text-n-slate-11 bg-n-slate-2 border border-solid border-n-weak rounded px-1.5 py-0.5 flex-shrink-0"><%= code %></span>diff --git a/spec/controllers/public/api/v1/portals/articles_controller_spec.rb b/spec/controllers/public/api/v1/portals/articles_controller_spec.rbindex 89d9de6b4e9..1cfb69b4f95 100644--- a/spec/controllers/public/api/v1/portals/articles_controller_spec.rb+++ b/spec/controllers/public/api/v1/portals/articles_controller_spec.rb@@ -11,11 +11,14 @@ RSpec.describe 'Public Articles API', type: :request docontent: 'This is a *test* content with ^markdown^', views: 0)end+ let!(:translated_article) do+ create(:article, category: category_2, portal: portal, author: agent, associated_article_id: article.id, views: 5)+ end+before doENV['HELPCENTER_URL'] = ENV.fetch('FRONTEND_URL', nil)create(:article, category: category, portal: portal, account_id: account.id, author_id: agent.id, views: 15)- create(:article, category: category, portal: portal, account_id: account.id, author_id: agent.id, associated_article_id: article.id, views: 1)- create(:article, category: category_2, portal: portal, account_id: account.id, author_id: agent.id, associated_article_id: article.id, views: 5)+ create(:article, category: category, portal: portal, account_id: account.id, author_id: agent.id, views: 1)create(:article, category: category_2, portal: portal, account_id: account.id, author_id: agent.id, views: 4)create(:article, category: category_2, portal: portal, account_id: account.id, author_id: agent.id, status: :draft)end@@ -148,6 +151,89 @@ RSpec.describe 'Public Articles API', type: :request doexpect(response).to have_http_status(:success)expect(response.body).to include('lang="es"')end++ it 'links to the matching published translation from the locale switcher' do+ get "/hc/#{portal.slug}/articles/#{article.slug}"++ expect(response).to have_http_status(:success)+ expect(response.body).to include(%(value="/hc/#{portal.slug}/articles/#{translated_article.slug}"))+ end++ %i[draft archived].each do |status|+ it "falls back to the locale home for a #{status} translation" do+ translated_article.update!(status: status)++ get "/hc/#{portal.slug}/articles/#{article.slug}"++ expect(response).to have_http_status(:success)+ expect(response.body).to include(%(value="/hc/#{portal.slug}/es"))+ expect(response.body).not_to include("/hc/#{portal.slug}/articles/#{translated_article.slug}")+ end+ end++ it 'links to the original article and sibling translations from a translated article' do+ portal.update!(config: portal.config.merge('allowed_locales' => %w[en es fr]))+ french_article = create(:article, locale: 'fr', portal: portal, author: agent, associated_article_id: article.id)++ get "/hc/#{portal.slug}/articles/#{french_article.slug}"++ expect(response).to have_http_status(:success)+ expect(response.body).to include(+ %(value="/hc/#{portal.slug}/articles/#{article.slug}"),+ %(value="/hc/#{portal.slug}/articles/#{translated_article.slug}"),+ %(value="/hc/#{portal.slug}/articles/#{french_article.slug}")+ )+ end++ it 'returns not found for an article in another portal' do+ foreign_article = create(:article)++ get "/hc/#{portal.slug}/articles/#{foreign_article.slug}"++ expect(response).to have_http_status(:not_found)+ end++ it 'excludes translations from other portals' do+ portal.update!(config: portal.config.merge('allowed_locales' => %w[en es fr]))+ foreign_portal = create(:portal, config: { allowed_locales: ['fr'] })+ foreign_article = create(:article, portal: foreign_portal, locale: 'fr', associated_article_id: article.id)++ get "/hc/#{portal.slug}/articles/#{article.slug}"++ expect(response).to have_http_status(:success)+ expect(response.body).to include(%(value="/hc/#{portal.slug}/fr"))+ expect(response.body).not_to include(foreign_article.slug)+ end++ it 'links to the matching article in the documentation layout' do+ portal.update!(config: portal.config.merge('layout' => 'documentation'))++ get "/hc/#{portal.slug}/articles/#{article.slug}"++ links = Nokogiri::HTML(response.body).css('header details a').map { |link| link['href'] }+ expect(links).to include("/hc/#{portal.slug}/articles/#{translated_article.slug}")+ end++ it 'uses the category locale after a translated category changes language' do+ portal.update!(config: portal.config.merge('allowed_locales' => %w[en es fr]))+ admin = create(:user, account: portal.account, role: :administrator)++ put "/api/v1/accounts/#{portal.account_id}/portals/#{portal.slug}/categories/#{category_2.id}",+ params: { category: { locale: 'fr' } }, headers: admin.create_new_auth_token++ expect(response).to have_http_status(:success)+ expect([category_2.reload.locale, translated_article.reload.locale]).to eq(%w[fr es])++ get "/hc/#{portal.slug}/articles/#{article.slug}"++ switchers = Nokogiri::HTML(response.body).css('select.locale-switcher')+ expect(switchers.size).to eq(2)+ switchers.each do |switcher|+ options = switcher.css('option').to_h { |option| [option.text, option['value']] }+ expect(options).to include('Spanish (es)' => "/hc/#{portal.slug}/es",+ 'French (fr)' => "/hc/#{portal.slug}/articles/#{translated_article.slug}")+ end+ endenddescribe 'GET /public/api/v1/portals/:slug/articles/:slug.md (markdown)' dodiff --git a/spec/controllers/public/api/v1/portals/categories_controller_spec.rb b/spec/controllers/public/api/v1/portals/categories_controller_spec.rbindex ea1a2811e4c..3e501aeed21 100644--- a/spec/controllers/public/api/v1/portals/categories_controller_spec.rb+++ b/spec/controllers/public/api/v1/portals/categories_controller_spec.rb@@ -2,7 +2,9 @@ require 'rails_helper'RSpec.describe 'Public Categories API', type: :request dolet!(:account) { create(:account) }- let!(:portal) { create(:portal, slug: 'test-portal', custom_domain: 'www.example.com') }+ let!(:portal) do+ create(:portal, slug: 'test-portal', custom_domain: 'www.example.com', config: { allowed_locales: %w[en es] })+ endbefore docreate(:category, slug: 'test-category-1', portal_id: portal.id, account_id: account.id)@@ -30,6 +32,62 @@ RSpec.describe 'Public Categories API', type: :request doexpect(response).to have_http_status(:success)end+ it 'links to the matching translated category from the locale switcher' do+ category = portal.categories.first+ translation = create(:category, locale: 'es', portal: portal, associated_category_id: category.id)++ get "/hc/#{portal.slug}/#{category.locale}/categories/#{category.slug}"++ expect(response).to have_http_status(:success)+ expect(response.body).to include(%(value="/hc/#{portal.slug}/es/categories/#{translation.slug}"))+ end++ it 'links to the locale home when a translated category does not exist' do+ category = portal.categories.first++ get "/hc/#{portal.slug}/#{category.locale}/categories/#{category.slug}"++ expect(response).to have_http_status(:success)+ expect(response.body).to include(%(value="/hc/#{portal.slug}/es"))+ end++ it 'links to the original category and sibling translations from a translated category' do+ portal.update!(config: portal.config.merge('allowed_locales' => %w[en es fr]))+ category = portal.categories.first+ spanish_category = create(:category, locale: 'es', portal: portal, associated_category_id: category.id)+ french_category = create(:category, locale: 'fr', portal: portal, associated_category_id: category.id)++ get "/hc/#{portal.slug}/fr/categories/#{french_category.slug}"++ expect(response).to have_http_status(:success)+ expect(response.body).to include(+ %(value="/hc/#{portal.slug}/en/categories/#{category.slug}"),+ %(value="/hc/#{portal.slug}/es/categories/#{spanish_category.slug}")+ )+ end++ it 'links to the translated category in the documentation layout' do+ category = portal.categories.first+ translation = create(:category, locale: 'es', portal: portal, associated_category_id: category.id)+ portal.update!(config: portal.config.merge('layout' => 'documentation'))++ get "/hc/#{portal.slug}/#{category.locale}/categories/#{category.slug}"++ expect(response.body).to include(%(href="/hc/#{portal.slug}/es/categories/#{translation.slug}"))+ end++ it 'excludes translations from other portals' do+ category = portal.categories.first+ foreign_portal = create(:portal, config: { allowed_locales: %w[en es] })+ foreign_category = create(:category, portal: foreign_portal, locale: 'es', associated_category_id: category.id)++ get "/hc/#{portal.slug}/en/categories/#{category.slug}"++ expect(response).to have_http_status(:success)+ expect(response.body).to include(%(value="/hc/#{portal.slug}/es"))+ expect(response.body).not_to include("/hc/#{portal.slug}/es/categories/#{foreign_category.slug}")+ end+it 'does not show the authors line when the only author has been deleted' docategory = portal.categories.firstarticle = create(:article, category: category, portal: portal, account_id: account.id)diff --git a/spec/controllers/public/api/v1/portals_controller_spec.rb b/spec/controllers/public/api/v1/portals_controller_spec.rbindex fb5bd5e1e18..b6493c540eb 100644--- a/spec/controllers/public/api/v1/portals_controller_spec.rb+++ b/spec/controllers/public/api/v1/portals_controller_spec.rb@@ -105,7 +105,11 @@ RSpec.describe Public::Api::V1::PortalsController, type: :request doswitchers.each do |switcher|options = switcher.css('option')- expect(options.map { |option| option['value'] }).to include('en', 'es', 'fr')+ expect(options.map { |option| option['value'] }).to include(+ "/hc/#{portal.slug}/en",+ 'es',+ "/hc/#{portal.slug}/fr"+ )expect(options.any? do |option|option['value'] == 'es' && option['selected'].present? && option['disabled'].present?diff --git a/spec/enterprise/jobs/captain/articles/translate_job_spec.rb b/spec/enterprise/jobs/captain/articles/translate_job_spec.rbindex 119c93b1c8d..f7e02c1e646 100644--- a/spec/enterprise/jobs/captain/articles/translate_job_spec.rb+++ b/spec/enterprise/jobs/captain/articles/translate_job_spec.rb@@ -58,6 +58,22 @@ RSpec.describe Captain::Articles::TranslateJob, type: :job do)end+ it 'keeps the original article as the root when translating a translation' do+ portal.update!(config: portal.config.merge('allowed_locales' => %w[en es fr]))+ category_fr = create(:category, portal: portal, account: account, locale: 'fr', slug: 'premiers-pas')+ allow(title_service).to receive(:perform).and_return({ message: 'Premiers pas' }, { message: 'Primeros pasos' })+ allow(content_service).to receive(:perform).and_return({ message: 'Bienvenue' }, { message: 'Bienvenido' })++ described_class.perform_now(account, article.id, 'fr', category_fr.id, user)+ french_article = portal.articles.find_by!(locale: 'fr')++ described_class.perform_now(account, french_article.id, 'es', category_es.id, user)+ spanish_article = portal.articles.find_by!(locale: 'es')++ expect(spanish_article.associated_article_id).to eq(article.id)+ expect(spanish_article.translation_family).to contain_exactly(article, french_article, spanish_article)+ end+it 'calls the translation service with the correct language' dodescribed_class.perform_now(account, article.id, 'es', category_es.id, user)