|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +## |
| 4 | +# Job to add a workflow to and object |
| 5 | +class AddWorkflowJob < GenericJob |
| 6 | + attr_reader :workflow_name |
| 7 | + |
| 8 | + # @param [Integer] bulk_action_id GlobalID for a BulkAction object |
| 9 | + # @param [Hash] params additional parameters that an Argo job may need |
| 10 | + # @option params [Array] :pids required list of pids |
| 11 | + # @option params [Hash] :add_workflow required Hash of workflow options |
| 12 | + # @option add_workflow [String] :workflow the name of the workflow to start |
| 13 | + # @option params [Array] :groups the groups the user belonged to when the started the job. Required for permissions check |
| 14 | + def perform(bulk_action_id, params) |
| 15 | + super |
| 16 | + @workflow_name = params.fetch(:add_workflow).fetch(:workflow) |
| 17 | + with_bulk_action_log do |log| |
| 18 | + log.puts("#{Time.current} Starting AddWorkflowJob for BulkAction #{bulk_action_id}") |
| 19 | + update_druid_count |
| 20 | + |
| 21 | + pids.each { |current_druid| start_workflow(current_druid, log) } |
| 22 | + log.puts("#{Time.current} Finished AddWorkflowJob for BulkAction #{bulk_action_id}") |
| 23 | + end |
| 24 | + end |
| 25 | + |
| 26 | + private |
| 27 | + |
| 28 | + def start_workflow(current_druid, log) |
| 29 | + cocina_object = Dor::Services::Client.object(current_druid).find |
| 30 | + |
| 31 | + unless ability.can?(:manage_item, cocina_object) |
| 32 | + bulk_action.increment(:druid_count_fail).save |
| 33 | + log.puts("#{Time.current} Not authorized for #{current_druid}") |
| 34 | + return |
| 35 | + end |
| 36 | + |
| 37 | + # check the workflow is present and active (not archived) |
| 38 | + if workflow_active?(cocina_object.externalIdentifier, cocina_object.version) |
| 39 | + bulk_action.increment(:druid_count_fail).save |
| 40 | + log.puts("#{Time.current} #{workflow_name} already exists for #{current_druid}") |
| 41 | + return |
| 42 | + end |
| 43 | + |
| 44 | + client.create_workflow_by_name(cocina_object.externalIdentifier, |
| 45 | + workflow_name, |
| 46 | + version: cocina_object.version) |
| 47 | + log.puts("#{Time.current} started #{workflow_name} for #{current_druid}") |
| 48 | + |
| 49 | + bulk_action.increment(:druid_count_success).save |
| 50 | + rescue StandardError => e |
| 51 | + log.puts("#{Time.current} Workflow creation failed #{e.class} #{e.message}") |
| 52 | + bulk_action.increment(:druid_count_fail).save |
| 53 | + end |
| 54 | + |
| 55 | + # Fetches the workflow from the workflow service and checks to see if it's active |
| 56 | + def workflow_active?(druid, version) |
| 57 | + workflow = client.workflow(pid: druid, workflow_name: workflow_name) |
| 58 | + workflow.active_for?(version: version) |
| 59 | + end |
| 60 | + |
| 61 | + def client |
| 62 | + @client ||= WorkflowClientFactory.build |
| 63 | + end |
| 64 | +end |
0 commit comments