Class: ResourcesController

Inherits:
ApplicationController show all
Includes:
ExportHelper, ResultInfo
Defined in:
frontend/app/controllers/resources_controller.rb,
public/app/controllers/resources_controller.rb

Constant Summary collapse

DEFAULT_RES_FACET_TYPES =
%w{primary_type subjects published_agents langcode}
DEFAULT_RES_INDEX_OPTS =
{
  'resolve[]' => ['repository:id', 'resource:id@compact_resource', 'top_container_uri_u_sstr:id'],
  'sort' => 'title_sort asc',
  'facet.mincount' => 1
}
DEFAULT_RES_SEARCH_OPTS =
{
  'resolve[]' => ['repository:id', 'resource:id@compact_resource', 'ancestors:id@compact_resource', 'top_container_uri_u_sstr:id'],
  'facet.mincount' => 1
}
DEFAULT_RES_SEARCH_PARAMS =
{
  q: ['*'],
  limit: 'resource',
  op: [''],
  field: ['title']
}
DEFAULT_RES_TYPES =
%w{pui_archival_object pui_digital_object agent subject}

Constants included from Searchable

Searchable::ABSTRACT

Instance Method Summary collapse

Methods included from ResultInfo

#breadcrumb_info, #fill_request_info, #get_rep_image, #handle_dates, #handle_external_docs, #process_agents, #process_digital, #process_digital_instance, #process_extents, #process_file_versions, #process_repo_info, #process_subjects

Methods included from ExportHelper

#csv_response, #xml_response

Methods inherited from ApplicationController

#archivesspace, can_access?, permission_mappings, set_access_control

Methods included from JsonHelper

#merge_notes, #process_json_notes

Methods included from Searchable

#default_search_opts, #get_filter_years, #handle_results, #html_notes, #process_results, #process_search_results, #repo_context, #search_terms, #set_up_advanced_search, #set_up_and_run_search, #set_up_search, #strip_facet_fields

Methods included from HandleFaceting

#fetch_only_facets, #get_pretty_facet_value, #strip_facets

Methods included from ManipulateNode

#inheritance, #process_mixed_content, #strip_mixed_content

Instance Method Details

#accept_childrenObject



336
337
338
# File 'frontend/app/controllers/resources_controller.rb', line 336

def accept_children
  handle_accept_children(JSONModel(:resource))
end

#add_childrenObject



259
260
261
262
263
264
265
266
267
268
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
# File 'frontend/app/controllers/resources_controller.rb', line 259

def add_children
  @parent = Resource.find(params[:id])
  @resource_uri = @parent.uri

  if params[:archival_record_children].blank? or params[:archival_record_children]["children"].blank?

    @children = ResourceChildren.new
    flash.now[:error] = I18n.t("rde.messages.no_rows")

  else
    children_data = cleanup_params_for_schema(params[:archival_record_children], JSONModel(:archival_record_children).schema)

    begin
      @children = ResourceChildren.from_hash(children_data, false)

      if params["validate_only"] == "true"
        @exceptions = @children.children.collect {|c| JSONModel(:archival_object).from_hash(c, false)._exceptions}

        error_count = @exceptions.select {|e| !e.empty?}.length
        if error_count > 0
          flash.now[:error] = I18n.t("rde.messages.rows_with_errors", :count => error_count)
        else
          flash.now[:success] = I18n.t("rde.messages.rows_no_errors")
        end

        return render_aspace_partial :partial => "shared/rde"
      else
        @children.save(:resource_id => @parent.id)
      end

      return render :plain => I18n.t("rde.messages.success")
    rescue JSONModel::ValidationException => e
      @exceptions = @children.children.collect {|c| JSONModel(:archival_object).from_hash(c, false)._exceptions}

      if @exceptions.all?(&:blank?)
        e.errors.each { |key, vals| flash.now[:error] = "#{key} : #{vals.join('<br/>')}" }
      else
        flash.now[:error] = I18n.t("rde.messages.rows_with_errors", :count => @exceptions.select {|e| !e.empty?}.length)
      end
    end

  end

  render_aspace_partial :partial => "shared/rde"
end

#createObject



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'frontend/app/controllers/resources_controller.rb', line 181

def create
  flash.keep(:spawned_from_accession)

  handle_crud(:instance => :resource,
              :on_invalid => ->() {
                render action: "new"
              },
              :on_valid => ->(id) {
                flash[:success] = I18n.t("resource._frontend.messages.created", JSONModelI18nWrapper.new(:resource => @resource).enable_parse_mixed_content!(url_for(:root)))

                if @resource["is_slug_auto"] == false &&
                   @resource["slug"] == nil &&
                   params["resource"] &&
                   params["resource"]["is_slug_auto"] == "1"

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

                redirect_to({
                              :controller => :resources,
                              :action => :edit,
                              :id => id
                           })
              })
end

#current_recordObject



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

def current_record
  @resource
end

#defaultsObject



69
70
71
72
73
74
75
76
77
78
79
80
# File 'frontend/app/controllers/resources_controller.rb', line 69

def defaults
  defaults = DefaultValues.get 'resource'

  values = defaults ? defaults.form_values : {:title => I18n.t("resource.title_default", :default => "")}

  @resource = Resource.new(values)._always_valid!

  @form_title = I18n.t("default_values.form_title.resource")


  render "defaults"
end

#deleteObject



231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'frontend/app/controllers/resources_controller.rb', line 231

def delete
  resource = Resource.find(params[:id])

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


  flash[:success] = I18n.t("resource._frontend.messages.deleted", JSONModelI18nWrapper.new(:resource => resource).enable_parse_mixed_content!(url_for(:root)))
  redirect_to(:controller => :resources, :action => :index, :deleted_uri => resource.uri)
end

#editObject



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'frontend/app/controllers/resources_controller.rb', line 152

def edit
  flash.keep if not flash.empty? # keep the notices so they display on the subsequent ajax call

  # check for active batch import job and redirect if there is one
  active_job = find_active_bulk_import_job
  if active_job
    flash[:active_bulk_import_job] = I18n.t(
      'bulk_import_job.active',
      url: "#{AppConfig[:frontend_proxy_url]}/resolve/readonly?uri=#{active_job['uri']}",
      uri: active_job['uri']
    )
    return redirect_to(:action => :show, :id => params[:id], :inline => params[:inline])
  end

  if params[:inline]
    # only fetch the fully resolved record when rendering the full form
    @resource = fetch_resolved(:resource, params[:id], excludes: ['linked_events', 'linked_events::linked_records'])

    if @resource.suppressed
      return redirect_to(:action => :show, :id => params[:id], :inline => params[:inline])
    end

    return render_aspace_partial :partial => "resources/edit_inline"
  end

  @resource = JSONModel(:resource).find(params[:id])
end

#indexObject

present a list of resources. If no repository named, just get all of them.



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'public/app/controllers/resources_controller.rb', line 34

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

#infiniteObject



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'public/app/controllers/resources_controller.rb', line 185

def infinite
  @root_uri = "/repositories/#{params[:rid]}/resources/#{params[:id]}"
  begin
    @criteria = {}
    @criteria['resolve[]'] = ['repository:id', 'resource:id@compact_resource', 'top_container_uri_u_sstr:id', 'related_accession_uris:id']
    @result = archivesspace.get_record(@root_uri, @criteria)
    @has_containers = has_containers?(@root_uri)

    @repo_info = @result.repository_information
    @page_title = "#{I18n.t('resource._singular')}: #{strip_mixed_content(@result.display_string)}"
    @context = [{:uri => @repo_info['top']['uri'], :crumb => @repo_info['top']['name'], type: 'repository'},
      {:uri => nil, :crumb => process_mixed_content(@result.display_string), type: @result.primary_type}]
    fill_request_info
    @ordered_records = archivesspace.get_record(@root_uri + '/ordered_records').json.fetch('uris')
  rescue RecordNotFound
    record_not_found(uri, 'resource')
  end
end

#inventoryObject



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'public/app/controllers/resources_controller.rb', line 244

def inventory
  uri = "/repositories/#{params[:rid]}/resources/#{params[:id]}"
  tree_root = archivesspace.get_raw_record(uri + '/tree/root') rescue nil
  @has_children = tree_root && tree_root['child_count'] > 0
  # stuff for the collection bits
  @criteria = {}
  @criteria['resolve[]'] = ['repository:id', 'resource:id@compact_resource', 'top_container_uri_u_sstr:id', 'related_accession_uris:id']
  @result =  archivesspace.get_record(uri, @criteria)
  @repo_info = @result.repository_information
  @page_title = "#{I18n.t('resource._singular')}: #{strip_mixed_content(@result.display_string)}"
  @context = [{:uri => @repo_info['top']['uri'], :crumb => @repo_info['top']['name'], type: 'repository'},
    {:uri => nil, :crumb => process_mixed_content(@result.display_string), type: @result.primary_type}]
  fill_request_info

  # top container stuff ... sets @records
  fetch_containers(uri, "#{uri}/inventory", params)

  if !@results.blank?
    params[:q] = '*'

    # ANW-733: Add facet filter query params.
    # This is automatically done in other places where pagination objects are created, but was missing here.

    search_uri = @base_search
    if @facet_filter
      search_uri += @facet_filter.get_filter_url_params
    end

    @pager = Pager.new(search_uri, @results['this_page'], @results['last_page'])
  else
    @pager = nil
  end

rescue RecordNotFound
  record_not_found(uri, 'resource')
end

#mergeObject



341
342
343
344
345
# File 'frontend/app/controllers/resources_controller.rb', line 341

def merge
  handle_merge( params[:refs],
                JSONModel(:resource).uri_for(params[:id]),
                'resource')
end

#models_in_graphObject



366
367
368
369
370
371
372
373
# File 'frontend/app/controllers/resources_controller.rb', line 366

def models_in_graph
  list_uri = JSONModel(:resource).uri_for(params[:id]) + "/models_in_graph"
  list = JSONModel::HTTP.get_json(list_uri)

  render :json => list.select { |type| type != "lang_material" }.map {|type|
    [type, I18n.t("#{type == 'archival_object' ? 'resource_component' : type}._singular")]
  }
end

#newObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'frontend/app/controllers/resources_controller.rb', line 47

def new
  @resource = Resource.new(:title => I18n.t("resource.title_default", :default => ""))._always_valid!
  defaults = user_defaults('resource')
  if defaults
    @resource.update(defaults.values)
    @form_title = "#{I18n.t('actions.new_prefix')} #{I18n.t('resource._singular')}"
  end

  if params[:accession_id]
    acc = Accession.find(params[:accession_id], find_opts)

    if acc
      @resource.populate_from_accession(acc)
      flash.now[:info] = I18n.t("resource._frontend.messages.spawned", JSONModelI18nWrapper.new(:accession => acc).enable_parse_mixed_content!(url_for(:root)))
      flash[:spawned_from_accession] = acc.id
    end
  end

  return render_aspace_partial :partial => "resources/new_inline" if params[:inline]
end

#node_from_rootObject



109
110
111
112
113
114
# File 'frontend/app/controllers/resources_controller.rb', line 109

def node_from_root
  resource_uri = JSONModel(:resource).uri_for(params[:id])

  render :json => pass_through_json("#{resource_uri}/tree/node_from_root",
                                    'node_ids[]' => params[:node_ids])
end

#publishObject



306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'frontend/app/controllers/resources_controller.rb', line 306

def publish
  resource = Resource.find(params[:id])

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

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

  redirect_to request.referer
end

#rdeObject



247
248
249
250
251
252
253
254
255
256
# File 'frontend/app/controllers/resources_controller.rb', line 247

def rde
  flash.clear

  @parent = Resource.find(params[:id])
  @resource_uri = @parent.uri
  @children = ResourceChildren.new
  @exceptions = []

  render_aspace_partial :partial => "shared/rde"
end

#resolveObject



174
175
176
177
178
179
180
181
182
# File 'public/app/controllers/resources_controller.rb', line 174

def resolve
  uri = "/repositories/#{params[:rid]}/resources/#{params[:id]}"
  results = archivesspace.search("ref_id:#{params[:ref_id]} AND resource:\"#{uri}\"", 1, 'type[]' => 'pui')
  if results['results'].length == 1
    redirect_to results['results'][0]['uri']
  else
    record_not_resolved("#{uri}/resolve/#{params[:ref_id]}", 'archival_object')
  end
end

#searchObject



90
91
92
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'public/app/controllers/resources_controller.rb', line 90

def search
  repo_id = params.require(:repo_id)
  res_id = "/repositories/#{repo_id}/resources/#{params.require(:id)}"
  search_opts = DEFAULT_RES_SEARCH_OPTS
  search_opts['fq'] = ["resource:\"#{res_id}\""]
  params[:res_id] = res_id
#    q = params.fetch(:q,'')
  unless params.fetch(:q, nil)
    params[:q] = ['*']
  end
  @base_search = "#{res_id}/search?"
  begin
    set_up_advanced_search(DEFAULT_RES_TYPES, DEFAULT_RES_FACET_TYPES, search_opts, params)
  rescue Exception => error
    flash[:error] = I18n.t('errors.unexpected_error')
    redirect_back(fallback_location: res_id ) and return
  end

  page = Integer(params.fetch(:page, "1"))
  @results = archivesspace.advanced_search('/search', page, @criteria)
  if @results['total_hits'].blank? || @results['total_hits'] == 0
    flash[:notice] = I18n.t('search_results.no_results')
    redirect_back(fallback_location: @base_search)
  else
    process_search_results(@base_search)
    title = ''
    title =  strip_mixed_content(@results['results'][0]['_resolved_resource']['json']['title']) if @results['results'][0] && @results['results'][0].dig('_resolved_resource', 'json')

    @context = []
    @context.push({:uri => "/repositories/#{repo_id}",
                    :crumb => get_pretty_facet_value('repository', "/repositories/#{repo_id}"),
                    :type => 'repository'})
    unless title.blank?
      @context.push({:uri => "#{res_id}", :crumb => title, type: 'resource'})
    end
    if @results['total_hits'] > 1
      @search[:dates_within] = true if params.fetch(:filter_from_year, '').blank? && params.fetch(:filter_to_year, '').blank?
      @search[:text_within] = true
    end
    @page_title = I18n.t('actions.search_in', :type => (title.blank? ? I18n.t('resource._singular') : "\"#{title}\""))
    @sort_opts = []
    all_sorts = Search.get_sort_opts
    all_sorts.delete('relevance') unless params[:q].size > 1 || params[:q] != '*'
    all_sorts.keys.each do |type|
      @sort_opts.push(all_sorts[type])
    end
    @no_statement = true
    render 'search/search_results'
  end
end

#showObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'frontend/app/controllers/resources_controller.rb', line 32

def show
  flash.keep

  if params[:inline]
    event_hits = fetch_linked_events_count(:resource, params[:id])
    excludes = event_hits > AppConfig[:max_linked_events_to_resolve] ? ['linked_events', 'linked_events::linked_records'] : []
    @resource = fetch_resolved(:resource, params[:id], excludes: excludes)

    flash.now[:info] = I18n.t("resource._frontend.messages.suppressed_info", JSONModelI18nWrapper.new(:resource => @resource).enable_parse_mixed_content!(url_for(:root))) if @resource.suppressed
    return render_aspace_partial :partial => "resources/show_inline"
  end

  @resource = JSONModel(:resource).find(params[:id])
end

#suppressObject



348
349
350
351
352
353
354
# File 'frontend/app/controllers/resources_controller.rb', line 348

def suppress
  resource = JSONModel(:resource).find(params[:id])
  resource.set_suppressed(true)

  flash[:success] = I18n.t("resource._frontend.messages.suppressed", JSONModelI18nWrapper.new(:resource => resource).enable_parse_mixed_content!(url_for(:root)))
  redirect_to(:controller => :resources, :action => :show, :id => params[:id])
end

#transferObject



141
142
143
144
145
146
147
148
149
# File 'frontend/app/controllers/resources_controller.rb', line 141

def transfer
  begin
    handle_transfer(Resource)
  rescue ArchivesSpace::TransferConflictException => e
    @transfer_errors = e.errors
    show
    render :action => :show
  end
end

#tree_nodeObject



116
117
118
119
120
121
122
123
124
125
126
# File 'frontend/app/controllers/resources_controller.rb', line 116

def tree_node
  resource_uri = JSONModel(:resource).uri_for(params[:id])
  node_uri = if !params[:node].blank?
               params[:node]
             else
               nil
             end

  render :json => pass_through_json("#{resource_uri}/tree/node",
                                    :node_uri => node_uri)
end

#tree_node_from_rootObject



237
238
239
240
241
242
# File 'public/app/controllers/resources_controller.rb', line 237

def tree_node_from_root
  @root_uri = "/repositories/#{params[:rid]}/resources/#{params[:id]}"
  render :json => archivesspace.get_raw_record(@root_uri + '/tree/node_from_root_' + params[:node_ids].first)
rescue RecordNotFound
  render json: {}, status: 404
end

#tree_rootObject



103
104
105
106
107
# File 'frontend/app/controllers/resources_controller.rb', line 103

def tree_root
  resource_uri = JSONModel(:resource).uri_for(params[:id])

  render :json => pass_through_json("#{resource_uri}/tree/root")
end

#tree_waypointObject



128
129
130
131
132
133
134
135
136
137
138
139
# File 'frontend/app/controllers/resources_controller.rb', line 128

def tree_waypoint
  resource_uri = JSONModel(:resource).uri_for(params[:id])
  node_uri = if !params[:node].blank?
               params[:node]
             else
               nil
             end

  render :json => pass_through_json("#{resource_uri}/tree/waypoint",
                                    :parent_node => node_uri,
                                    :offset => params[:offset])
end

#unpublishObject



321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'frontend/app/controllers/resources_controller.rb', line 321

def unpublish
  resource = Resource.find(params[:id])

  response = JSONModel::HTTP.post_form("#{resource.uri}/unpublish")

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

  redirect_to request.referer
end

#unsuppressObject



357
358
359
360
361
362
363
# File 'frontend/app/controllers/resources_controller.rb', line 357

def unsuppress
  resource = JSONModel(:resource).find(params[:id])
  resource.set_suppressed(false)

  flash[:success] = I18n.t("resource._frontend.messages.unsuppressed", JSONModelI18nWrapper.new(:resource => resource).enable_parse_mixed_content!(url_for(:root)))
  redirect_to(:controller => :resources, :action => :show, :id => params[:id])
end

#updateObject



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'frontend/app/controllers/resources_controller.rb', line 208

def update
  handle_crud(:instance => :resource,
              :obj => fetch_resolved(:resource, params[:id], excludes: ['linked_events', 'linked_events::linked_records']),
              :on_invalid => ->() {
                render_aspace_partial :partial => "edit_inline"
              },
              :on_valid => ->(id) {

                flash.now[:success] = I18n.t("resource._frontend.messages.updated", JSONModelI18nWrapper.new(:resource => @resource).enable_parse_mixed_content!(url_for(:root)))

                if @resource["is_slug_auto"] == false &&
                   @resource["slug"] == nil &&
                   params["resource"] &&
                   params["resource"]["is_slug_auto"] == "1"

                  flash.now[:warning] = I18n.t("slug.autogen_disabled")
                end

                render_aspace_partial :partial => "edit_inline"
              })
end

#update_defaultsObject



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'frontend/app/controllers/resources_controller.rb', line 83

def update_defaults
  begin
    DefaultValues.from_hash({
                              "record_type" => "resource",
                              "lock_version" => params[:resource].delete('lock_version'),
                              "defaults" => cleanup_params_for_schema(
                                                                      params[:resource],
                                                                      JSONModel(:resource).schema
                                                                      )
                            }).save

    flash[:success] = "Defaults updated"

    redirect_to :controller => :resources, :action => :defaults
  rescue Exception => e
    flash[:error] = e.message
    redirect_to :controller => :resources, :action => :defaults
  end
end

#waypointsObject



204
205
206
207
208
209
210
211
212
213
214
# File 'public/app/controllers/resources_controller.rb', line 204

def waypoints
  search_opts = {
    'resolve[]' => ['top_container_uri_u_sstr:id']
  }
  results = archivesspace.search_records(params[:urls], search_opts, true)

  render :json => Hash[results.records.map {|record|
                         @result = record
                         [record.uri,
                          render_to_string(:partial => 'infinite_item')]}]
end