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

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, #touch_employee_last_seen

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?, #skip_layout_for_turbo_frame?, #stamp_impersonation_context, #tab_frame_breakout_request?, #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, #registration_lead_type, #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 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?

Instance Method Details

#analyze_seoObject

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



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'app/controllers/crm/posts_controller.rb', line 343

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

Renders the blog content calendar's new-event form.



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

def calendar
  @event = Event.new
end

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



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'app/controllers/crm/posts_controller.rb', line 443

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_or_fallback(job_id, return_path)
end

#cloneObject

Duplicates an existing post as an unpublished draft.



130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'app/controllers/crm/posts_controller.rb', line 130

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

Creates a post from the submitted post/blog_post/article_post params.



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'app/controllers/crm/posts_controller.rb', line 145

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

Destroys the post.



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

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).



65
66
67
# File 'app/controllers/crm/posts_controller.rb', line 65

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

#editObject

Renders the form to edit an existing post.



124
125
126
127
# File 'app/controllers/crm/posts_controller.rb', line 124

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

#extract_schemaObject

Enqueues schema.org extraction, for the loaded post, a specific article id,
or (if neither is present) redirects back to pick one.



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'app/controllers/crm/posts_controller.rb', line 320

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)
    redirect_to_job_or_fallback(job_id, post_path(@post.id),
                                notice: "Schema extraction queued for post: #{@post.subject}")
  elsif params[:article_id].present?
    # Extract schemas from a specific article
    job_id = BlogSchemaExtractionWorker.perform_async(params[:article_id].to_i)
    redirect_to_job_or_fallback(job_id, posts_path,
                                notice: "Schema extraction queued for article #{params[:article_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



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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'app/controllers/crm/posts_controller.rb', line 386

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

Purges the edge cache for every published post, via tag-based purging.



309
310
311
312
313
314
315
316
# File 'app/controllers/crm/posts_controller.rb', line 309

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

Purges the post's edge cache.



301
302
303
304
305
306
# File 'app/controllers/crm/posts_controller.rb', line 301

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

Lists posts, ransack-filtered and searched (keyword/AI/hybrid mode), plus
dashboard stats cards.



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
57
58
# File 'app/controllers/crm/posts_controller.rb', line 13

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.



373
374
375
376
377
378
379
380
381
382
# File 'app/controllers/crm/posts_controller.rb', line 373

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



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'app/controllers/crm/posts_controller.rb', line 243

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



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
101
102
# File 'app/controllers/crm/posts_controller.rb', line 70

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

Renders the form for a new post.



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

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

#previewObject

Redirects to the post's front-end preview URL, JWT-token-authorized.



227
228
229
230
231
232
233
# File 'app/controllers/crm/posts_controller.rb', line 227

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



464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'app/controllers/crm/posts_controller.rb', line 464

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

AJAX endpoint: returns pricing/review info for a SKU embedded in post content.



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'app/controllers/crm/posts_controller.rb', line 268

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

Redirects to compose a communication with the post attached.



236
237
238
239
# File 'app/controllers/crm/posts_controller.rb', line 236

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

Shows a post, or streams it as a PDF.



105
106
107
108
109
110
111
112
113
114
# File 'app/controllers/crm/posts_controller.rb', line 105

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

Updates a post from post_params, applying any requested state transition
(publish/archive/etc.) after the attribute save succeeds.



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
203
204
205
206
207
208
209
210
211
# File 'app/controllers/crm/posts_controller.rb', line 169

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