Class: Collavre::Tools::CreativeCreateService

Inherits:
Object
  • Object
show all
Extended by:
T::Sig, ToolMeta
Includes:
DescriptionNormalizable
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



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 20

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

  # Normalize description - wrap plain text in <p> tags if needed
  normalized_description = normalize_description(description)

  # Build the creative
  creative = Creative.new(
    description: normalized_description,
    parent: parent,
    progress: progress || 0
  )

  # 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