Class: Crm::PostsController

Inherits:
CrmController show all
Includes:
ActionView::Helpers::TextHelper, Controllers::Articlable, Controllers::Attachable
Defined in:
app/controllers/crm/posts_controller.rb

Overview

Controller: posts.

Constant Summary

Constants included from Controllers::Attachable

Controllers::Attachable::PUBLICATIONS_PER_PAGE

Constants included from Controllers::ReferenceFindable

Controllers::ReferenceFindable::ID_EMBEDDED_PATTERNS

Constants included from Controllers::AnalyticsEvents

Controllers::AnalyticsEvents::MAX_QUEUED_EVENTS, Controllers::AnalyticsEvents::SESSION_KEY

Constants included from Controllers::ErrorRendering

Controllers::ErrorRendering::NON_CONTENT_PATH_PREFIXES

Constants included from Www::SeoHelper

Www::SeoHelper::AWARDS, Www::SeoHelper::CA_ADDRESS, Www::SeoHelper::CA_BUSINESS_HOURS, Www::SeoHelper::CA_CONTACT_POINT, Www::SeoHelper::CA_CURRENCIES, Www::SeoHelper::CA_DESCRIPTION, Www::SeoHelper::CA_FOUNDING_DATE, Www::SeoHelper::CA_GLOBAL_LOCATION_NUMBER, Www::SeoHelper::CA_LEGAL_NAME, Www::SeoHelper::CA_LOCAL_BUSINESS, Www::SeoHelper::CA_ONLINE_STORE, Www::SeoHelper::CA_RETURN_POLICY, Www::SeoHelper::CA_SALES_DEPARTMENT, Www::SeoHelper::CA_SERVICE_AREA, Www::SeoHelper::CA_URL, Www::SeoHelper::CA_VAT_ID, Www::SeoHelper::CA_WAREHOUSE_DEPARTMENT, Www::SeoHelper::CA_WAREHOUSE_HOURS, Www::SeoHelper::COMPANY_EMAIL, Www::SeoHelper::COMPANY_LOGO, Www::SeoHelper::COMPANY_NAME, Www::SeoHelper::COMPANY_SLOGAN, Www::SeoHelper::EXPERTISE, Www::SeoHelper::FAX_NUMBER, Www::SeoHelper::GS1_COMPANY_PREFIX, Www::SeoHelper::ISO6523_CODE, Www::SeoHelper::PAYMENT_METHODS, Www::SeoHelper::PHONE_NUMBER, Www::SeoHelper::PRIMARY_NAICS, Www::SeoHelper::REFUND_TYPE, Www::SeoHelper::RETURN_FEES, Www::SeoHelper::RETURN_METHOD, Www::SeoHelper::RETURN_POLICY_CATEGORY, Www::SeoHelper::SECONDARY_NAICS, Www::SeoHelper::SOCIAL_PROFILES, Www::SeoHelper::US_ADDRESS, Www::SeoHelper::US_BUSINESS_HOURS, Www::SeoHelper::US_CONTACT_POINT, Www::SeoHelper::US_CURRENCIES, Www::SeoHelper::US_DESCRIPTION, Www::SeoHelper::US_FOUNDING_DATE, Www::SeoHelper::US_GLOBAL_LOCATION_NUMBER, Www::SeoHelper::US_IMAGE, Www::SeoHelper::US_LEGAL_NAME, Www::SeoHelper::US_LOCAL_BUSINESS, Www::SeoHelper::US_ONLINE_STORE, Www::SeoHelper::US_RETURN_POLICY, Www::SeoHelper::US_SALES_DEPARTMENT, Www::SeoHelper::US_SERVICE_AREA, Www::SeoHelper::US_TAX_ID, Www::SeoHelper::US_URL, Www::SeoHelper::US_WAREHOUSE_DEPARTMENT, Www::SeoHelper::US_WAREHOUSE_HOURS

Constants included from IconHelper

IconHelper::CUSTOM_ICON_MAP, IconHelper::CUSTOM_SVG_DIR, IconHelper::DEFAULT_FAMILY

Instance Method Summary collapse

Methods included from Controllers::Articlable

#convert_type, #load_article, #show_description, #show_solution

Methods included from Controllers::Attachable

#attach, #publication_modal, #remove_attachment, #search_library

Methods inherited from CrmController

#access_denied, #context_id, #context_object, #crm_home_path, #current_ability, #default_url_options, #download_temp, #get_tempfile_path_for_download, #init_status_job_collector, #initialize_crm_lazy_chunks, #persist_enqueued_status_jobs, #record_not_found, #redirect_to_job_or_fallback, #render_edit_action, #set_context, #set_download_path, #stash_file_for_temp_download, #sync_admin_presence_cookie

Methods inherited from ApplicationController

#account_impersonated?, #add_to_flash, #after_sign_in_path_for, #bypass_forgery_protection?, #chat_enabled?, #cloudflare_cleared?, #default_catalog, #default_url_options, #enable_turbo_frames, #find_publication, #fix_invalid_accept_header, #init_js_utils, #is_globals_call?, #layout_by_resource, #locale_store, #redirect_to, #require_employee_for_crm, #set_base_host, #set_real_ip, #set_report_errors_for, #should_render_layout?, #stamp_impersonation_context, #warmlyyours_canada_ip?, #warmlyyours_ip?, #y

Methods included from Controllers::ReturnPathHandling

#check_for_return_path, #redirect_to_return_path_or_default

Methods included from Controllers::AnalyticsEvents

#consume_queued_analytics_events, #track_event

Methods included from Controllers::DeviceDetection

#device_detector, #is_ie?

Methods included from Controllers::SubdomainDetection

#is_crm_request?, #is_www_request?, #json_request?

Methods included from Controllers::TurboSafeRedirect

#redirect_to

Methods included from Controllers::TrackingDetection

#bot_request?, #gdpr_country?, #gdpr_country_data, #prevent_bots, #set_tracking_cookie, #track_visitor?

Methods included from Controllers::AcceleratedFileSending

#send_file_accelerated, #send_upload_accelerated

Methods included from Controllers::ErrorRendering

#excp_string, #mail_to_for_error_reporting, #render_400, #render_404, #render_406, #render_410, #render_500, #render_invalid_authenticity_token, #render_ip_spoof_error, #render_unpermitted_parameters, #safe_referer_or_fallback

Methods included from Controllers::TurnstileVerification

#load_turnstile_script_tag, #turnstile_lazy_widget, #turnstile_script_tag, #turnstile_widget, #validate_turnstile!

Methods included from Controllers::CloudflareCaching

edge_cached, #edge_cached_action?, #reset_cloudflare_cache, #set_cloudflare_cache, #skip_edge_cache!, #skip_session

Methods included from Controllers::Webpackable

#preload_webpack_fonts, #webpack_css_include, #webpack_css_url, #webpack_js_include, #wpd_is_running?

Methods included from Controllers::Localizable

#cloudflare_country_locale, #determine_request_locale, #geocoder_locale, #guest_user_locale_check, #locale_optional_www_auth_path?, #param_locale, #set_locale, #set_request_locale, #skip_localization?, #warmlyyours_ip_locale

Methods included from Controllers::Authenticable

#access_denied, #authenticate_account, #authenticate_account!, #authenticate_account_from_login_token!, #check_is_a_manager, #check_is_a_sales_manager, #check_is_an_admin, #check_is_an_employee, #check_party, #clear_mismatched_guest_user, #create_guest_user, #credentials?, #current_or_guest_user, #current_or_guest_user_id_read_only, #current_user, #devise_mapping, #fully_logged_in?, #generate_bot_id, #guest_user, #identifiable?, #init_current_user, #initialize_guest, #load_context_user, #logging_in, #resource, #resource_name, #restrict_access_for_non_employees, #scrubbed_request_path, #user_object, #warn_on_session_guest_id_leak

Methods included from ApplicationHelper

#better_number_to_currency, #check_force_logout, #check_or_cross, #check_or_times, #embedded_tab_frame_id, #error_messages, #general_disclaimer_on_product_installation_and_local_codes, #gridjs_from_html_table, #gridjs_table, #is_wy_ip, #line_break, #parent_layout, #pass_or_fail, #render_error_messages_list, #render_video_card, #resolved_auth_form_turbo_frame, #return_path_or, #safe_css_color, #set_return_path_if_present, #set_section_if_present, #tab_frame_id, #to_underscore, #track_page?, #turbo_section_wrapper, #turbo_tabs_request?, #url_on_same_domain_as_request, #widget_index_daily_focus_index_path, #working_hours?, #yes_or_no, #yes_or_no_highlighted, #yes_or_no_with_check_or_cross, #youtube_video

Methods included from UppyUploaderHelper

#file_uploader, #image_uploader, #large_file_uploader_s3, #lead_sketch_uploader, #rma_image_uploader, #rma_image_uploader_s3, #uppy_uploader, #video_uploader

Methods included from Www::ImagesHelper

#image_asset_tag, #image_asset_url

Methods included from Www::SeoHelper

#add_page_schema, #add_webpage_schema, #canada?, #company_social_links, #ensure_context_json, #json_ld_script_tag, #local_business_schema, #online_store_id, #online_store_schema, #page_main_entity, #page_main_entity_json, #render_auto_collection_page_schema, #render_collection_page_schema, #render_local_business_schema, #render_online_store_schema, #render_page_schemas, #render_page_video_schemas, #render_webpage_schema, #render_webpage_schema_with_collections, #usa?

Methods included from UrlsHelper

#catalog_breadcrumb_links, #catalog_link, #catalog_link_for_product_line, #catalog_link_for_sku, #cms_link, #delocalized_path, #path_to_sales_product_sku, #path_to_sales_product_sku_for_product_line, #path_to_sales_product_sku_for_product_line_slug, #product_line_from_catalog_link, #protocol_neutral_url, #sanitize_external_url, #valid_external_url?

Methods included from IconHelper

#account_nav_icon, #fa_icon, #star_rating_html

Instance Method Details

#analyze_seoObject

POST /posts/:id/analyze_seo
Triggers AI SEO analysis for all sitemaps (locales) of this post



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'app/controllers/crm/posts_controller.rb', line 325

def analyze_seo
  authorize!(:update, Post)

  site_maps = @post.site_maps.to_a

  if site_maps.empty?
    flash[:warning] = 'No sitemaps found for this post. The post may need to be published first.'
    redirect_to post_path(@post, anchor: 'seo-schema')
    return
  end

  return_path = post_path(@post, anchor: 'seo-schema')

  # Queue analysis for each sitemap with return path back to post. The jobs
  # surface automatically in the global Jobs tracker — every status-tracked
  # worker enqueued during a CRM request is captured (see
  # CrmController#persist_enqueued_status_jobs + the Sidekiq client middleware).
  site_maps.each do |site_map|
    SeoPageAnalysisWorker.perform_async(site_map.id, { return_path: return_path })
  end

  flash[:info] = "SEO analysis queued for #{site_maps.size} locale(s): #{site_maps.map(&:locale).join(', ')}. Analysis takes ~1 minute per locale."

  # Redirect back to the post immediately — queued jobs appear in the Jobs
  # tracker (top-right) with live progress; results land on refresh.
  redirect_to return_path
end

#calendarObject



211
212
213
# File 'app/controllers/crm/posts_controller.rb', line 211

def calendar
  @event = Event.new
end

POST /posts/:id/check_links
Queues a background link audit and redirects to job status page.



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'app/controllers/crm/posts_controller.rb', line 425

def check_links
  authorize!(:update, @post)

  html = active_html_for(@post)
  if html.blank?
    flash[:info] = 'Post has no content to check.'
    redirect_to post_path(@post, anchor: 'internal-links') and return
  end

  return_path = post_path(@post, anchor: 'internal-links')
  job_id = ArticleLinkCheckerWorker.perform_async(
    'article_ids' => [@post.id],
    'skip_external' => true,
    'return_path' => return_path
  )

  redirect_to job_path(job_id)
end

#cloneObject



124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'app/controllers/crm/posts_controller.rb', line 124

def clone
  @old_post = Post.find(params[:id])
  authorize!(:create, @post)
  @post = @old_post.deep_dup
  @post.published_at = nil
  if @post.save
    flash[:info] = 'Post was successfully cloned.'
    redirect_to edit_post_path(@post.id)
  else
    flash[:error] = "Error cloning post: #{@post.errors_to_s}"
    redirect_to post_path(@old_post.id)
  end
end

#createObject



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'app/controllers/crm/posts_controller.rb', line 138

def create
  @post = Post.new((params[:post] || {}).merge(params[:blog_post] || {}).merge(params[:article_post] || {}))
  @post.creator_id ||= current_user.id
  @post.user_id = @post.creator_id

  if @post.save # and @post.save
    respond_to do |format|
      format.html do
        flash[:info] = 'Blog post was successfully created.'
        redirect_to post_path(@post.id)
      end
      format.turbo_stream # Renders create.turbo_stream.erb which calls Turbo.visit() to edit page
    end
  else
    setup_image_template
    respond_to do |format|
      format.html { render :new, status: :unprocessable_content }
      format.turbo_stream { render :new, status: :unprocessable_content } # Re-render form with inline validation errors
    end
  end
end

#destroyObject



204
205
206
207
208
209
# File 'app/controllers/crm/posts_controller.rb', line 204

def destroy
  authorize!(:destroy, @post)
  flash[:info] = "Post #{@post.id} destroyed"
  @post.destroy
  redirect_to url_for(action: :index)
end

#draftsObject

GET /posts/drafts — target of the blog admin bar's "Edit Drafts" link
(drafts_posts_path). There is no dedicated drafts view; reuse the
index pre-filtered to draft posts, matching the state_eq links the
stats cards already use. The route existed without a matching action,
so the link 500'd with AbstractController::ActionNotFound (#5590).



63
64
65
# File 'app/controllers/crm/posts_controller.rb', line 63

def drafts
  redirect_to posts_path(q: { state_eq: 'draft' }, anchor: 'results')
end

#editObject



119
120
121
122
# File 'app/controllers/crm/posts_controller.rb', line 119

def edit
  setup_image_template
  authorize!(:update, @post)
end

#extract_schemaObject



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'app/controllers/crm/posts_controller.rb', line 302

def extract_schema
  authorize!(:update, Post)

  if @post.present?
    # Extract schema for the current post
    options = { return_path: post_path(@post.id) }
    job_id = BlogSchemaExtractionWorker.perform_async(@post.id, options)
    flash[:info] = "Schema extraction queued for post: #{@post.subject}"
    redirect_to job_path(job_id)
  elsif params[:article_id].present?
    # Extract schemas from a specific article
    job_id = BlogSchemaExtractionWorker.perform_async(params[:article_id].to_i)
    flash[:info] = "Schema extraction queued for article #{params[:article_id]}"
    redirect_to job_path(job_id)
  else
    # No batch processing - redirect back to posts index
    flash[:warning] = 'Please select a specific post to extract schema from'
    redirect_to posts_path
  end
end

POST /posts/:id/fix_link
Replaces a broken internal link href with a corrected path



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'app/controllers/crm/posts_controller.rb', line 368

def fix_link
  authorize!(:update, @post)

  broken_href = params[:broken_href].to_s
  replacement_path = params[:replacement_path].to_s.strip
  if broken_href.blank? || replacement_path.blank?
    flash[:error] = 'Both the broken link and replacement path are required.'
    redirect_to post_path(@post, anchor: 'internal-links') and return
  end

  html = active_html_for(@post)
  if html.blank?
    flash[:error] = 'Post has no content to fix.'
    redirect_to post_path(@post, anchor: 'internal-links') and return
  end

  new_href = "https://www.warmlyyours.com/{{locale}}#{replacement_path}"
  doc = Nokogiri::HTML::DocumentFragment.parse(html)
  locale_normalizer = ->(s) { s.gsub(/%7B%7B[%20\s]*locale[%20\s]*%7D%7D/i, '{{locale}}').gsub(/\{\{[%20\s]*locale[%20\s]*\}\}/, '{{locale}}') }
  resolved_broken = locale_normalizer.call(broken_href).gsub(/\{\{\s*locale\s*\}\}/, 'en-US')
  replaced = 0

  doc.css('a[href]').each do |link|
    link_href = locale_normalizer.call(link['href'].to_s).gsub(/\{\{\s*locale\s*\}\}/, 'en-US')
    next unless link_href == resolved_broken

    link['href'] = new_href
    replaced += 1
  end

  if replaced.zero?
    flash[:warning] = 'Link not found in post content. It may have already been fixed.'
    redirect_to post_path(@post, anchor: 'internal-links') and return
  end

  new_html = doc.to_html
  @post.solution = new_html
  @post.auto_sanitize_urls = true
  @post.updater_id = current_user.id
  @post.revision_change_notes = "Fixed broken link: #{broken_href.truncate(60)}"
  @post.save!

  begin
    Seo::InternalLinkValidator.upsert_editorial_links!(@post)
  rescue StandardError
    nil
  end

  # Re-run audit in background so the cached broken links reflect the fix
  ArticleLinkCheckerWorker.perform_async('article_ids' => [@post.id], 'skip_external' => true)

  flash[:success] = "Fixed #{replaced} link occurrence(s): #{broken_href.truncate(50)}#{replacement_path}"
  redirect_to post_path(@post, anchor: 'internal-links')
end

#flush_all_cacheObject



293
294
295
296
297
298
299
300
# File 'app/controllers/crm/posts_controller.rb', line 293

def flush_all_cache
  authorize!(:update, Post)
  all_posts = Post.published
  all_posts.touch_all
  # Use tag-based purging instead of URL-based purging for better performance
  Post.purge_all_posts_by_tag
  redirect_to url_for(action: :index), notice: 'Cache refreshed for all posts using tag-based purging, this can take a couple minutes'
end

#flush_cacheObject



286
287
288
289
290
291
# File 'app/controllers/crm/posts_controller.rb', line 286

def flush_cache
  authorize!(:update, Post)
  @post.touch
  @post.purge_edge_cache
  redirect_to(@post, notice: 'Cache purge has been queued, this can take a couple minutes')
end

#indexObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/controllers/crm/posts_controller.rb', line 11

def index
  @search_mode = params[:search_mode].presence || 'keyword'
  @search_query = params[:search_query].to_s.strip

  # Direct ID lookup: redirect straight to the post (HTML) or show in results (Turbo Frame)
  if @search_query.match?(/\A\d+\z/)
    post = Post.find_by(id: @search_query.to_i)
    if post
      return redirect_to post_path(post) unless turbo_frame_request?
    end
  end

  @q = Post.with_comments_count.ransack(params[:q])
  @q.sorts = 'updated_at DESC' if @q.sorts.blank?
  @available_schema_types = Article.available_schema_types

  # Apply search based on mode
  base_scope = @q.result
  @posts = apply_search_mode(base_scope, @search_mode, @search_query)

  # Stats for Blogs with Video card
  @total_posts = Post.count
  @posts_with_video = Post.has_video('true').count
  @posts_with_video_percentage = percentage_of(@posts_with_video, @total_posts)

  # Other stats to render with the same component
  @published_posts = Post.published.count
  @scheduled_posts = Post.waiting_to_publish.count
  @no_schema_published = Post.published.no_schema.count
  @with_schema_published = Post.published.has_schema('true').count
  @with_comments_posts = Post.published.joins(:post_comments).distinct.count
  @draft_posts = Post.drafts.count
  @archived_posts = Post.archived.count

  @published_percentage = percentage_of(@published_posts, @total_posts)
  @scheduled_percentage = percentage_of(@scheduled_posts, @total_posts)
  @no_schema_percentage = percentage_of(@no_schema_published, @total_posts)
  @with_schema_percentage = percentage_of(@with_schema_published, @total_posts)
  @with_comments_percentage = percentage_of(@with_comments_posts, @total_posts)
  @draft_percentage = percentage_of(@draft_posts, @total_posts)
  @archived_percentage = percentage_of(@archived_posts, @total_posts)

  respond_to do |format|
    format.html
  end
end

GET /posts/:id/internal_links
Lazy-loaded turbo frame for the Internal Links tab content.



355
356
357
358
359
360
361
362
363
364
# File 'app/controllers/crm/posts_controller.rb', line 355

def internal_links
  load_internal_links_data
  render partial: 'internal_links_tab',
         locals: { post: @post,
                   outbound_links: @outbound_links,
                   inbound_links: @inbound_links,
                   broken_links: @broken_links,
                   post_site_map: @post_site_map,
                   last_audit_at: @last_audit_at }
end

#keyword_researchObject

GET /posts/:id/keyword_research
Returns keyword suggestions via Turbo Frame



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'app/controllers/crm/posts_controller.rb', line 230

def keyword_research
  load_post unless @post
  authorize! :read, @post

  # Extract main topic from post subject
  topic = extract_topic(@post.subject)

  begin
    client = Seo::KeywordsPeopleUseClient.new
    @keyword_result = client.keyword_generator(topic)
    @paa_result = client.people_also_ask(topic)
  rescue Seo::KeywordsPeopleUseClient::AuthenticationError => e
    @error = "API authentication failed: #{e.message}"
  rescue StandardError => e
    @error = "Failed to fetch keywords: #{e.message}"
    Rails.logger.error "[PostsController#keyword_research] #{e.class}: #{e.message}"
  end

  respond_to do |format|
    format.turbo_stream
    format.html { render partial: 'keyword_research_results', locals: { post: @post } }
  end
end

#lookupObject

GET /posts/lookup



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'app/controllers/crm/posts_controller.rb', line 68

def lookup
  term = params[:q].to_s.strip
  per_page = params[:per_page].to_i
  per_page = 20 if per_page < 1 || per_page > 100

  scope = Post.published.where.not(id: params[:exclude_id])

  if term.present?
    ilike = "%#{ActiveRecord::Base.sanitize_sql_like(term)}%"
    scope = scope.where('LOWER(subject) LIKE LOWER(?) OR LOWER(slug) LIKE LOWER(?)', ilike, ilike)
  end

  # Order by subject alphabetically (matching related_articles_for_select), with relevance boost for searches
  scope = if term.present?
            # Sanitize the search term for LIKE comparison
            search_prefix = "#{ActiveRecord::Base.sanitize_sql_like(term)}%"
            scope.order(Arel.sql(ActiveRecord::Base.sanitize_sql_array(['CASE WHEN LOWER(subject) LIKE LOWER(?) THEN 0 ELSE 1 END, subject', search_prefix])))
          else
            scope.order(:subject)
          end

  # Use Pagy for pagination
  @pagy, paginated_scope = pagy(scope, limit: per_page)

  # Pluck data matching the format from related_articles_for_select: "Subject (YYYY-MM-DD) - ID"
  results = paginated_scope.pluck(:id, Arel.sql("articles.subject || ' (' || TO_CHAR(articles.updated_at, 'YYYY-MM-DD') || ') - ' || articles.id::varchar"))

  render json: {
    results: results.map { |id, display_text| { id: id, text: display_text } },
    has_more: @pagy.next.present?,
    page: @pagy.page
  }
end

#newObject



113
114
115
116
117
# File 'app/controllers/crm/posts_controller.rb', line 113

def new
  setup_image_template
  @post = Post.new(original_author_id: current_user.id)
  authorize!(:create, @post)
end

#previewObject



215
216
217
218
219
220
221
# File 'app/controllers/crm/posts_controller.rb', line 215

def preview
  @preview_mode = true
  # Generate JWT token for secure preview access
  token = BlogPreviewTokenService.generate_token(@post.id, current_user&.id)
  preview_url = "#{WEB_URL}#{preview_post_path(@post, token: token)}"
  redirect_to preview_url, allow_other_host: true
end

#refresh_oembedObject

POST /posts/:id/refresh_oembed
Re-renders all oEmbed content (FAQs, products, videos, images) in the post body



446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
# File 'app/controllers/crm/posts_controller.rb', line 446

def refresh_oembed
  authorize!(:update, Post)

  service = Oembed::ContentRefreshService.new
  updated = service.refresh_post(@post)
  result = service.instance_variable_get(:@stats)

  if updated
    parts = []
    parts << "#{result[:faqs_refreshed]} FAQs" if result[:faqs_refreshed].to_i > 0
    parts << "#{result[:products_refreshed]} products" if result[:products_refreshed].to_i > 0
    parts << "#{result[:videos_refreshed]} videos" if result[:videos_refreshed].to_i > 0
    parts << "#{result[:images_refreshed]} images" if result[:images_refreshed].to_i > 0
    flash[:success] = "oEmbed content refreshed: #{parts.any? ? parts.join(', ') : 'content updated'}."
  else
    flash[:info] = 'No oEmbed changes detected — content is already up to date.'
  end

  flash[:warning] = "#{result[:errors].size} error(s): #{result[:errors].first(3).join('; ')}" if result[:errors].any?

  redirect_to post_path(@post, anchor: 'linked-assets')
end

#retrieve_sku_infoObject



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'app/controllers/crm/posts_controller.rb', line 254

def retrieve_sku_info
  sku = params[:sku]
  item = Item.find_by(sku: sku)
  ic = CatalogItem.by_skus(sku).main_catalogs
  item_catalog_usa = ic.where(catalog_id: 1).first
  item_catalog_ca = ic.where(catalog_id: 2).first
  product_review = ReviewsIo.fetch_reviews(sku: sku, page: 1, limit: 5)
  rating = Rating.new(product_review, item)

  price_usa = if item_catalog_usa.sale_price_in_effect?
                item_catalog_usa.sale_price
              else
                item_catalog_usa.bom_price
              end

  price_ca = if item_catalog_ca.sale_price_in_effect?
               item_catalog_ca.sale_price
             else
               item_catalog_ca.bom_price
             end

  respond_to do |format|
    format.json do
      render json: { sku: sku,
                     product_name: item_catalog_usa.name,
                     price_usa: price_usa,
                     price_ca: price_ca,
                     reviews: rating.review_count }
    end
  end
end

#send_by_emailObject



223
224
225
226
# File 'app/controllers/crm/posts_controller.rb', line 223

def send_by_email
  # @post = Article.find(params[:id].split("-")[0])
  redirect_to new_communication_path(resource_id: @post.id, resource_type: 'article')
end

#showObject



102
103
104
105
106
107
108
109
110
111
# File 'app/controllers/crm/posts_controller.rb', line 102

def show
  @article = @post
  respond_to do |format|
    format.html
    format.pdf do
      result = Pdf::Document::Article.call(@post)
      send_data result.pdf, filename: result.file_name, type: 'application/pdf', disposition: 'inline'
    end
  end
end

#updateObject



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'app/controllers/crm/posts_controller.rb', line 160

def update
  authorize!(:update, @post)
  state_event = post_params[:state_event]

  filtered = post_params.except(:state_event).reject do |key, value|
    %w[published_at revised_at publish_on].include?(key.to_s) && value.blank?
  end
  @post.assign_attributes(filtered)
  @post.updater_id = current_user.id
  saved = @post.save

  # Handle state transitions (archive, publish, etc.) - these save automatically with bang methods
  if saved && state_event.present? && @post.send("can_#{state_event}?")
    begin
      @post.send("#{state_event}!")
    rescue StateMachines::InvalidTransition => e
      @post.errors.add(:base, e.message)
      saved = false
    end
  end

  if saved
    # Backfill any missing data-embedded-asset-uuid attributes synchronously so
    # the form re-renders with UUID-annotated HTML. The service is idempotent —
    # fast no-op when all UUIDs are already present.
    Posts::EmbeddedAssetSyncService.new(@post).call
    @post.reload # picks up UUID-annotated solution + clears cached errors
    flash[:info] = 'Post saved successfully.'
    respond_to do |format|
      format.html { redirect_to post_path(@post.id) }
      format.turbo_stream do
        setup_image_template
        # Renders update.turbo_stream.erb - flash will be appended by TurboStreamFlashable
      end
    end
  else
    setup_image_template
    respond_to do |format|
      format.html { render :edit, status: :unprocessable_content }
      format.turbo_stream { render :edit, status: :unprocessable_content } # Re-render form with inline validation errors
    end
  end
end