Class: TopContainer

Inherits:
Sequel::Model
  • Object
show all
Defined in:
backend/app/model/top_container.rb

Constant Summary collapse

SERIES_LEVELS =
['series']
OTHERLEVEL_SERIES_LEVELS =
['accession']

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.batch_update(ids, fields) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
# File 'backend/app/model/top_container.rb', line 305

def self.batch_update(ids, fields)
  fields.each_value(&:strip!)
  out = {}
  begin
    n = self.filter(:id => ids).update(fields.merge({:system_mtime => Time.now, :user_mtime => Time.now}))
    out[:records_updated] = n
  rescue
    out[:error] = $!
  end
  out
end

.bulk_update_barcodes(barcode_data) ⇒ Object



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'backend/app/model/top_container.rb', line 400

def self.bulk_update_barcodes(barcode_data)
  updated = []

  ids = barcode_data.map {|uri, _| my_jsonmodel.id_for(uri)}

  # null out barcodes to avoid duplicate error as bulk updates are
  # applied
  TopContainer.filter(:id => ids).update(:barcode => nil)

  barcode_data.each do |uri, barcode|
    id = my_jsonmodel.id_for(uri)

    top_container = TopContainer[id]
    top_container.barcode = barcode
    top_container.system_mtime = Time.now

    top_container.save(:columns => [:barcode, :system_mtime])
    updated << id
  end

  TopContainer.update_mtime_for_ids(ids)
  updated
end

.bulk_update_container_profile(ids, container_profile_uri) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'backend/app/model/top_container.rb', line 318

def self.bulk_update_container_profile(ids, container_profile_uri)
  out = {:records_updated => ids.length}

  relationship = TopContainer.find_relationship(:top_container_profile)

  begin
    # Clear all existing container profile links
    relationship.handle_delete(relationship.find_by_participant_ids(TopContainer, ids).map(&:id))

    unless container_profile_uri.empty?
      container_profile = ContainerProfile[JSONModel(:container_profile).id_for(container_profile_uri)]

      raise "Container profile not found: #{container_profile_uri}" if !container_profile

      now = Time.now

      ids.each do |id|
        top_container = TopContainer[id]

        relationship.relate(top_container, container_profile, {
                              :aspace_relationship_position => 1,
                              :system_mtime => now,
                              :user_mtime => now
                            })
      end
    end

    TopContainer.update_mtime_for_ids(ids)

  rescue
    Log.exception($!)

    # This is going to roll back, so nothing will be updated.
    out[:records_updated] = 0
    out[:error] = $!
  end

  out
end

.bulk_update_indicators(indicator_data) ⇒ Object



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'backend/app/model/top_container.rb', line 425

def self.bulk_update_indicators(indicator_data)
  updated = []

  ids = indicator_data.map {|uri, _| my_jsonmodel.id_for(uri)}

  indicator_data.each do |uri, indicator|
    next unless indicator #skip any records where indicator is not specified

    id = my_jsonmodel.id_for(uri)

    top_container = TopContainer[id]
    top_container.indicator = indicator
    top_container.system_mtime = Time.now

    top_container.save(:columns => [:indicator, :system_mtime])
    updated << id
  end

  TopContainer.update_mtime_for_ids(ids)
  updated
end

.bulk_update_location(ids, location_uri) ⇒ Object



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'backend/app/model/top_container.rb', line 359

def self.bulk_update_location(ids, location_uri)
  out = {:records_updated => ids.length}

  relationship = TopContainer.find_relationship(:top_container_housed_at)

  begin
    relationship.handle_delete(relationship.find_by_participant_ids(TopContainer, ids).select {|v| v.status == 'current'}.map(&:id))

    unless location_uri.empty?
      location = Location[JSONModel(:location).id_for(location_uri)]

      raise "Location not found: #{location_uri}" if !location

      now = Time.now

      ids.each do |id|
        top_container = TopContainer[id]

        relationship.relate(top_container, location, {
                              :status => 'current',
                              :start_date => now.iso8601,
                              :aspace_relationship_position => 0,
                              :system_mtime => now,
                              :user_mtime => now
                            })
      end
    end

    TopContainer.update_mtime_for_ids(ids)

  rescue
    Log.exception($!)

    out[:records_updated] = 0
    out[:error] = $!
  end

  out
end

.bulk_update_locations(location_data) ⇒ Object



448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'backend/app/model/top_container.rb', line 448

def self.bulk_update_locations(location_data)
  out = {
    :records_ids_updated => []
  }

  ids = location_data.map {|uri, _| my_jsonmodel.id_for(uri)}

  # remove all 'current' locations
  relationship = TopContainer.find_relationship(:top_container_housed_at)
  relationship.handle_delete(relationship.find_by_participant_ids(TopContainer, ids).select {|v| v.status == 'current'}.map(&:id))

  now = Time.now

  # add new 'current' location for each container
  location_data.each do |uri, location_uri|
  id = my_jsonmodel.id_for(uri)

  begin
    location = Location[JSONModel(:location).id_for(location_uri)]

    raise "Location not found: #{location_uri}" if !location

    top_container = TopContainer[id]

    relationship.relate(top_container, location, {
      :status => 'current',
      :start_date => now.iso8601,
      :aspace_relationship_position => 0,
      :system_mtime => now,
      :user_mtime => now
    })

    out[:records_ids_updated] << id
  rescue
    Log.exception($!)

    out[:error] = $!
  end
end

  TopContainer.update_mtime_for_ids(ids)

  out[:records_updated] = out[:records_ids_updated].length

  out
end

.find_title_for(series) ⇒ Object



132
133
134
# File 'backend/app/model/top_container.rb', line 132

def self.find_title_for(series)
  series.respond_to?(:display_string) ? series.display_string : series.title
end

.for_barcode(barcode) ⇒ Object



495
496
497
# File 'backend/app/model/top_container.rb', line 495

def self.for_barcode(barcode)
  TopContainer[:barcode => barcode, :repo_id => self.active_repository]
end

.for_indicator(indicator) ⇒ Object



499
500
501
# File 'backend/app/model/top_container.rb', line 499

def self.for_indicator(indicator)
  TopContainer[:indicator => indicator, :repo_id => self.active_repository]
end

.linked_instance_dsObject



39
40
41
42
43
44
# File 'backend/app/model/top_container.rb', line 39

def self.linked_instance_ds
  TopContainer
    .join(:top_container_link_rlshp, :top_container_link_rlshp__top_container_id => :top_container__id)
    .join(:sub_container, :sub_container__id => :top_container_link_rlshp__sub_container_id)
    .join(:instance, :instance__id => :sub_container__instance_id)
end

.resource_ids_linked_directly(id) ⇒ Object



521
522
523
524
525
526
527
528
529
530
# File 'backend/app/model/top_container.rb', line 521

def self.resource_ids_linked_directly(id)
  Resource
   .join(:instance, :instance__resource_id => :resource__id)
   .join(:sub_container, :sub_container__instance_id => :instance__id)
   .join(:top_container_link_rlshp, :top_container_link_rlshp__sub_container_id => :sub_container__id)
   .filter(:top_container_link_rlshp__top_container_id => id)
   .select(:resource__id)
   .distinct
   .all.map {|row| row[:id]}
end

.resource_ids_linked_via_ao(id) ⇒ Object



532
533
534
535
536
537
538
539
540
541
542
# File 'backend/app/model/top_container.rb', line 532

def self.resource_ids_linked_via_ao(id)
  Resource
   .join(:archival_object, :archival_object__root_record_id => :resource__id)
   .join(:instance, :instance__archival_object_id => :archival_object__id)
   .join(:sub_container, :sub_container__instance_id => :instance__id)
   .join(:top_container_link_rlshp, :top_container_link_rlshp__sub_container_id => :sub_container__id)
   .filter(:top_container_link_rlshp__top_container_id => id)
   .select(:resource__id)
   .distinct
   .all.map {|row| row[:id]}
end

.search_stream(params, repo_id, &block) ⇒ Object



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
# File 'backend/app/model/top_container.rb', line 268

def self.search_stream(params, repo_id, &block)
  query = if params[:q]
            Solr::Query.create_keyword_search(params[:q])
          else
            Solr::Query.create_match_all_query
          end


  max_results = AppConfig.has_key?(:max_top_container_results) ? AppConfig[:max_top_container_results] : 10000

  query.pagination(1, max_results).
    set_repo_id(repo_id).
    set_record_types(params[:type]).
    set_facets(params[:facet]).
    set_filter(params[:filter])

  if params[:filter_term]
    query.set_filter(AdvancedQueryBuilder.from_json_filter_terms(params[:filter_term]))
  end

  query.add_solr_param(:qf, "series_identifier_u_stext collection_identifier_u_stext")

  url = query.to_solr_url
  req = Net::HTTP::Get.new(url.request_uri)

  ASHTTP.start_uri(url) do |http|
    http.request(req, nil) do |response|
      if response.code =~ /^4/
        raise response.body
      end

      block.call(response)
    end
  end
end

.sequel_to_jsonmodel(objs, opts = {}) ⇒ Object



179
180
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
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'backend/app/model/top_container.rb', line 179

def self.sequel_to_jsonmodel(objs, opts = {})
  jsons = super

  publication_status = ImpliedPublicationCalculator.new.for_top_containers(objs)

  jsons.zip(objs).each do |json, obj|
    json['is_linked_to_published_record'] = publication_status.fetch(obj)

    json['display_string'] = obj.display_string
    json['long_display_string'] = obj.long_display_string

    json['subcontainer_barcodes'] = obj.find_subcontainer_barcodes

    obj.series.each do |series|
      json['series'] ||= []
      json['series'] << {
        'ref' => series.uri,
        'identifier' => series.component_id,
        'display_string' => find_title_for(series),
        'level_display_string' => obj.level_display_string(series),
        'publish' => !(series.suppressed == 1) && (series.publish == 1)
      }
    end

    obj.collections.each do |collection|
      json['collection'] ||= []
      json['collection'] << {
        'ref' => collection.uri,
        'identifier' => Identifiers.format(Identifiers.parse(collection.identifier)),
        'display_string' => find_title_for(collection)
      }
    end

    if json['exported_to_ils']
      json['exported_to_ils'] = json['exported_to_ils'].getlocal.iso8601
    end
  end

  jsons
end

.touch_records(obj) ⇒ Object



544
545
546
547
548
549
# File 'backend/app/model/top_container.rb', line 544

def self.touch_records(obj)
  [{
    type: Resource,
    ids: (resource_ids_linked_directly(obj.id) + resource_ids_linked_via_ao(obj.id)).uniq
  }]
end

.update_mtime_for_ids(ids) ⇒ Object



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'backend/app/model/top_container.rb', line 503

def self.update_mtime_for_ids(ids)
  # Update the Top Container records themselves
  super

  # ... and all of their linked records
  ASModel.all_models.each do |model|
    next unless model.associations.include?(:instance)
    association = model.association_reflection(:instance)
    key = association[:key]
    linked_ids = TopContainer.linked_instance_ds.
                 join(model.table_name, Sequel.qualify(model.table_name, :id) => Sequel.qualify(:instance, key)).
                 filter(:top_container__id => ids).
                 select(Sequel.qualify(model.table_name, :id)).map {|row| row[:id] }
    model.update_mtime_for_ids(linked_ids)

  end
end

Instance Method Details

#calculate_collectionsObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'backend/app/model/top_container.rb', line 51

def calculate_collections
  result = []

  # Resource linked directly
  resource_ids = []
  resource_ids += self.class.resource_ids_linked_directly(self.id)

  # Resource linked via AO
  resource_ids += self.class.resource_ids_linked_via_ao(self.id)

  result += Resource
            .filter(:id => resource_ids.uniq)
            .select_all(:resource)
            .all

  result += Accession
           .join(:instance, :instance__accession_id => :accession__id)
           .join(:sub_container, :sub_container__instance_id => :instance__id)
           .join(:top_container_link_rlshp, :top_container_link_rlshp__sub_container_id => :sub_container__id)
           .filter(:top_container_link_rlshp__top_container_id => self.id)
           .select_all(:accession)
           .all

  result.uniq {|obj| [obj.class, obj.id]}
end

#calculate_seriesObject



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'backend/app/model/top_container.rb', line 82

def calculate_series
  linked_aos = ArchivalObject
               .join(:instance, :instance__archival_object_id => :archival_object__id)
               .join(:sub_container, :sub_container__instance_id => :instance__id)
               .join(:top_container_link_rlshp, :top_container_link_rlshp__sub_container_id => :sub_container__id)
               .filter(:top_container_link_rlshp__top_container_id => self.id)
               .select(:archival_object__id)

  # Find the top-level archival objects of our selected records.
  # Unfortunately there's no easy way to do this besides walking back up the
  # tree.
  top_level_aos = walk_to_top_level_aos(linked_aos.map {|row| row[:id]})

  ArchivalObject
    .join(:enumeration_value, {:level_enum__id => :archival_object__level_id},
          :table_alias => :level_enum)
    .filter(:archival_object__id => top_level_aos)
    .exclude(:archival_object__component_id => nil)
    .where { Sequel.|(
               { :level_enum__value => SERIES_LEVELS },
               Sequel.&({ :level_enum__value => 'otherlevel'},
                        { Sequel.function(:lower, :other_level) => OTHERLEVEL_SERIES_LEVELS }))
  }.select_all(:archival_object)
end

#collectionsObject



47
48
49
# File 'backend/app/model/top_container.rb', line 47

def collections
  @collections ||= calculate_collections
end

#deleteObject

When deleting a top_container, delete all related instances and their subcontainers



252
253
254
255
# File 'backend/app/model/top_container.rb', line 252

def delete
  related_records(:top_container_link).map {|sub| Instance[sub.instance_id].delete }
  super
end

#display_stringObject



150
151
152
# File 'backend/app/model/top_container.rb', line 150

def display_string
  ["#{type ? type.capitalize : ''}", "#{indicator}:", series_label, format_barcode].compact.join(" ").gsub(/:\Z/, '')
end

#find_subcontainer_barcodesObject



168
169
170
171
172
173
174
175
176
177
# File 'backend/app/model/top_container.rb', line 168

def find_subcontainer_barcodes
  sub_container_barcodes = ""
  found_subcontainers = related_records(:top_container_link)
  found_subcontainers.each do |found_subcontainer|
    if found_subcontainer.barcode_2
      sub_container_barcodes = sub_container_barcodes + found_subcontainer.barcode_2 + " "
    end
  end
  sub_container_barcodes
end

#format_barcodeObject



32
33
34
35
36
# File 'backend/app/model/top_container.rb', line 32

def format_barcode
  if self.barcode
    "[#{I18n.t("instance_container.barcode")}: #{self.barcode}]"
  end
end

#level_display_string(series) ⇒ Object



137
138
139
# File 'backend/app/model/top_container.rb', line 137

def level_display_string(series)
  series.other_level || I18n.t("enumerations.archival_record_level.#{series.level}")
end

#long_display_stringObject



155
156
157
158
159
160
161
162
163
164
165
166
# File 'backend/app/model/top_container.rb', line 155

def long_display_string
  container_bit = ["#{type ? type.capitalize : ''}", "#{indicator}", format_barcode].compact.join(" ")
  container_profile = related_records(:top_container_profile)
  container_profile &&= container_profile.name
  location = related_records(:top_container_housed_at).first
  location &&= location.title
  resource = collections.first
  resource &&= [Identifiers.format(Identifiers.parse(resource.identifier)), resource.title].compact.join(", ")

  # Long display string = container type container indicator [barcode: barcode], container profile name, location title, first resource/accession id, first resource/accession title, "series" label
  [container_bit, container_profile, location, resource, series_label].compact.join(", ")
end

#reindex_linked_recordsObject



264
265
266
# File 'backend/app/model/top_container.rb', line 264

def reindex_linked_records
  self.class.update_mtime_for_ids([self.id])
end

#seriesObject



78
79
80
# File 'backend/app/model/top_container.rb', line 78

def series
  @series ||= calculate_series
end

#series_labelObject



141
142
143
144
145
146
147
148
# File 'backend/app/model/top_container.rb', line 141

def series_label
  attached_series = self.series
  if attached_series.empty?
    nil
  else
    attached_series.map {|s| "#{level_display_string(s)} #{s.component_id}" }.join("; ")
  end
end

#update_from_json(json, opts = {}, apply_nested_records = true) ⇒ Object



257
258
259
260
261
# File 'backend/app/model/top_container.rb', line 257

def update_from_json(json, opts = {}, apply_nested_records = true)
  result = super
  reindex_linked_records
  result
end

#validateObject



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'backend/app/model/top_container.rb', line 17

def validate
  validates_unique([:repo_id, :barcode],
                   :message => "A barcode must be unique within a repository")
  map_validation_to_json_property([:repo_id, :barcode], :barcode)

  check = BarcodeCheck.new(Repository[self.class.active_repository].repo_code)

  if !check.valid?(self[:barcode])
    errors.add(:barcode, "Length must be within the range set in configuration")
  end

  super
end

#walk_to_top_level_aos(ao_ids) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'backend/app/model/top_container.rb', line 108

def walk_to_top_level_aos(ao_ids)
  result = []
  id_set = ao_ids

  while !id_set.empty?
    next_id_set = []

    ArchivalObject.filter(:id => id_set).select(:id, :parent_id).each do |row|
      if row[:parent_id].nil?
        # This one's a top-level record
        result << row[:id]
      else
        # Keep looking
        next_id_set << row[:parent_id]
      end

      id_set = next_id_set
    end
  end

  result
end