Class: Collavre::CreativesController
- Inherits:
-
ApplicationController
- Object
- ApplicationController
- ApplicationController
- Collavre::CreativesController
- Includes:
- Collavre::Concerns::Exportable, Collavre::Concerns::Shareable, Collavre::Concerns::SlideViewable, Collavre::Concerns::TreeManageable, CreativePermissionGuard
- Defined in:
- app/controllers/collavre/creatives_controller.rb
Instance Method Summary collapse
- #archive ⇒ Object
- #contexts ⇒ Object
- #create ⇒ Object
- #destroy ⇒ Object
- #edit ⇒ Object
- #index ⇒ Object
- #new ⇒ Object
- #parent_suggestions ⇒ Object
- #show ⇒ Object
- #trigger_action ⇒ Object
- #unarchive ⇒ Object
- #update ⇒ Object
- #update_contexts ⇒ Object
- #update_metadata ⇒ Object
Methods included from Collavre::Concerns::Shareable
Methods included from Collavre::Concerns::TreeManageable
#append_as_parent, #append_below, #children, #link_drop, #reorder, #unconvert
Methods included from Collavre::Concerns::Exportable
Methods included from Collavre::Concerns::SlideViewable
Instance Method Details
#archive ⇒ Object
501 502 503 504 |
# File 'app/controllers/collavre/creatives_controller.rb', line 501 def archive @creative.archive! head :ok end |
#contexts ⇒ Object
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'app/controllers/collavre/creatives_controller.rb', line 314 def contexts unless @creative.(Current.user, :read) render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden and return end creative = @creative.effective_origin(Set.new) own_ids = creative.context_ids - [ creative.id ] inherited_ids = (creative.effective_context_ids - own_ids - [ creative.id ]).uniq own_creatives = Creative.where(id: own_ids).index_by(&:id) inherited_creatives = Creative.where(id: inherited_ids).index_by(&:id) disabled_ids = creative.effective_disabled_context_ids own = own_ids.filter_map do |cid| c = own_creatives[cid] next unless c { id: c.id, description: c.creative_snippet, inherited: false, disabled: disabled_ids.include?(cid) } end inherited = inherited_ids.filter_map do |cid| c = inherited_creatives[cid] next unless c { id: c.id, description: c.creative_snippet, inherited: true, disabled: disabled_ids.include?(cid) } end render json: { contexts: inherited + own, can_manage: creative.(Current.user, :admin), disabled_self_context: creative.data&.dig("disabled_self_context") == true } end |
#create ⇒ Object
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
# File 'app/controllers/collavre/creatives_controller.rb', line 192 def create result = Creatives::CreateService.new( creative_params: creative_params, user: Current.user, child_id: params[:child_id], before_id: params[:before_id], after_id: params[:after_id], tag_ids: params[:tags] ).call @creative = result.creative if result.success? # Expose the post-rewrite markdown source so the client can sync its # textarea after the server replaces inline data: URIs with blob paths, # matching the update endpoint contract. Without this, a freshly created # markdown creative with a pasted data: URI would re-import the blob on # the next keystroke save. render json: { id: @creative.id, content_type: @creative.data&.dig("content_type"), markdown_source: @creative.data&.dig("markdown_source") } else render json: { errors: result.errors }, status: :unprocessable_entity end end |
#destroy ⇒ Object
511 512 513 514 515 516 517 518 519 520 521 |
# File 'app/controllers/collavre/creatives_controller.rb', line 511 def destroy parent = @creative.parent unless @creative.(Current.user, :admin) redirect_to @creative, alert: t("collavre.creatives.errors.no_permission") and return end Creatives::DestroyService.new( creative: @creative, user: Current.user, delete_with_children: params[:delete_with_children].present? ).call end |
#edit ⇒ Object
229 230 231 232 233 234 235 236 |
# File 'app/controllers/collavre/creatives_controller.rb', line 229 def edit unless @creative.(Current.user, :write) redirect_to @creative, alert: t("collavre.creatives.errors.no_permission") and return end if params[:inline] render partial: "inline_edit_form" end end |
#index ⇒ Object
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'app/controllers/collavre/creatives_controller.rb', line 16 def index respond_to do |format| format.html do # HTML only needs parent_creative for nav/title - skip expensive filtered queries # Must check permission to avoid leaking metadata (og:title, etc.) to unauthorized users if params[:id].present? creative = Creative.find_by(id: params[:id]) @parent_creative = creative if creative&.(Current.user, :read) end @creatives = [] # CSR will fetch via JSON @shared_list = @parent_creative ? @parent_creative.all_shared_users : [] end format.json do # Full query only for JSON requests user_id_for_state = Current.user&.id if user_id_for_state.nil? && params[:id].present? # Public view: use owner's state target_creative = Creative.find_by(id: params[:id]) user_id_for_state = target_creative&.effective_origin&.user_id end @expanded_state_map = if user_id_for_state UserCreativePreference.where(user_id: user_id_for_state, creative_id: params[:id]).first&. || {} else {} end index_result = ::Creatives::IndexQuery.new(user: Current.user, params: params.to_unsafe_h).call @creatives = index_result.creatives || [] @parent_creative = index_result.parent_creative @shared_creative = index_result.shared_creative @shared_list = index_result.shared_list @overall_progress = index_result.overall_progress if any_filter_active? @allowed_creative_ids = index_result.allowed_creative_ids @progress_map = index_result.progress_map # Set filtered_progress on parent creative if progress_map is available if @parent_creative && @progress_map && @progress_map.key?(@parent_creative.id.to_s) @parent_creative.filtered_progress = @progress_map[@parent_creative.id.to_s] end # Disable caching for filtered results to ensure fresh data expires_now if any_filter_active? if params[:simple].present? render json: serialize_creatives(@creatives) else @creatives_tree_json = build_tree( index_result.creatives, params: params, expanded_state_map: @expanded_state_map, level: 1, allowed_creative_ids: @allowed_creative_ids, progress_map: @progress_map ) render json: { creatives: @creatives_tree_json } end end end end |
#new ⇒ Object
178 179 180 181 182 183 184 185 186 187 188 189 190 |
# File 'app/controllers/collavre/creatives_controller.rb', line 178 def new @creative = Creative.new if params[:parent_id].present? @parent_creative = Creative.find_by(id: params[:parent_id]) @creative.parent = @parent_creative if @parent_creative end if params[:child_id].present? @child_creative = Creative.find_by(id: params[:child_id]) end if params[:after_id].present? @after_creative = Creative.find_by(id: params[:after_id]) end end |
#parent_suggestions ⇒ Object
220 221 222 223 224 225 226 227 |
# File 'app/controllers/collavre/creatives_controller.rb', line 220 def parent_suggestions unless @creative.(Current.user, :read) render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden and return end suggestions = ::GeminiParentRecommender.new.recommend(@creative) render json: suggestions end |
#show ⇒ Object
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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# File 'app/controllers/collavre/creatives_controller.rb', line 76 def show unless @creative.(Current.user, :read) if Current.user redirect_to creatives_path, alert: t("collavre.creatives.errors.no_permission") else request_authentication end return end respond_to do |format| = { id: @creative.id } [:comment_id] = params[:comment_id] if params[:comment_id].present? format.html { redirect_to creatives_path() } format.json do # Use HTTP caching with ETag - must vary by user since response includes user-specific data # ETag must also include prompt comment and children timestamps since those are in response effective = @creative.effective_origin cache_user = Current.user&.id || "anon" # Include prompt comment timestamp (user-specific private comments starting with "> ") # Note: LIKE '> %' uses index prefix scan if available; consider dedicated prompt flag if bottleneck prompt_updated = if Current.user @creative.comments .where(private: true, user: Current.user) .where("content LIKE ?", "> %") .maximum(:updated_at) end # Get children stats in a single query, reuse for has_children # Use separate Arel.sql args so pick returns an array; unscope order to avoid Postgres aggregate error children_count, children_max_updated = @creative.children .unscope(:order) .pick(Arel.sql("COUNT(*)"), Arel.sql("MAX(updated_at)")) children_count = children_count.to_i # Handle nil and string type-casting from adapters children_key = "#{children_count}-#{children_max_updated&.to_i}" last_modified = [ @creative.updated_at, effective.updated_at, prompt_updated ].compact.max trigger_loop_data = @creative.data&.dig("trigger", "loop") parent_trigger_enabled = @creative.parent&.drop_trigger_enabled? || false can_edit = @creative.(Current.user, :write) etag = [ "creative", @creative.cache_key_with_version, effective.cache_key_with_version, "user", cache_user, "prompt", prompt_updated&.to_i, "children", children_key, "trigger_v3", trigger_loop_data&.dig("state"), trigger_loop_data&.dig("current_iteration"), parent_trigger_enabled, "can_edit", can_edit ].join(":") if stale?(etag: etag, last_modified: last_modified, public: false) root = params[:root_id] ? Creative.find_by(id: params[:root_id]) : nil depth = if root (@creative.ancestors.count - root.ancestors.count) + 1 else @creative.ancestors.count + 1 end sanitized_data = @creative.effective_origin(Set.new).data # markdown_source is exposed via the top-level `markdown_source:` field for writers; # exclude it from the editable `data` payload so the metadata YAML editor can't # round-trip a stale copy back into data["markdown_source"] on update_metadata. if sanitized_data.is_a?(Hash) && sanitized_data.key?("markdown_source") sanitized_data = sanitized_data.except("markdown_source") end render json: { id: @creative.id, description: @creative.effective_description, description_raw_html: @creative.description, origin_id: @creative.origin_id, parent_id: @creative.parent_id, progress: @creative.progress, progress_html: view_context.render_creative_progress(@creative), depth: depth, prompt: @creative.prompt_for(Current.user), has_children: children_count > 0, data: sanitized_data, content_type: effective.data&.dig("content_type"), markdown_source: can_edit ? effective.data&.dig("markdown_source") : nil, trigger_loop: trigger_loop_data, is_trigger_task: parent_trigger_enabled, can_edit: can_edit } end end end end |
#trigger_action ⇒ Object
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
# File 'app/controllers/collavre/creatives_controller.rb', line 416 def trigger_action action = params[:action_name] || (request.content_type&.include?("json") ? request.request_parameters["action"] : params[:action]) case action when "toggle_container" # Container toggle operates on effective_origin (where trigger config lives) creative = @creative.effective_origin(Set.new) unless creative.(Current.user, :write) render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden return end enabled = ActiveModel::Type::Boolean.new.cast( request.content_type&.include?("json") ? request.request_parameters["enabled"] : params[:enabled] ) data = creative.data || {} trigger = data["trigger"] || {} trigger["on_child_enter"] = enabled data["trigger"] = trigger previous_enabled = creative.drop_trigger_enabled? creative.update!(data: data) notify_drop_trigger_missing_agent!(creative) if !previous_enabled && creative.drop_trigger_enabled? when "start" # Start trigger: fires DropTriggerJob as if the child was just dropped into the container creative = @creative unless creative.(Current.user, :write) render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden return end parent = creative.parent unless parent&.drop_trigger_enabled? render json: { error: t("collavre.drop_trigger.not_a_container") }, status: :unprocessable_entity return end DropTriggerJob.perform_later(parent.id, creative.id) when "pause", "resume", "restart" # Loop actions operate on the creative itself (where loop state lives) creative = @creative unless creative.(Current.user, :write) render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden return end data = creative.data || {} trigger = data["trigger"] || {} loop_data = trigger["loop"] case action when "pause" if loop_data && %w[running pending_verification].include?(loop_data["state"]) loop_data["state"] = "paused" trigger["loop"] = loop_data data["trigger"] = trigger creative.update!(data: data) end when "resume" if loop_data && %w[paused idle stuck awaiting_user].include?(loop_data["state"]) loop_data["state"] = "running" trigger["loop"] = loop_data data["trigger"] = trigger creative.update!(data: data) post_continue_to_agent(creative, loop_data) end when "restart" if loop_data && %w[completed max_reached stuck].include?(loop_data["state"]) loop_data["state"] = "running" loop_data["current_iteration"] = 0 loop_data["infra_retry_count"] = 0 trigger["loop"] = loop_data data["trigger"] = trigger creative.update!(data: data) post_restart_trigger(creative) end end else render json: { error: "Unknown action" }, status: :unprocessable_entity return end head :ok end |
#unarchive ⇒ Object
506 507 508 509 |
# File 'app/controllers/collavre/creatives_controller.rb', line 506 def unarchive @creative.unarchive! head :ok end |
#update ⇒ Object
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
# File 'app/controllers/collavre/creatives_controller.rb', line 238 def update respond_to do |format| permitted = creative_params.to_h base = @creative.effective_origin(Set.new) success = true previous_progress = base.progress requested_progress = permitted["progress"] || permitted[:progress] # Require write permission for origin content changes (description, progress, sequence) origin_changes = permitted.except("parent_id") if origin_changes.any? && !@creative.(Current.user, :write) format.html { redirect_to @creative, alert: t("collavre.creatives.errors.no_permission") } format.json { render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden } next end # Handle parent_id change separately for Linked Creatives if @creative.origin_id.present? && permitted.key?("parent_id") parent_id = permitted.delete("parent_id") success &&= @creative.update(parent_id: parent_id) end # When updating the base (Origin), we must NOT pass origin_id. # Because if @creative is Linked, params might include origin_id. # Passing origin_id to the Origin creative causes it to fail validation (cannot changes if has origin) # or creates a self-cycle. permitted.delete("origin_id") permitted.delete(:origin_id) success &&= base.update(permitted) if success && requested_progress.present? && requested_progress.to_f >= 1 && previous_progress.to_f < 1 if base.children.exists? base.self_and_descendants.where(origin_id: nil) .update_all(progress: 1.0, updated_at: Time.current) end end if success format.html { redirect_to @creative } format.json do base.reload response_data = { id: base.id, progress: base.progress, progress_html: view_context.render_creative_progress(base), has_children: base.children.exists?, content_type: base.data&.dig("content_type") } # Expose the post-rewrite markdown source so the client can sync its # textarea after the server replaces inline data: URIs with blob paths. # Gated on write permission so a read-only share recipient moving a # linked creative (parent_id-only PATCH bypasses the origin_changes # write check) cannot read the origin's raw Markdown source. if @creative.(Current.user, :write) response_data[:markdown_source] = base.data&.dig("markdown_source") end # Build ancestor chain for progress updates (closure_tree: 1 SELECT via hierarchy table) ancestor_records = base.ancestors.order(:id) if ancestor_records.any? response_data[:ancestors] = ancestor_records.map do |anc| { id: anc.id, progress: anc.progress, progress_html: view_context.render_creative_progress(anc, has_children: true) } end end render json: response_data end else format.html { render :edit, status: :unprocessable_entity } format.json { render json: { errors: @creative.errors. }, status: :unprocessable_entity } end end end |
#update_contexts ⇒ Object
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
# File 'app/controllers/collavre/creatives_controller.rb', line 348 def update_contexts creative = @creative.effective_origin(Set.new) unless creative.(Current.user, :admin) render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden return end current_data = (creative.data || {}).dup current_data["context_ids"] = Array(params[:context_ids]).map(&:to_i) if params.key?(:context_ids) if params.key?(:disabled_context_ids) requested_disabled = Array(params[:disabled_context_ids]).map(&:to_i) parent_disabled = creative.parent&.effective_disabled_context_ids || [] inherited_only = parent_disabled - creative.disabled_context_ids current_data["disabled_context_ids"] = requested_disabled - inherited_only current_data.delete("disabled_context_ids") if current_data["disabled_context_ids"].empty? end if params.key?(:disabled_self_context) if ActiveModel::Type::Boolean.new.cast(params[:disabled_self_context]) current_data["disabled_self_context"] = true else current_data.delete("disabled_self_context") end end if creative.update(data: current_data) head :ok else render json: { errors: creative.errors. }, status: :unprocessable_entity end end |
#update_metadata ⇒ Object
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 |
# File 'app/controllers/collavre/creatives_controller.rb', line 379 def creative = @creative.effective_origin(Set.new) unless creative.(Current.user, :write) render json: { error: t("collavre.creatives.errors.no_permission") }, status: :forbidden return end new_data = begin JSON.parse(params[:data]) rescue JSON::ParserError => e render json: { error: "Invalid JSON: #{e.}" }, status: :unprocessable_entity return end unless new_data.is_a?(Hash) render json: { error: t("collavre.creatives.errors.metadata_must_be_object") }, status: :unprocessable_entity return end # Reserved markdown fields are not editable via metadata; preserve current values so a stale # YAML payload from the metadata popup can't overwrite a concurrent markdown edit. current_data = creative.data || {} %w[markdown_source content_type].each do |key| if current_data.key?(key) new_data[key] = current_data[key] else new_data.delete(key) end end previous_enabled = creative.drop_trigger_enabled? if creative.update(data: new_data) notify_drop_trigger_missing_agent!(creative) if !previous_enabled && creative.drop_trigger_enabled? head :ok else render json: { errors: creative.errors. }, status: :unprocessable_entity end end |