Class: Collavre::Tools::CreativeCreateService

Inherits:
Object
  • Object
show all
Extended by:
T::Sig, ToolMeta
Defined in:
app/services/collavre/tools/creative_create_service.rb

Instance Method Summary collapse

Instance Method Details

#call(description:, parent_id: nil, progress: nil, after_id: nil, before_id: nil) ⇒ Object



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
# File 'app/services/collavre/tools/creative_create_service.rb', line 19

def call(description:, parent_id: nil, progress: nil, after_id: nil, before_id: nil)
  raise "Current.user is required" unless Current.user

  # Validate parent permission if specified
  parent = nil
  if parent_id.present?
    parent = Creative.find_by(id: parent_id)
    unless parent
      return { error: "Parent Creative not found", id: parent_id }
    end
    unless parent.has_permission?(Current.user, :write)
      return { error: "No write permission on parent Creative", id: parent_id }
    end
  end

  # Build the creative. The description is authored as Markdown: store it as
  # the canonical markdown_source and let Describable#convert_markdown_to_html
  # render it to the HTML description (markdown_editor defaults to the
  # advanced "source" surface for tool/MCP writes).
  creative = Creative.new(
    parent: parent,
    progress: progress || 0
  )
  creative.content_type_input = "markdown"
  creative.markdown_source = description

  # Set user based on parent or current user
  creative.user = parent ? parent.user : Current.user

  unless creative.save
    return { error: "Failed to create Creative", details: creative.errors.full_messages }
  end

  # Handle ordering
  handle_ordering(creative, before_id: before_id, after_id: after_id)

  # Broadcast after ordering so sequence and previous_sibling are correct
  creative.reload
  creative.broadcast_creative_created(after_id: after_id)

  {
    success: true,
    id: creative.id,
    description: creative.description,
    parent_id: creative.parent_id,
    progress: creative.progress
  }
end