Class: AgentsController

Inherits:
ApplicationController show all
Defined in:
frontend/app/controllers/agents_controller.rb,
public/app/controllers/agents_controller.rb

Overview

frozen_string_literal: true

Constant Summary collapse

DEFAULT_AG_TYPES =
%w{repository resource accession archival_object digital_object classification}
DEFAULT_AG_FACET_TYPES =
%w{primary_type subjects}
DEFAULT_AG_SEARCH_OPTS =
{
  'sort' => 'title_sort asc',
  'resolve[]' => ['repository:id', 'resource:id@compact_resource', 'ancestors:id@compact_resource'],
  'facet.mincount' => 1
}
DEFAULT_AG_SEARCH_PARAMS =
{
  :q => ['*'],
  :limit => 'agent',
  :op => ['OR'],
  :field => ['title']
}
RETAINED_PARAMETERS =
['filter_fields', 'filter_values']

Instance Method Summary collapse

Methods inherited from ApplicationController

#archivesspace, can_access?, permission_mappings, set_access_control

Instance Method Details

#createObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'frontend/app/controllers/agents_controller.rb', line 62

def create
  handle_crud(instance: :agent,
              model: JSONModel(@agent_type),
              required_fields: @required_fields,
              find_opts: find_opts,
              before_hooks: [method(:set_structured_date_type)],
              on_invalid: lambda {
                ensure_auth_and_display
                return render_aspace_partial partial: 'agents/new' if inline?
                return render action: :new
              },
              on_valid: lambda  { |id|
                flash[:success] = t('agent._frontend.messages.created')

                if @agent['is_slug_auto'] == false &&
                   @agent['slug'].nil? &&
                   params['agent'] &&
                   params['agent']['is_slug_auto'] == '1'

                  flash[:warning] = t('slug.autogen_disabled')
                end

                return render json: @agent.to_hash if inline?
                if params.key?(:plus_one)
                  return redirect_to({ controller: :agents, action: :new, agent_type: @agent_type })
                end

                redirect_to({ controller: :agents, action: :edit, id: id, agent_type: @agent_type })
              })
end

#current_recordObject



28
29
30
# File 'frontend/app/controllers/agents_controller.rb', line 28

def current_record
  @agent
end

#defaultsObject



154
155
156
157
158
159
160
161
162
# File 'frontend/app/controllers/agents_controller.rb', line 154

def defaults
  defaults = DefaultValues.get params['agent_type']

  @agent = JSONModel(@agent_type).new({ agent_type: @agent_type })._always_valid!

  @agent.update(defaults.form_values) if defaults

  render 'defaults'
end

#deleteObject



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'frontend/app/controllers/agents_controller.rb', line 119

def delete
  agent = JSONModel(@agent_type).find(params[:id])

  if agent.key?('is_repo_agent')
    flash[:error] = t('errors.cannot_delete_repository_agent')
    redirect_to(controller: :agents, action: :show, id: params[:id])
    return
  end

  begin
    agent.delete
  rescue ConflictException => e
    flash[:error] = t('agent._frontend.messages.delete_conflict', error: t("errors.#{e.conflicts}", default: e.message))
    redirect_to(controller: :agents, action: :show, id: params[:id])
    return
  end

  flash[:success] = t('agent._frontend.messages.deleted', JSONModelI18nWrapper.new(agent: agent))
  redirect_to(controller: :agents, action: :index, deleted_uri: agent.uri)
end

#editObject



58
59
60
# File 'frontend/app/controllers/agents_controller.rb', line 58

def edit
  @agent = JSONModel(@agent_type).find(params[:id], find_opts)
end

#indexObject



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'frontend/app/controllers/agents_controller.rb', line 14

def index
  respond_to do |format|
    format.html do
      @search_data = Search.for_type(session[:repo_id], 'agent', params_for_backend_search.merge({ 'facet[]' => SearchResultData.AGENT_FACETS }))
    end
    format.csv do
      search_params = params_for_backend_search.merge({ 'facet[]' => SearchResultData.AGENT_FACETS })
      search_params['type[]'] = 'agent'
      uri = "/repositories/#{session[:repo_id]}/search"
      csv_response(uri, Search.build_filters(search_params), "#{t('agent._plural').downcase}.")
    end
  end
end

#mergeObject



217
218
219
220
221
222
223
224
225
226
227
# File 'frontend/app/controllers/agents_controller.rb', line 217

def merge
  merge_list = params[:record_uris]
  target = merge_list[0]
  merge_list.shift
  victims = merge_list
  target_type = JSONModel.parse_reference(target)[:type]
  handle_merge(victims,
               target,
               'agent',
               { agent_type: target_type })
end

#merge_detailObject



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 'frontend/app/controllers/agents_controller.rb', line 269

def merge_detail
  merge_destination_uri = JSONModel(@agent_type).uri_for(params[:id])
  merge_candidate_uri = params['victim_uri']
  request = JSONModel(:merge_request_detail).new
  request.target = { 'ref' => JSONModel(@agent_type).uri_for(params[:id]) }
  request.victims = Array.wrap({ 'ref' => params['victim_uri'] })

  # the backend is expecting to know how the user may have re-ordered subrecords in the merge interface. This information is encoded in the params, but will be stripped out when we clean them up unless we add them as a pseudo schema attribute.
  # add_position_to_agents_merge does exactly this.
  agent_params_with_position = add_position_to_agents_merge_params(params['agent'])
  request.selections = cleanup_params_for_schema(agent_params_with_position, JSONModel(@agent_type).schema)

  uri = "#{JSONModel::HTTP.backend_url}/merge_requests/agent_detail"
  if params['dry_run']
    uri += '?dry_run=true'
    response = JSONModel::HTTP.post_json(URI(uri), request.to_json)
    merge_response = ASUtils.json_parse(response.body)

    @agent = JSONModel(@agent_type).from_hash(merge_response['result'], find_opts)
    render_aspace_partial partial: 'agents/merge_preview', locals: { object: @agent }
  else
    begin
      # For each linked resource or AO, need to remember roles to re-establish with the destination agent.
      candidate_roles = get_merge_candidate_linked_roles(merge_candidate_uri)

      response = JSONModel::HTTP.post_json(URI(uri), request.to_json)

      recreate_linked_record_agent_roles(candidate_roles, merge_destination_uri)

      flash[:success] = t('agent._frontend.messages.merged')
      resolver = Resolver.new(request.target['ref'])
      redirect_to(resolver.view_uri)
    rescue ValidationException => e
      flash[:error] = e.errors.to_s
      redirect_to({ action: :show, id: params[:id] }.merge(extra_params))
    rescue ConflictException => e
      flash[:error] = t('errors.merge_conflict', message: e.conflicts)
      redirect_to({ action: :show, id: params[:id] }.merge(extra_params))
    rescue RecordNotFound => e
      flash[:error] = t('errors.error_404')
      redirect_to({ action: :show, id: params[:id] }.merge(extra_params))
    end
  end
end

#merge_selectorObject



229
230
231
232
233
234
235
236
237
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
# File 'frontend/app/controllers/agents_controller.rb', line 229

def merge_selector
  @agent = JSONModel(@agent_type).find(params[:id], find_opts)

  if params[:refs].is_a?(Array)
    flash[:error] = t('errors.merge_too_many_victims')
    redirect_to({ action: :show, id: params[:id] })
    return
  end

  victim_details = JSONModel.parse_reference(params[:refs])
  @victim_type = victim_details[:type].to_sym
  if @victim_type != @agent_type
    flash[:error] = t('errors.merge_different_types')
    redirect_to({ action: :show, id: params[:id] })
    return
  end

  @victim = JSONModel(@victim_type).find(victim_details[:id], find_opts)
  if @agent.key?('is_user') || @victim.key?('is_user')
    flash[:error] = t('errors.merge_denied_for_system_user')
    redirect_to({ action: :show, id: params[:id] })
    return
  end

  relationship_uris = @victim['related_agents'] ? @victim['related_agents'].map {|ra| ra['ref']} : []
  if relationship_uris.include?(@agent['uri'])
    flash[:error] = t('errors.merge_denied_relationship')
    redirect_to({ action: :show, id: params[:id] })
    return
  end

  if !user_can?('view_agent_contact_record') && (@agent.agent_contacts.any? || @victim.agent_contacts.any?)
    flash[:error] = t('errors.merge_restricted_contact_details')
    redirect_to({ action: :show, id: params[:id] })
    return
  end

  render '_merge_selector'
end

#newObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'frontend/app/controllers/agents_controller.rb', line 36

def new
  @agent = JSONModel(@agent_type).new({ agent_type: @agent_type })._always_valid!
  if user_prefs['default_values']
    defaults = DefaultValues.get @agent_type.to_s
    @agent.update(defaults.values) if defaults
  end

  @required_fields.each_required_subrecord do |property, stub_record|
    @agent[property] << stub_record if @agent[property].empty?
  end

  if @agent.names.empty?
    @agent.names = [@name_type.new({ authorized: true, is_display_name: true })._always_valid!]
  end

  ensure_auth_and_display

  set_sort_name_default

  render_aspace_partial partial: 'agents/new' if inline?
end

#publishObject



140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'frontend/app/controllers/agents_controller.rb', line 140

def publish
  agent = JSONModel(@agent_type).find(params[:id])

  response = JSONModel::HTTP.post_form("#{agent.uri}/publish")

  if response.code == '200'
    flash[:success] = t('agent._frontend.messages.published', JSONModelI18nWrapper.new(agent: agent).enable_parse_mixed_content!(url_for(:root)))
  else
    flash[:error] = ASUtils.json_parse(response.body)['error'].to_s
  end

  redirect_to request.referer
end

#requiredObject



181
182
183
184
185
186
# File 'frontend/app/controllers/agents_controller.rb', line 181

def required
  @agent = JSONModel(@agent_type).new({ agent_type: @agent_type })._always_valid!
  # we are pretending this is an agent form but it's really a RequiredFields form
  @agent.lock_version = @required_fields.lock_version
  render 'required'
end

#searchObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'public/app/controllers/agents_controller.rb', line 69

def search
  # need at least q[]=WHATEVER&op[]=OR&field[]=title&from_year[]=&to_year[]=&limit=pui_agent
  @base_search = '/agents/search?'
  page = Integer(params.fetch(:page, "1"))
  begin
    set_up_and_run_search( DEFAULT_AG_TYPES, DEFAULT_AG_FACET_TYPES, DEFAULT_AG_SEARCH_OPTS, params)
  rescue NoResultsError
    flash[:error] = I18n.t('search_results.no_results')
    redirect_back(fallback_location: '/') and return
  rescue Exception => error
    flash[:error] = I18n.t('errors.unexpected_error')
    redirect_back(fallback_location: '/agents') and return
  end
  @page_title = I18n.t('agent._plural')
  @results_type = @page_title
  @search_title = I18n.t('search_results.search_for', {:type => I18n.t('agent._plural'), :term => params.fetch(:q)[0]})
  render 'search/search_results'
end

#showObject



32
33
34
# File 'frontend/app/controllers/agents_controller.rb', line 32

def show
  @agent = JSONModel(@agent_type).find(params[:id], find_opts)
end

#updateObject



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
# File 'frontend/app/controllers/agents_controller.rb', line 93

def update
  handle_crud(instance: :agent,
              model: JSONModel(@agent_type),
              obj: JSONModel(@agent_type).find(params[:id], find_opts),
              before_hooks: [method(:set_structured_date_type)],
              on_invalid: lambda {
                if @agent.names.empty?
                  @agent.names = [@name_type.new._always_valid!]
                end

                return render action: :edit
              },
              on_valid: lambda  { |id|
                flash[:success] = t('agent._frontend.messages.updated')
                if @agent['is_slug_auto'] == false &&
                   @agent['slug'].nil? &&
                   params['agent'] &&
                   params['agent']['is_slug_auto'] == '1'

                  flash[:warning] = t('slug.autogen_disabled')
                end

                redirect_to controller: :agents, action: :edit, id: id, agent_type: @agent_type
              })
end

#update_defaultsObject



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'frontend/app/controllers/agents_controller.rb', line 164

def update_defaults
  DefaultValues.from_hash({
                            'record_type' => @agent_type.to_s,
                            'lock_version' => params['agent'].delete('lock_version'),
                            'defaults' => cleanup_params_for_schema(
                              params['agent'],
                              JSONModel(@agent_type).schema
                            )
                          }).save

  flash[:success] = t('default_values.messages.defaults_updated')
  redirect_to controller: :agents, action: :defaults
rescue Exception => e
  flash[:error] = e.message
  redirect_to controller: :agents, action: :defaults
end

#update_requiredObject



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'frontend/app/controllers/agents_controller.rb', line 188

def update_required
  processed_params = cleanup_params_for_schema(
    params['agent'],
    JSONModel(@agent_type).schema
  )
  subrecord_requirements = []

  processed_params.each do |key, defn|
    next unless defn.is_a?(Array) && defn.size == 1
    # we aren't interested in booleans
    defn[0].reject! {|k, v| [false, true].include? (v) }
    subrecord_requirements << {
      property: key,
      record_type: defn[0]['jsonmodel_type'],
      required: (defn[0]['required'] == 'true'),
      required_fields: defn[0].keys.reject { |k| ['jsonmodel_type', 'required'].include?(k) }
    }
  end
  RequiredFields.from_hash({
                             'lock_version' => processed_params['lock_version'],
                             'record_type' => @agent_type.to_s,
                             'subrecord_requirements' => subrecord_requirements}).save
  flash[:success] = t('required_fields.messages.required_fields_updated')
  redirect_to controller: :agents, action: :required
rescue Exception => e
  flash[:error] = e.message
  redirect_to controller: :agents, action: :required
end