checklist_templates_controller.rb 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class ChecklistTemplatesController < ApplicationController
  3. prepend_before_action :authenticate_and_authorize!
  4. def index
  5. model_index_render(ChecklistTemplate, params)
  6. end
  7. def show
  8. model_show_render(ChecklistTemplate, params)
  9. end
  10. def create
  11. items = params[:items].presence || []
  12. ChecklistTemplate.create!(
  13. name: params[:name],
  14. active: params[:active],
  15. ).tap do |cl|
  16. create_and_sort_checklist_template_items(cl, items)
  17. render json: cl.attributes_with_association_ids, status: :created
  18. end
  19. end
  20. def update
  21. checklist_template = ChecklistTemplate.find(params[:id])
  22. items = params[:items].presence || []
  23. checklist_template.update!(
  24. name: params[:name],
  25. active: params[:active],
  26. )
  27. create_and_sort_checklist_template_items(checklist_template, items)
  28. render json: checklist_template.attributes_with_association_ids, status: :ok
  29. end
  30. def destroy
  31. model_destroy_render(ChecklistTemplate, params)
  32. end
  33. private
  34. def create_and_sort_checklist_template_items(checklist_template, items)
  35. return if items.blank?
  36. checklist_template.items.destroy_all if checklist_template.items.present?
  37. checklist_template.sorted_item_ids = []
  38. items.compact_blank.each { |text| ChecklistTemplate::Item.create!(text: text.strip, checklist_template:) }
  39. end
  40. end