Class: TaxonNameRelationship

Inherits:
ApplicationRecord show all
Includes:
Housekeeping, Shared::Citations, Shared::DwcOccurrenceHooks, Shared::IsData, Shared::Notes, SoftValidation
Defined in:
app/models/taxon_name_relationship.rb

Overview

TODO:

SourceClassifiedAs is not really Combination in the other sense

TODO:

validate, that all the relationships in the table could be linked to relationships in classes (if those had changed)

TODO:

Check if more than one species associated with the genus in the original paper

A NOMEN github.com/SpeciesFileGroup/nomen relationship between two Protonyms.

Unless otherwise noted relationships read left to right, and can be interpreted by inserting “of” after the class name.

For example the triple:

Subject: Aus aus - TaxonNameRelationship::Iczn::Invalidating::Synonym - Object: Bus bus

Can be read as:

  aus synonym OF bus

Note that not all relationships are reflective.  We can't say, for the example above we can't say

  bus valid_name OF aus

Note that we can not say that all names that are subjects are valid, this is determined on a case by case basis.

TaxonNameRelationships have a domain (attributes on the subject) and range (attributes on the object). So if you use a relationship you may be asserting a TaxonNameClassification also exists for the subject or object.

Defined Under Namespace

Classes: Combination, CurrentCombination, Hybrid, Icn, Icnp, Icvcn, Iczn, OriginalCombination, SourceClassifiedAs, Typification

Constant Summary

Constants included from SoftValidation

SoftValidation::ANCESTORS_WITH_SOFT_VALIDATIONS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Shared::IsData

#errors_excepting, #full_error_messages_excepting, #identical, #is_community?, #is_destroyable?, #is_editable?, #is_in_use?, #is_in_users_projects?, #metamorphosize, #similar

Methods included from SoftValidation

#clear_soft_validations, #fix_for, #fix_soft_validations, #soft_fixed?, #soft_valid?, #soft_validate, #soft_validated?, #soft_validations, #soft_validators

Methods included from Shared::Notes

#concatenated_notes_string, #reject_notes

Methods included from Shared::Citations

#cited?, #mark_citations_for_destruction, #origin_citation_source_id, #reject_citations, #requires_citation?, #sources_by_topic_id

Methods included from Housekeeping

#has_polymorphic_relationship?

Methods inherited from ApplicationRecord

transaction_with_retry

Instance Attribute Details

#no_cachedBoolean?

Returns When true, cached values are not built.

Returns:

  • (Boolean, nil)

    When true, cached values are not built



54
55
56
# File 'app/models/taxon_name_relationship.rb', line 54

def no_cached
  @no_cached
end

#object_taxon_name_idInteger

Returns the object taxon name.

Returns:

  • (Integer)

    the object taxon name



44
45
46
47
48
49
50
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
140
141
142
143
144
145
146
147
148
149
150
151
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
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
219
220
221
222
223
224
225
226
227
228
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
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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
357
358
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'app/models/taxon_name_relationship.rb', line 44

class TaxonNameRelationship < ApplicationRecord
  include Housekeeping
  include Shared::Citations
  include Shared::Notes
  include SoftValidation
  include Shared::DwcOccurrenceHooks
  include Shared::IsData

  # @return [Boolean, nil]
  #   When true, cached values are not built
  attr_accessor :no_cached

  belongs_to :subject_taxon_name, class_name: 'TaxonName', inverse_of: :taxon_name_relationships # left side
  belongs_to :object_taxon_name, class_name: 'TaxonName', inverse_of: :related_taxon_name_relationships # right side

  # !! Keep as after_commit unless you are wanting to spend a lot of time
  # !! refactoring tests
  after_commit :set_cached_names_for_taxon_names, unless: -> {self.no_cached || destroyed?}
  after_destroy :set_cached_names_for_taxon_names, unless: -> {self.no_cached}

  # TODO: remove, it's required by STI
  validates_presence_of :type, message: 'Relationship type should be specified'
  validates_presence_of :subject_taxon_name, message: 'Missing taxon name on the left side'
  validates_presence_of :object_taxon_name, message: 'Missing taxon name on the right side'
  validates_uniqueness_of :object_taxon_name_id, scope: [:type, :project_id], if: :is_combination?
  validates_uniqueness_of :object_taxon_name_id, scope: [:type, :subject_taxon_name_id, :project_id], unless: :is_combination?

  validate :validate_type, :validate_subject_and_object_are_not_identical
  validate :subject_and_object_in_same_project

  with_options unless: -> {!subject_taxon_name || !object_taxon_name} do
    validate :validate_subject_and_object_share_code,
      :validate_uniqueness_of_typification_object,
      #:validate_uniqueness_of_synonym_subject,
      :validate_object_and_subject_both_protonyms,
      :validate_object_must_equal_subject_for_uncertain_placement,
      :validate_subject_and_object_ranks,
      :validate_rank_group
  end

  # TODO: isolate to an include file sensu protonym
  soft_validate(
    :sv_validate_required_relationships,
    set: :validate_required_relationships,
    name: 'Required relationships',
    description: 'Required relationships' )

  soft_validate(
    :sv_validate_disjoint_relationships,
    set: :validate_disjoint_relationships,
    name: 'Conflicting relationships',
    description: 'Detect conflicting relationships' )

  soft_validate(
    :sv_validate_disjoint_object,
    set: :validate_disjoint_object,
    name: 'Conflicting object taxon',
    description: 'Object taxon has a status conflicting with the relationship' )

  soft_validate(
    :sv_validate_disjoint_subject,
    set: :validate_disjoint_subject,
    name: 'Conflicting subject taxon',
    description: 'Subject taxon has a status conflicting with the relationship' )

  soft_validate(
    :sv_specific_relationship,
    set: :specific_relationship,
    name: 'validate relationship',
    description: 'Validate integrity of the relationship, for example, the year applicability range' )

  soft_validate(
    :sv_objective_synonym_relationship,
    set: :objective_synonym_relationship,
    fix: :sv_fix_objective_synonym_relationship,
    name: 'Objective synonym relationship',
    description: 'Objective synonyms should have the same type' )

  soft_validate(
    :sv_synonym_relationship,
    set: :synonym_relationship,
    name: 'Synonym relationship',
    description: 'Validate integrity of synonym relationship' )

  soft_validate(
    :sv_not_specific_relationship,
    set: :not_specific_relationship,
    fix: :sv_fix_not_specific_relationship,
    name: 'Not specific relationship',
    description: 'More specific relationship is preferred, for example "Subjective synonym" instead of "Synonym".' )

  soft_validate(
    :sv_synonym_linked_to_valid_name,
    set: :synonym_linked_to_valid_name,
    fix: :sv_fix_subject_parent_update,
    name: 'Synonym not linked to valid taxon',
    description: 'Synonyms should be linked to valid taxon.' )

  soft_validate(
    :sv_validate_priority,
    set: :validate_priority,
    name: 'Priority validation',
    description: 'Junior synonym should be younger than senior synonym' )

  soft_validate(
    :sv_validate_seniority,
    set: :validate_seniority,
    name: 'Seniority validation',
    description: 'Of two synonyms described in the same paper, one described at a higher rank has a priority' )

  soft_validate(
    :sv_coordinated_taxa,
    set: :coordinated_taxa,
    fix: :sv_fix_coordinated_subject_taxa,
    name: 'Move relationship to coordinate taxon',
    description: 'Relationship should be moved to the lowest rank coordinate taxon (for example from species to nomynotypical subspecies). It could be updated automatically with the Fix.' )

  soft_validate(
    :sv_coordinated_taxa_object,
    set: :coordinated_taxa,
    fix: :sv_fix_coordinated_object_taxa,
    name: 'Move object relationship to coordinate taxon',
    description: 'Relationship should be moved to the lowest rank coordinate object taxon (for example from species to nomynotypical subspecies). It could be updated automatically with the Fix.')

  scope :where_subject_is_taxon_name, -> (taxon_name) {where(subject_taxon_name_id: taxon_name)}
  scope :where_object_is_taxon_name, -> (taxon_name) {where(object_taxon_name_id: taxon_name)}
  scope :where_object_in_taxon_names, -> (taxon_name_array) {where('"taxon_name_relationships"."object_taxon_name_id" IN (?)', taxon_name_array)}

  scope :with_type_string, -> (type_string) { where(sanitize_sql_array(["taxon_name_relationships.type = '%s'", type_string])) }

  scope :with_type_base, -> (base_string) {where('"taxon_name_relationships"."type" LIKE ?', "#{base_string}%")}
  scope :with_type_contains, -> (base_string) {where('"taxon_name_relationships"."type" LIKE ?', "%#{base_string}%")}

  scope :with_two_type_bases, -> (base_string1, base_string2) {
    where('taxon_name_relationships.type LIKE ? OR taxon_name_relationships.type LIKE ?', "#{base_string1}%", "#{base_string2}%") }

  scope :homonym_or_suppressed, -> {where("taxon_name_relationships.type LIKE 'TaxonNameRelationship::Iczn::Invalidating::Homonym%' OR taxon_name_relationships.type LIKE 'TaxonNameRelationship::Iczn::Invalidating::Suppression::Total'") }
  scope :with_type_array, -> (base_array) {where('taxon_name_relationships.type IN (?)', base_array ) }

  def dwc_occurrences
    DwcOccurrence
      .joins("JOIN collection_objects co on dwc_occurrence_object_id = co.id AND dwc_occurrence_object_type = 'CollectionObject'")
      .joins("JOIN taxon_determinations td on co.id = td.taxon_determination_object_id AND td.taxon_determination_object_type = 'CollectionObject'")
      .joins("JOIN otus o on o.id = td.otu_id")
      .where(o: {taxon_name_id: [subject_taxon_name_id, object_taxon_name_id]})
      .distinct
  end

  # @return [Array of TaxonNameClassification]
  #  the inferable TaxonNameClassification(s) added to the subject when this relationship is used
  #  !! Not implemented
  def subject_properties
    []
  end

  # @return [Array of TaxonNameClassification]
  #  the inferable TaxonNameClassification(s) added to the subject when this relationship is used
  #  !! Not implmented
  def object_properties
    []
  end

  # @return class
  #   this method calls Module#module_parent
  def self.parent
    self.module_parent
  end

  # @return [Array of NomenclatureRank]
  #   the valid ranks to which the subject name can belong, set in subclasses. (left side)
  def self.valid_subject_ranks
    []
  end

  # @return [Array of NomenclatureRank]
  #   the valid ranks to which the object name can belong, set in subclasses. (right side)
  def self.valid_object_ranks
    []
  end

  # @return [Array of TaxonNameRelationships]
  #   if this relationships is set for the subject, then others in this array should not be used for that subject
  def self.disjoint_taxon_name_relationships
    []
  end

  # TODO: why isn't this disjoint?
  # disjoint relationships for the taxon as a object
  def self.required_taxon_name_relationships
    []
  end

  def self.disjoint_subject_classes
    []
  end

  def self.disjoint_object_classes
    []
  end

  def self.gbif_status_of_subject
    nil
  end

  def self.gbif_status_of_object
    nil
  end

  def self.assignable
    false
  end

  # @return [Symbol]
  #   determine the relative age of subject and object
  #   :direct - subject is younger than object
  #   :reverse - object is younger than subject
  def self.nomenclatural_priority
    nil
  end

  # @return [String]
  #    the status inferred by the relationship to the object name
  def object_status
    self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
  end

  # @return [String]
  #    the status inferred by the relationship to the subject name
  def subject_status
    self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
  end

  # @return [String]
  #    the connecting word in the relationship from the subject name to object name
  def subject_status_connector_to_object
    ' of'
  end

  # @return [String]
  #    the connecting word in the relationship from the object name to subject name
  def object_status_connector_to_subject
    ' of'
  end

  # @return [String]
  #   a readable fragement combining status and connector
  def subject_status_tag
    subject_status + subject_status_connector_to_object
  end

  # @return [String]
  #   a readable fragement combining status and connector
  def object_status_tag
    object_status + object_status_connector_to_subject
  end

  # @return [String, nil]
  #   the type of this relationship, IF the type is a valid name, else nil
  def type_name
    r = self.type
    TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r : nil
  end

  def type_class=(value)
    write_attribute(:type, value.to_s)
  end

  def type_class
    r = read_attribute(:type).to_s
    TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r.safe_constantize : nil
  end

  # @return [String, nil]
  #   the NOMEN uri for this type
  def self.nomen_uri
    const_defined?(:NOMEN_URI, false) ? self::NOMEN_URI : nil
  end

  # @return [Time]
  #   effective date of publication, used to determine nomenclatural priorities
  #   !! Careful, if no date is present the current year is given, rather than nil, @proceps is this a safe inference?
  def nomenclature_date
    self.source ? (self.source.cached_nomenclature_date ? self.source.cached_nomenclature_date.to_time : Time.current) : Time.current
  end

  def is_combination?
    !!/TaxonNameRelationship::(OriginalCombination|Combination)/.match(self.type.to_s)
  end

  protected

  def subject_and_object_in_same_project
    if subject_taxon_name && object_taxon_name
      if subject_taxon_name.project_id != object_taxon_name.project_id
        errors.add(:base, 'one name is not in the same project as the other')
      end
    end
  end

  def validate_type
    # TODO: Remove, handled by STI
    if type && !TAXON_NAME_RELATIONSHIP_NAMES.include?(type.to_s)
      errors.add(:type, "'#{type}' is not a valid taxon name relationship")
    elsif self.type_class && object_taxon_name.class.to_s == 'Protonym' && !self.type_class.valid_object_ranks.include?(object_taxon_name.rank_string)
      errors.add(:type, "'#{type}' is not a valid taxon name relationship")
    end

    if object_taxon_name.class.to_s == 'Protonym' || object_taxon_name.class.to_s == 'Hybrid'
      errors.add(:type, "'#{type}' is not a valid taxon name relationship") if /TaxonNameRelationship::Combination::/.match(self.type)
    end

    if object_taxon_name.class.to_s == 'Combination'
      errors.add(:type, "'#{type}' is not a valid taxon name relationship") unless /TaxonNameRelationship::Combination::/.match(self.type)
    end
  end

  # @todo validate, that all the relationships in the table could be linked to relationships in classes (if those had changed)

  def validate_subject_and_object_share_code
    if object_taxon_name.type  == 'Protonym' && subject_taxon_name.type == 'Protonym'
      errors.add(:object_taxon_name_id, 'The related taxon is not in the same monenclatural group (ICZN, ICN, ICNP, ICVCN') if subject_taxon_name.rank_class.try(:nomenclatural_code) != object_taxon_name.rank_class.try(:nomenclatural_code)
    end
  end

  def validate_subject_and_object_are_not_identical
    if !self.object_taxon_name_id.nil? && self.object_taxon_name == self.subject_taxon_name
      errors.add(:object_taxon_name_id, "#{self.object_taxon_name.try(:cached_html)} should not refer to itself") unless self.type =~ /OriginalCombination/
    end
  end

  def validate_object_must_equal_subject_for_uncertain_placement
    if self.object_taxon_name_id != self.subject_taxon_name.parent_id && self.type_name == 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      errors.add(:object_taxon_name_id, "The parent #{self.subject_taxon_name.parent.cached_html} and the Incertae Sedis placement (#{self.object_taxon_name.cached_html}) should match")
    end
  end

  def validate_subject_and_object_ranks
    tname = self.type_name

    if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      rank_group = self.subject_taxon_name.rank_class.try(:parent)
      unless rank_group == self.object_taxon_name.rank_class.try(:parent)
        errors.add(:object_taxon_name_id, "Rank of related taxon should be in the #{rank_group.try(:rank_name)} rank group, not #{self.object_taxon_name.rank_class.try(:rank_name)}")
      end
    end

    if self.type_class.present? # only validate if it is set
      if object_taxon_name && object_taxon_name.rank_class
        if object_taxon_name.type == 'Protonym' || object_taxon_name.type == 'Hybrid'
          unless self.type_class.valid_object_ranks.include?(self.object_taxon_name.rank_string)
            errors.add(:object_taxon_name_id, "#{self.object_taxon_name.rank_class.rank_name.capitalize} rank of #{self.object_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
            errors.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.object_taxon_name.rank_class.rank_name} rank of #{self.object_taxon_name.cached_html}")
          end
        end
      end

      if subject_taxon_name && subject_taxon_name.rank_class
        if subject_taxon_name.type == 'Protonym' || subject_taxon_name.type == 'Hybrid'
          unless self.type_class.valid_subject_ranks.include?(self.subject_taxon_name.rank_string)
            soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
            soft_validations.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.subject_taxon_name.rank_class.rank_name} rank of #{self.subject_taxon_name.cached_html}")
          end
        end
      end
    end
  end

  ##### Protonym historically could be listed as a synonym to different taxa
  #def validate_uniqueness_of_synonym_subject
  #  if !self.type.nil? && /Synonym/.match(self.type_name) && !TaxonNameRelationship.where(subject_taxon_name_id: self.subject_taxon_name_id).with_type_contains('Synonym').not_self(self).empty?
  #    errors.add(:subject_taxon_name_id, 'Only one synonym relationship is allowed')
  #  end
  #end

  def validate_uniqueness_of_typification_object
    if /Typification/.match(self.type_name) && !TaxonNameRelationship.where(object_taxon_name_id: self.object_taxon_name_id).with_type_contains('Typification').not_self(self).empty?
      errors.add(:object_taxon_name_id, 'Only one Type designation relationship is allowed')
    end
  end

  def validate_rank_group
    if self.type =~ /Hybrid/ && self.subject_taxon_name && self.object_taxon_name
      if self.subject_taxon_name.rank_class.parent != self.object_taxon_name.rank_class.parent
        errors.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the rank of hybrid (#{self.object_taxon_name.rank_class.rank_name})")
      end
    end
  end

  def validate_object_and_subject_both_protonyms
    if /TaxonNameRelationship::Combination::/.match(self.type)
      errors.add(:object_taxon_name_id, 'Not a Combination') if object_taxon_name.type != 'Combination'
    else
      errors.add(:object_taxon_name_id, 'Not a Protonym') if object_taxon_name.type == 'Combination'
    end
    errors.add(:subject_taxon_name_id, 'Not a Protonym') if subject_taxon_name.type == 'Combination' && self.type != 'TaxonNameRelationship::CurrentCombination'
  end

  def set_cached_names_for_taxon_names
    # !! only fire if subject_taxon_name changed
    return true unless subject_taxon_name_id_previously_changed? || destroyed?

    TaxonName.transaction do
      if is_invalidating?
        t = subject_taxon_name

        if type_name =~/Misspelling/
          t.update_column(:cached_misspelling, t.get_cached_misspelling)
          t.update_columns(
              cached_author_year: t.get_author_and_year,
              cached_nomenclature_date: t.nomenclature_date,
              cached_original_combination: t.get_original_combination,
              cached_original_combination_html: t.get_original_combination_html)
        end

        if type_name =~/Misapplication/
          t.update_columns(
            cached_author_year: t.get_author_and_year,
            cached_nomenclature_date: t.nomenclature_date)
        end

        vn = t.get_valid_taxon_name

        # !! NO set cached should do this from TN side of things,
        # !! Not here

        n = t.get_full_name

        t.update_columns(
          cached: n,
          cached_html: t.get_full_name_html(n), # OK to force reload here, otherwise we need an exception in #set_cached
          cached_valid_taxon_name_id: vn.id,
          cached_is_valid: !t.unavailable_or_invalid?)

        t.combination_list_self.each do |c|
          c.update_column(:cached_valid_taxon_name_id, vn.id)
        end

        vn.list_of_invalid_taxon_names.each do |s|
          s.update_columns(
            cached_valid_taxon_name_id: vn.id,
            cached_is_valid: !s.unavailable_or_invalid?)

          s.combination_list_self.each do |c|
            c.update_column(:cached_valid_taxon_name_id, vn.id)
          end
        end

      end

    end

    true
  end

  def is_invalidating?
    TAXON_NAME_RELATIONSHIP_NAMES_INVALID.include?(type_name)
  end

  def sv_validate_required_relationships
    return true if self.subject_taxon_name.not_binominal?
    object_relationships = TaxonNameRelationship.where_object_is_taxon_name(self.object_taxon_name).not_self(self).collect{|r| r.type}
    required = self.type_class.required_taxon_name_relationships - object_relationships
    required.each do |r|
      soft_validations.add(:type, " Presence of #{self.subject_status} requires selection of #{r.demodulize.underscore.humanize.downcase}")
    end
  end

  def sv_validate_disjoint_relationships
    tname = self.type_name
    if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      subject_relationships = TaxonNameRelationship.where_subject_is_taxon_name(self.subject_taxon_name).not_self(self)
      subject_relationships.each  do |i|
        if self.type_class.disjoint_taxon_name_relationships.include?(i.type_name)
          soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with another relationship: '#{i.subject_status}'")
        end
      end
    end
  end

  def sv_validate_disjoint_object
    classifications = self.object_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
    disjoint_object_classes = self.type_class.disjoint_object_classes
    compare = disjoint_object_classes & classifications
    compare.each do |i|
      c = i.demodulize.underscore.humanize.downcase
      soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with the taxon status: '#{c}'")
      soft_validations.add(:object_taxon_name_id, "#{self.object_taxon_name.cached_html} has a conflicting status: '#{c}'")
    end
  end

  def sv_validate_disjoint_subject
    classifications = self.subject_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
    disjoint_subject_classes = self.type_class.disjoint_subject_classes
    compare = disjoint_subject_classes & classifications
    compare.each do |i|
      c = i.demodulize.underscore.humanize.downcase
      soft_validations.add(:type, "#{self.subject_status.capitalize} conflicting with the status: '#{c}'")
      soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.cached_html} has a conflicting status: '#{c}'")
    end
  end

  def sv_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_objective_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_fix_objective_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_not_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_fix_not_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_synonym_linked_to_valid_name
    #synonyms and misspellings should be linked to valid names
    if ::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
      obj = self.object_taxon_name
      subj = self.subject_taxon_name
      if subj.rank_class.try(:nomenclatural_code) == :iczn && (obj.parent_id != subj.parent_id || obj.rank_class != subj.rank_class) &&  subj.cached_valid_taxon_name_id == obj.cached_valid_taxon_name_id
        soft_validations.add(:subject_taxon_name_id, "#{self.subject_status.capitalize}  #{subj.cached_html_name_and_author_year} should have the same parent and rank with  #{obj.cached_html_name_and_author_year}",
                             success_message: 'The parent was updated', failure_message:  'The parent was not updated')
      end
    end
  end

  def sv_fix_subject_parent_update
    res = false
    if TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
      obj = self.object_taxon_name
      subj = self.subject_taxon_name
      unless obj.parent_id == subj.parent_id
        subj.parent_id = obj.parent_id
        subj.rank_class = obj.rank_class
        begin
          TaxonName.transaction do
            subj.save!
            res = true
          end
        rescue
        end
      end
    end
    res
  end

  def subject_invalid_statuses
    TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & self.subject_taxon_name.taxon_name_classifications.collect{|c| c.type_class.to_s}
  end

  def sv_validate_priority
    true # all validations moved to subclasses
  end

  def sv_validate_seniority
    true # all validations moved to subclasses
  end

  def sv_coordinated_taxa
    s = subject_taxon_name
    o = object_taxon_name
    s_new = s.lowest_rank_coordinated_taxon
    if s != s_new
      soft_validations.add(:subject_taxon_name_id, "Relationship should move from #{s.rank_class.rank_name} #{s.cached_html} to #{s_new.rank_class.rank_name} #{s_new.cached_html}",
                           success_message: "Relationship moved to  #{s_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
    end
  end

  def sv_coordinated_taxa_object
    s = subject_taxon_name
    o = object_taxon_name
    o_new = o.lowest_rank_coordinated_taxon
    if o != o_new
      soft_validations.add(:object_taxon_name_id, "Relationship should move from #{o.rank_class.rank_name} #{o.cached_html} to #{o_new.rank_class.rank_name} #{o_new.cached_html}",
                           success_message: "Relationship moved to  #{o_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
    end
  end

  def sv_fix_coordinated_subject_taxa
    s = subject_taxon_name
    s_new = s.lowest_rank_coordinated_taxon
    if s != s_new
      self.subject_taxon_name = s_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def sv_fix_coordinated_object_taxa
    o = self.object_taxon_name
    o_new = o.lowest_rank_coordinated_taxon
    if o != o_new
      self.object_taxon_name = o_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def sv_fix_combination_relationship
    s = self.subject_taxon_name
    list = s.list_of_coordinated_names + [s]
    if s.rank_string =~ /Species/
      s_new = list.detect{|t| t.rank_class.rank_name == 'species'}
    elsif s.rank_string =~ /Genus/
      s_new = list.detect{|t| t.rank_class.rank_name == 'genus'}
    else
      s_new = s
    end
    if s != s_new && !s.nil?
      self.subject_taxon_name = s_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def self.collect_to_s(*args)
    args.collect{|arg| arg.to_s}
  end

  def self.collect_descendants_to_s(*classes)
    ans = []
    classes.each do |klass|
      ans += klass.descendants.collect{|k| k.to_s}
    end
    ans
  end

  def self.collect_descendants_and_itself_to_s(*classes)
    classes.collect{|k| k.to_s} + self.collect_descendants_to_s(*classes)
  end

  # Force loading all descendants as soon as this class is referenced
  Dir.glob("#{Rails.root.join("app/models/taxon_name_relationship/**/*.rb")}")
    .sort { |a, b| a.split('/').count <=> b.split('/').count }
    .map { |p| p.split('/app/models/').last.sub(/\.rb$/, '') }
    .map { |p| p.split('/') }
    .map { |c| c.map { |n| ActiveSupport::Inflector.camelize(n) } }
    .map { |c| c.join('::') }.map(&:constantize)
end

#project_idInteger

the project ID

Returns:

  • (Integer)


44
45
46
47
48
49
50
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
140
141
142
143
144
145
146
147
148
149
150
151
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
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
219
220
221
222
223
224
225
226
227
228
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
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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
357
358
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'app/models/taxon_name_relationship.rb', line 44

class TaxonNameRelationship < ApplicationRecord
  include Housekeeping
  include Shared::Citations
  include Shared::Notes
  include SoftValidation
  include Shared::DwcOccurrenceHooks
  include Shared::IsData

  # @return [Boolean, nil]
  #   When true, cached values are not built
  attr_accessor :no_cached

  belongs_to :subject_taxon_name, class_name: 'TaxonName', inverse_of: :taxon_name_relationships # left side
  belongs_to :object_taxon_name, class_name: 'TaxonName', inverse_of: :related_taxon_name_relationships # right side

  # !! Keep as after_commit unless you are wanting to spend a lot of time
  # !! refactoring tests
  after_commit :set_cached_names_for_taxon_names, unless: -> {self.no_cached || destroyed?}
  after_destroy :set_cached_names_for_taxon_names, unless: -> {self.no_cached}

  # TODO: remove, it's required by STI
  validates_presence_of :type, message: 'Relationship type should be specified'
  validates_presence_of :subject_taxon_name, message: 'Missing taxon name on the left side'
  validates_presence_of :object_taxon_name, message: 'Missing taxon name on the right side'
  validates_uniqueness_of :object_taxon_name_id, scope: [:type, :project_id], if: :is_combination?
  validates_uniqueness_of :object_taxon_name_id, scope: [:type, :subject_taxon_name_id, :project_id], unless: :is_combination?

  validate :validate_type, :validate_subject_and_object_are_not_identical
  validate :subject_and_object_in_same_project

  with_options unless: -> {!subject_taxon_name || !object_taxon_name} do
    validate :validate_subject_and_object_share_code,
      :validate_uniqueness_of_typification_object,
      #:validate_uniqueness_of_synonym_subject,
      :validate_object_and_subject_both_protonyms,
      :validate_object_must_equal_subject_for_uncertain_placement,
      :validate_subject_and_object_ranks,
      :validate_rank_group
  end

  # TODO: isolate to an include file sensu protonym
  soft_validate(
    :sv_validate_required_relationships,
    set: :validate_required_relationships,
    name: 'Required relationships',
    description: 'Required relationships' )

  soft_validate(
    :sv_validate_disjoint_relationships,
    set: :validate_disjoint_relationships,
    name: 'Conflicting relationships',
    description: 'Detect conflicting relationships' )

  soft_validate(
    :sv_validate_disjoint_object,
    set: :validate_disjoint_object,
    name: 'Conflicting object taxon',
    description: 'Object taxon has a status conflicting with the relationship' )

  soft_validate(
    :sv_validate_disjoint_subject,
    set: :validate_disjoint_subject,
    name: 'Conflicting subject taxon',
    description: 'Subject taxon has a status conflicting with the relationship' )

  soft_validate(
    :sv_specific_relationship,
    set: :specific_relationship,
    name: 'validate relationship',
    description: 'Validate integrity of the relationship, for example, the year applicability range' )

  soft_validate(
    :sv_objective_synonym_relationship,
    set: :objective_synonym_relationship,
    fix: :sv_fix_objective_synonym_relationship,
    name: 'Objective synonym relationship',
    description: 'Objective synonyms should have the same type' )

  soft_validate(
    :sv_synonym_relationship,
    set: :synonym_relationship,
    name: 'Synonym relationship',
    description: 'Validate integrity of synonym relationship' )

  soft_validate(
    :sv_not_specific_relationship,
    set: :not_specific_relationship,
    fix: :sv_fix_not_specific_relationship,
    name: 'Not specific relationship',
    description: 'More specific relationship is preferred, for example "Subjective synonym" instead of "Synonym".' )

  soft_validate(
    :sv_synonym_linked_to_valid_name,
    set: :synonym_linked_to_valid_name,
    fix: :sv_fix_subject_parent_update,
    name: 'Synonym not linked to valid taxon',
    description: 'Synonyms should be linked to valid taxon.' )

  soft_validate(
    :sv_validate_priority,
    set: :validate_priority,
    name: 'Priority validation',
    description: 'Junior synonym should be younger than senior synonym' )

  soft_validate(
    :sv_validate_seniority,
    set: :validate_seniority,
    name: 'Seniority validation',
    description: 'Of two synonyms described in the same paper, one described at a higher rank has a priority' )

  soft_validate(
    :sv_coordinated_taxa,
    set: :coordinated_taxa,
    fix: :sv_fix_coordinated_subject_taxa,
    name: 'Move relationship to coordinate taxon',
    description: 'Relationship should be moved to the lowest rank coordinate taxon (for example from species to nomynotypical subspecies). It could be updated automatically with the Fix.' )

  soft_validate(
    :sv_coordinated_taxa_object,
    set: :coordinated_taxa,
    fix: :sv_fix_coordinated_object_taxa,
    name: 'Move object relationship to coordinate taxon',
    description: 'Relationship should be moved to the lowest rank coordinate object taxon (for example from species to nomynotypical subspecies). It could be updated automatically with the Fix.')

  scope :where_subject_is_taxon_name, -> (taxon_name) {where(subject_taxon_name_id: taxon_name)}
  scope :where_object_is_taxon_name, -> (taxon_name) {where(object_taxon_name_id: taxon_name)}
  scope :where_object_in_taxon_names, -> (taxon_name_array) {where('"taxon_name_relationships"."object_taxon_name_id" IN (?)', taxon_name_array)}

  scope :with_type_string, -> (type_string) { where(sanitize_sql_array(["taxon_name_relationships.type = '%s'", type_string])) }

  scope :with_type_base, -> (base_string) {where('"taxon_name_relationships"."type" LIKE ?', "#{base_string}%")}
  scope :with_type_contains, -> (base_string) {where('"taxon_name_relationships"."type" LIKE ?', "%#{base_string}%")}

  scope :with_two_type_bases, -> (base_string1, base_string2) {
    where('taxon_name_relationships.type LIKE ? OR taxon_name_relationships.type LIKE ?', "#{base_string1}%", "#{base_string2}%") }

  scope :homonym_or_suppressed, -> {where("taxon_name_relationships.type LIKE 'TaxonNameRelationship::Iczn::Invalidating::Homonym%' OR taxon_name_relationships.type LIKE 'TaxonNameRelationship::Iczn::Invalidating::Suppression::Total'") }
  scope :with_type_array, -> (base_array) {where('taxon_name_relationships.type IN (?)', base_array ) }

  def dwc_occurrences
    DwcOccurrence
      .joins("JOIN collection_objects co on dwc_occurrence_object_id = co.id AND dwc_occurrence_object_type = 'CollectionObject'")
      .joins("JOIN taxon_determinations td on co.id = td.taxon_determination_object_id AND td.taxon_determination_object_type = 'CollectionObject'")
      .joins("JOIN otus o on o.id = td.otu_id")
      .where(o: {taxon_name_id: [subject_taxon_name_id, object_taxon_name_id]})
      .distinct
  end

  # @return [Array of TaxonNameClassification]
  #  the inferable TaxonNameClassification(s) added to the subject when this relationship is used
  #  !! Not implemented
  def subject_properties
    []
  end

  # @return [Array of TaxonNameClassification]
  #  the inferable TaxonNameClassification(s) added to the subject when this relationship is used
  #  !! Not implmented
  def object_properties
    []
  end

  # @return class
  #   this method calls Module#module_parent
  def self.parent
    self.module_parent
  end

  # @return [Array of NomenclatureRank]
  #   the valid ranks to which the subject name can belong, set in subclasses. (left side)
  def self.valid_subject_ranks
    []
  end

  # @return [Array of NomenclatureRank]
  #   the valid ranks to which the object name can belong, set in subclasses. (right side)
  def self.valid_object_ranks
    []
  end

  # @return [Array of TaxonNameRelationships]
  #   if this relationships is set for the subject, then others in this array should not be used for that subject
  def self.disjoint_taxon_name_relationships
    []
  end

  # TODO: why isn't this disjoint?
  # disjoint relationships for the taxon as a object
  def self.required_taxon_name_relationships
    []
  end

  def self.disjoint_subject_classes
    []
  end

  def self.disjoint_object_classes
    []
  end

  def self.gbif_status_of_subject
    nil
  end

  def self.gbif_status_of_object
    nil
  end

  def self.assignable
    false
  end

  # @return [Symbol]
  #   determine the relative age of subject and object
  #   :direct - subject is younger than object
  #   :reverse - object is younger than subject
  def self.nomenclatural_priority
    nil
  end

  # @return [String]
  #    the status inferred by the relationship to the object name
  def object_status
    self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
  end

  # @return [String]
  #    the status inferred by the relationship to the subject name
  def subject_status
    self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
  end

  # @return [String]
  #    the connecting word in the relationship from the subject name to object name
  def subject_status_connector_to_object
    ' of'
  end

  # @return [String]
  #    the connecting word in the relationship from the object name to subject name
  def object_status_connector_to_subject
    ' of'
  end

  # @return [String]
  #   a readable fragement combining status and connector
  def subject_status_tag
    subject_status + subject_status_connector_to_object
  end

  # @return [String]
  #   a readable fragement combining status and connector
  def object_status_tag
    object_status + object_status_connector_to_subject
  end

  # @return [String, nil]
  #   the type of this relationship, IF the type is a valid name, else nil
  def type_name
    r = self.type
    TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r : nil
  end

  def type_class=(value)
    write_attribute(:type, value.to_s)
  end

  def type_class
    r = read_attribute(:type).to_s
    TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r.safe_constantize : nil
  end

  # @return [String, nil]
  #   the NOMEN uri for this type
  def self.nomen_uri
    const_defined?(:NOMEN_URI, false) ? self::NOMEN_URI : nil
  end

  # @return [Time]
  #   effective date of publication, used to determine nomenclatural priorities
  #   !! Careful, if no date is present the current year is given, rather than nil, @proceps is this a safe inference?
  def nomenclature_date
    self.source ? (self.source.cached_nomenclature_date ? self.source.cached_nomenclature_date.to_time : Time.current) : Time.current
  end

  def is_combination?
    !!/TaxonNameRelationship::(OriginalCombination|Combination)/.match(self.type.to_s)
  end

  protected

  def subject_and_object_in_same_project
    if subject_taxon_name && object_taxon_name
      if subject_taxon_name.project_id != object_taxon_name.project_id
        errors.add(:base, 'one name is not in the same project as the other')
      end
    end
  end

  def validate_type
    # TODO: Remove, handled by STI
    if type && !TAXON_NAME_RELATIONSHIP_NAMES.include?(type.to_s)
      errors.add(:type, "'#{type}' is not a valid taxon name relationship")
    elsif self.type_class && object_taxon_name.class.to_s == 'Protonym' && !self.type_class.valid_object_ranks.include?(object_taxon_name.rank_string)
      errors.add(:type, "'#{type}' is not a valid taxon name relationship")
    end

    if object_taxon_name.class.to_s == 'Protonym' || object_taxon_name.class.to_s == 'Hybrid'
      errors.add(:type, "'#{type}' is not a valid taxon name relationship") if /TaxonNameRelationship::Combination::/.match(self.type)
    end

    if object_taxon_name.class.to_s == 'Combination'
      errors.add(:type, "'#{type}' is not a valid taxon name relationship") unless /TaxonNameRelationship::Combination::/.match(self.type)
    end
  end

  # @todo validate, that all the relationships in the table could be linked to relationships in classes (if those had changed)

  def validate_subject_and_object_share_code
    if object_taxon_name.type  == 'Protonym' && subject_taxon_name.type == 'Protonym'
      errors.add(:object_taxon_name_id, 'The related taxon is not in the same monenclatural group (ICZN, ICN, ICNP, ICVCN') if subject_taxon_name.rank_class.try(:nomenclatural_code) != object_taxon_name.rank_class.try(:nomenclatural_code)
    end
  end

  def validate_subject_and_object_are_not_identical
    if !self.object_taxon_name_id.nil? && self.object_taxon_name == self.subject_taxon_name
      errors.add(:object_taxon_name_id, "#{self.object_taxon_name.try(:cached_html)} should not refer to itself") unless self.type =~ /OriginalCombination/
    end
  end

  def validate_object_must_equal_subject_for_uncertain_placement
    if self.object_taxon_name_id != self.subject_taxon_name.parent_id && self.type_name == 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      errors.add(:object_taxon_name_id, "The parent #{self.subject_taxon_name.parent.cached_html} and the Incertae Sedis placement (#{self.object_taxon_name.cached_html}) should match")
    end
  end

  def validate_subject_and_object_ranks
    tname = self.type_name

    if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      rank_group = self.subject_taxon_name.rank_class.try(:parent)
      unless rank_group == self.object_taxon_name.rank_class.try(:parent)
        errors.add(:object_taxon_name_id, "Rank of related taxon should be in the #{rank_group.try(:rank_name)} rank group, not #{self.object_taxon_name.rank_class.try(:rank_name)}")
      end
    end

    if self.type_class.present? # only validate if it is set
      if object_taxon_name && object_taxon_name.rank_class
        if object_taxon_name.type == 'Protonym' || object_taxon_name.type == 'Hybrid'
          unless self.type_class.valid_object_ranks.include?(self.object_taxon_name.rank_string)
            errors.add(:object_taxon_name_id, "#{self.object_taxon_name.rank_class.rank_name.capitalize} rank of #{self.object_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
            errors.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.object_taxon_name.rank_class.rank_name} rank of #{self.object_taxon_name.cached_html}")
          end
        end
      end

      if subject_taxon_name && subject_taxon_name.rank_class
        if subject_taxon_name.type == 'Protonym' || subject_taxon_name.type == 'Hybrid'
          unless self.type_class.valid_subject_ranks.include?(self.subject_taxon_name.rank_string)
            soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
            soft_validations.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.subject_taxon_name.rank_class.rank_name} rank of #{self.subject_taxon_name.cached_html}")
          end
        end
      end
    end
  end

  ##### Protonym historically could be listed as a synonym to different taxa
  #def validate_uniqueness_of_synonym_subject
  #  if !self.type.nil? && /Synonym/.match(self.type_name) && !TaxonNameRelationship.where(subject_taxon_name_id: self.subject_taxon_name_id).with_type_contains('Synonym').not_self(self).empty?
  #    errors.add(:subject_taxon_name_id, 'Only one synonym relationship is allowed')
  #  end
  #end

  def validate_uniqueness_of_typification_object
    if /Typification/.match(self.type_name) && !TaxonNameRelationship.where(object_taxon_name_id: self.object_taxon_name_id).with_type_contains('Typification').not_self(self).empty?
      errors.add(:object_taxon_name_id, 'Only one Type designation relationship is allowed')
    end
  end

  def validate_rank_group
    if self.type =~ /Hybrid/ && self.subject_taxon_name && self.object_taxon_name
      if self.subject_taxon_name.rank_class.parent != self.object_taxon_name.rank_class.parent
        errors.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the rank of hybrid (#{self.object_taxon_name.rank_class.rank_name})")
      end
    end
  end

  def validate_object_and_subject_both_protonyms
    if /TaxonNameRelationship::Combination::/.match(self.type)
      errors.add(:object_taxon_name_id, 'Not a Combination') if object_taxon_name.type != 'Combination'
    else
      errors.add(:object_taxon_name_id, 'Not a Protonym') if object_taxon_name.type == 'Combination'
    end
    errors.add(:subject_taxon_name_id, 'Not a Protonym') if subject_taxon_name.type == 'Combination' && self.type != 'TaxonNameRelationship::CurrentCombination'
  end

  def set_cached_names_for_taxon_names
    # !! only fire if subject_taxon_name changed
    return true unless subject_taxon_name_id_previously_changed? || destroyed?

    TaxonName.transaction do
      if is_invalidating?
        t = subject_taxon_name

        if type_name =~/Misspelling/
          t.update_column(:cached_misspelling, t.get_cached_misspelling)
          t.update_columns(
              cached_author_year: t.get_author_and_year,
              cached_nomenclature_date: t.nomenclature_date,
              cached_original_combination: t.get_original_combination,
              cached_original_combination_html: t.get_original_combination_html)
        end

        if type_name =~/Misapplication/
          t.update_columns(
            cached_author_year: t.get_author_and_year,
            cached_nomenclature_date: t.nomenclature_date)
        end

        vn = t.get_valid_taxon_name

        # !! NO set cached should do this from TN side of things,
        # !! Not here

        n = t.get_full_name

        t.update_columns(
          cached: n,
          cached_html: t.get_full_name_html(n), # OK to force reload here, otherwise we need an exception in #set_cached
          cached_valid_taxon_name_id: vn.id,
          cached_is_valid: !t.unavailable_or_invalid?)

        t.combination_list_self.each do |c|
          c.update_column(:cached_valid_taxon_name_id, vn.id)
        end

        vn.list_of_invalid_taxon_names.each do |s|
          s.update_columns(
            cached_valid_taxon_name_id: vn.id,
            cached_is_valid: !s.unavailable_or_invalid?)

          s.combination_list_self.each do |c|
            c.update_column(:cached_valid_taxon_name_id, vn.id)
          end
        end

      end

    end

    true
  end

  def is_invalidating?
    TAXON_NAME_RELATIONSHIP_NAMES_INVALID.include?(type_name)
  end

  def sv_validate_required_relationships
    return true if self.subject_taxon_name.not_binominal?
    object_relationships = TaxonNameRelationship.where_object_is_taxon_name(self.object_taxon_name).not_self(self).collect{|r| r.type}
    required = self.type_class.required_taxon_name_relationships - object_relationships
    required.each do |r|
      soft_validations.add(:type, " Presence of #{self.subject_status} requires selection of #{r.demodulize.underscore.humanize.downcase}")
    end
  end

  def sv_validate_disjoint_relationships
    tname = self.type_name
    if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      subject_relationships = TaxonNameRelationship.where_subject_is_taxon_name(self.subject_taxon_name).not_self(self)
      subject_relationships.each  do |i|
        if self.type_class.disjoint_taxon_name_relationships.include?(i.type_name)
          soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with another relationship: '#{i.subject_status}'")
        end
      end
    end
  end

  def sv_validate_disjoint_object
    classifications = self.object_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
    disjoint_object_classes = self.type_class.disjoint_object_classes
    compare = disjoint_object_classes & classifications
    compare.each do |i|
      c = i.demodulize.underscore.humanize.downcase
      soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with the taxon status: '#{c}'")
      soft_validations.add(:object_taxon_name_id, "#{self.object_taxon_name.cached_html} has a conflicting status: '#{c}'")
    end
  end

  def sv_validate_disjoint_subject
    classifications = self.subject_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
    disjoint_subject_classes = self.type_class.disjoint_subject_classes
    compare = disjoint_subject_classes & classifications
    compare.each do |i|
      c = i.demodulize.underscore.humanize.downcase
      soft_validations.add(:type, "#{self.subject_status.capitalize} conflicting with the status: '#{c}'")
      soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.cached_html} has a conflicting status: '#{c}'")
    end
  end

  def sv_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_objective_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_fix_objective_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_not_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_fix_not_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_synonym_linked_to_valid_name
    #synonyms and misspellings should be linked to valid names
    if ::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
      obj = self.object_taxon_name
      subj = self.subject_taxon_name
      if subj.rank_class.try(:nomenclatural_code) == :iczn && (obj.parent_id != subj.parent_id || obj.rank_class != subj.rank_class) &&  subj.cached_valid_taxon_name_id == obj.cached_valid_taxon_name_id
        soft_validations.add(:subject_taxon_name_id, "#{self.subject_status.capitalize}  #{subj.cached_html_name_and_author_year} should have the same parent and rank with  #{obj.cached_html_name_and_author_year}",
                             success_message: 'The parent was updated', failure_message:  'The parent was not updated')
      end
    end
  end

  def sv_fix_subject_parent_update
    res = false
    if TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
      obj = self.object_taxon_name
      subj = self.subject_taxon_name
      unless obj.parent_id == subj.parent_id
        subj.parent_id = obj.parent_id
        subj.rank_class = obj.rank_class
        begin
          TaxonName.transaction do
            subj.save!
            res = true
          end
        rescue
        end
      end
    end
    res
  end

  def subject_invalid_statuses
    TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & self.subject_taxon_name.taxon_name_classifications.collect{|c| c.type_class.to_s}
  end

  def sv_validate_priority
    true # all validations moved to subclasses
  end

  def sv_validate_seniority
    true # all validations moved to subclasses
  end

  def sv_coordinated_taxa
    s = subject_taxon_name
    o = object_taxon_name
    s_new = s.lowest_rank_coordinated_taxon
    if s != s_new
      soft_validations.add(:subject_taxon_name_id, "Relationship should move from #{s.rank_class.rank_name} #{s.cached_html} to #{s_new.rank_class.rank_name} #{s_new.cached_html}",
                           success_message: "Relationship moved to  #{s_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
    end
  end

  def sv_coordinated_taxa_object
    s = subject_taxon_name
    o = object_taxon_name
    o_new = o.lowest_rank_coordinated_taxon
    if o != o_new
      soft_validations.add(:object_taxon_name_id, "Relationship should move from #{o.rank_class.rank_name} #{o.cached_html} to #{o_new.rank_class.rank_name} #{o_new.cached_html}",
                           success_message: "Relationship moved to  #{o_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
    end
  end

  def sv_fix_coordinated_subject_taxa
    s = subject_taxon_name
    s_new = s.lowest_rank_coordinated_taxon
    if s != s_new
      self.subject_taxon_name = s_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def sv_fix_coordinated_object_taxa
    o = self.object_taxon_name
    o_new = o.lowest_rank_coordinated_taxon
    if o != o_new
      self.object_taxon_name = o_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def sv_fix_combination_relationship
    s = self.subject_taxon_name
    list = s.list_of_coordinated_names + [s]
    if s.rank_string =~ /Species/
      s_new = list.detect{|t| t.rank_class.rank_name == 'species'}
    elsif s.rank_string =~ /Genus/
      s_new = list.detect{|t| t.rank_class.rank_name == 'genus'}
    else
      s_new = s
    end
    if s != s_new && !s.nil?
      self.subject_taxon_name = s_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def self.collect_to_s(*args)
    args.collect{|arg| arg.to_s}
  end

  def self.collect_descendants_to_s(*classes)
    ans = []
    classes.each do |klass|
      ans += klass.descendants.collect{|k| k.to_s}
    end
    ans
  end

  def self.collect_descendants_and_itself_to_s(*classes)
    classes.collect{|k| k.to_s} + self.collect_descendants_to_s(*classes)
  end

  # Force loading all descendants as soon as this class is referenced
  Dir.glob("#{Rails.root.join("app/models/taxon_name_relationship/**/*.rb")}")
    .sort { |a, b| a.split('/').count <=> b.split('/').count }
    .map { |p| p.split('/app/models/').last.sub(/\.rb$/, '') }
    .map { |p| p.split('/') }
    .map { |c| c.map { |n| ActiveSupport::Inflector.camelize(n) } }
    .map { |c| c.join('::') }.map(&:constantize)
end

#subject_taxon_name_idInteger

Returns the subject taxon name.

Returns:

  • (Integer)

    the subject taxon name



44
45
46
47
48
49
50
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
140
141
142
143
144
145
146
147
148
149
150
151
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
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
219
220
221
222
223
224
225
226
227
228
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
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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
357
358
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'app/models/taxon_name_relationship.rb', line 44

class TaxonNameRelationship < ApplicationRecord
  include Housekeeping
  include Shared::Citations
  include Shared::Notes
  include SoftValidation
  include Shared::DwcOccurrenceHooks
  include Shared::IsData

  # @return [Boolean, nil]
  #   When true, cached values are not built
  attr_accessor :no_cached

  belongs_to :subject_taxon_name, class_name: 'TaxonName', inverse_of: :taxon_name_relationships # left side
  belongs_to :object_taxon_name, class_name: 'TaxonName', inverse_of: :related_taxon_name_relationships # right side

  # !! Keep as after_commit unless you are wanting to spend a lot of time
  # !! refactoring tests
  after_commit :set_cached_names_for_taxon_names, unless: -> {self.no_cached || destroyed?}
  after_destroy :set_cached_names_for_taxon_names, unless: -> {self.no_cached}

  # TODO: remove, it's required by STI
  validates_presence_of :type, message: 'Relationship type should be specified'
  validates_presence_of :subject_taxon_name, message: 'Missing taxon name on the left side'
  validates_presence_of :object_taxon_name, message: 'Missing taxon name on the right side'
  validates_uniqueness_of :object_taxon_name_id, scope: [:type, :project_id], if: :is_combination?
  validates_uniqueness_of :object_taxon_name_id, scope: [:type, :subject_taxon_name_id, :project_id], unless: :is_combination?

  validate :validate_type, :validate_subject_and_object_are_not_identical
  validate :subject_and_object_in_same_project

  with_options unless: -> {!subject_taxon_name || !object_taxon_name} do
    validate :validate_subject_and_object_share_code,
      :validate_uniqueness_of_typification_object,
      #:validate_uniqueness_of_synonym_subject,
      :validate_object_and_subject_both_protonyms,
      :validate_object_must_equal_subject_for_uncertain_placement,
      :validate_subject_and_object_ranks,
      :validate_rank_group
  end

  # TODO: isolate to an include file sensu protonym
  soft_validate(
    :sv_validate_required_relationships,
    set: :validate_required_relationships,
    name: 'Required relationships',
    description: 'Required relationships' )

  soft_validate(
    :sv_validate_disjoint_relationships,
    set: :validate_disjoint_relationships,
    name: 'Conflicting relationships',
    description: 'Detect conflicting relationships' )

  soft_validate(
    :sv_validate_disjoint_object,
    set: :validate_disjoint_object,
    name: 'Conflicting object taxon',
    description: 'Object taxon has a status conflicting with the relationship' )

  soft_validate(
    :sv_validate_disjoint_subject,
    set: :validate_disjoint_subject,
    name: 'Conflicting subject taxon',
    description: 'Subject taxon has a status conflicting with the relationship' )

  soft_validate(
    :sv_specific_relationship,
    set: :specific_relationship,
    name: 'validate relationship',
    description: 'Validate integrity of the relationship, for example, the year applicability range' )

  soft_validate(
    :sv_objective_synonym_relationship,
    set: :objective_synonym_relationship,
    fix: :sv_fix_objective_synonym_relationship,
    name: 'Objective synonym relationship',
    description: 'Objective synonyms should have the same type' )

  soft_validate(
    :sv_synonym_relationship,
    set: :synonym_relationship,
    name: 'Synonym relationship',
    description: 'Validate integrity of synonym relationship' )

  soft_validate(
    :sv_not_specific_relationship,
    set: :not_specific_relationship,
    fix: :sv_fix_not_specific_relationship,
    name: 'Not specific relationship',
    description: 'More specific relationship is preferred, for example "Subjective synonym" instead of "Synonym".' )

  soft_validate(
    :sv_synonym_linked_to_valid_name,
    set: :synonym_linked_to_valid_name,
    fix: :sv_fix_subject_parent_update,
    name: 'Synonym not linked to valid taxon',
    description: 'Synonyms should be linked to valid taxon.' )

  soft_validate(
    :sv_validate_priority,
    set: :validate_priority,
    name: 'Priority validation',
    description: 'Junior synonym should be younger than senior synonym' )

  soft_validate(
    :sv_validate_seniority,
    set: :validate_seniority,
    name: 'Seniority validation',
    description: 'Of two synonyms described in the same paper, one described at a higher rank has a priority' )

  soft_validate(
    :sv_coordinated_taxa,
    set: :coordinated_taxa,
    fix: :sv_fix_coordinated_subject_taxa,
    name: 'Move relationship to coordinate taxon',
    description: 'Relationship should be moved to the lowest rank coordinate taxon (for example from species to nomynotypical subspecies). It could be updated automatically with the Fix.' )

  soft_validate(
    :sv_coordinated_taxa_object,
    set: :coordinated_taxa,
    fix: :sv_fix_coordinated_object_taxa,
    name: 'Move object relationship to coordinate taxon',
    description: 'Relationship should be moved to the lowest rank coordinate object taxon (for example from species to nomynotypical subspecies). It could be updated automatically with the Fix.')

  scope :where_subject_is_taxon_name, -> (taxon_name) {where(subject_taxon_name_id: taxon_name)}
  scope :where_object_is_taxon_name, -> (taxon_name) {where(object_taxon_name_id: taxon_name)}
  scope :where_object_in_taxon_names, -> (taxon_name_array) {where('"taxon_name_relationships"."object_taxon_name_id" IN (?)', taxon_name_array)}

  scope :with_type_string, -> (type_string) { where(sanitize_sql_array(["taxon_name_relationships.type = '%s'", type_string])) }

  scope :with_type_base, -> (base_string) {where('"taxon_name_relationships"."type" LIKE ?', "#{base_string}%")}
  scope :with_type_contains, -> (base_string) {where('"taxon_name_relationships"."type" LIKE ?', "%#{base_string}%")}

  scope :with_two_type_bases, -> (base_string1, base_string2) {
    where('taxon_name_relationships.type LIKE ? OR taxon_name_relationships.type LIKE ?', "#{base_string1}%", "#{base_string2}%") }

  scope :homonym_or_suppressed, -> {where("taxon_name_relationships.type LIKE 'TaxonNameRelationship::Iczn::Invalidating::Homonym%' OR taxon_name_relationships.type LIKE 'TaxonNameRelationship::Iczn::Invalidating::Suppression::Total'") }
  scope :with_type_array, -> (base_array) {where('taxon_name_relationships.type IN (?)', base_array ) }

  def dwc_occurrences
    DwcOccurrence
      .joins("JOIN collection_objects co on dwc_occurrence_object_id = co.id AND dwc_occurrence_object_type = 'CollectionObject'")
      .joins("JOIN taxon_determinations td on co.id = td.taxon_determination_object_id AND td.taxon_determination_object_type = 'CollectionObject'")
      .joins("JOIN otus o on o.id = td.otu_id")
      .where(o: {taxon_name_id: [subject_taxon_name_id, object_taxon_name_id]})
      .distinct
  end

  # @return [Array of TaxonNameClassification]
  #  the inferable TaxonNameClassification(s) added to the subject when this relationship is used
  #  !! Not implemented
  def subject_properties
    []
  end

  # @return [Array of TaxonNameClassification]
  #  the inferable TaxonNameClassification(s) added to the subject when this relationship is used
  #  !! Not implmented
  def object_properties
    []
  end

  # @return class
  #   this method calls Module#module_parent
  def self.parent
    self.module_parent
  end

  # @return [Array of NomenclatureRank]
  #   the valid ranks to which the subject name can belong, set in subclasses. (left side)
  def self.valid_subject_ranks
    []
  end

  # @return [Array of NomenclatureRank]
  #   the valid ranks to which the object name can belong, set in subclasses. (right side)
  def self.valid_object_ranks
    []
  end

  # @return [Array of TaxonNameRelationships]
  #   if this relationships is set for the subject, then others in this array should not be used for that subject
  def self.disjoint_taxon_name_relationships
    []
  end

  # TODO: why isn't this disjoint?
  # disjoint relationships for the taxon as a object
  def self.required_taxon_name_relationships
    []
  end

  def self.disjoint_subject_classes
    []
  end

  def self.disjoint_object_classes
    []
  end

  def self.gbif_status_of_subject
    nil
  end

  def self.gbif_status_of_object
    nil
  end

  def self.assignable
    false
  end

  # @return [Symbol]
  #   determine the relative age of subject and object
  #   :direct - subject is younger than object
  #   :reverse - object is younger than subject
  def self.nomenclatural_priority
    nil
  end

  # @return [String]
  #    the status inferred by the relationship to the object name
  def object_status
    self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
  end

  # @return [String]
  #    the status inferred by the relationship to the subject name
  def subject_status
    self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
  end

  # @return [String]
  #    the connecting word in the relationship from the subject name to object name
  def subject_status_connector_to_object
    ' of'
  end

  # @return [String]
  #    the connecting word in the relationship from the object name to subject name
  def object_status_connector_to_subject
    ' of'
  end

  # @return [String]
  #   a readable fragement combining status and connector
  def subject_status_tag
    subject_status + subject_status_connector_to_object
  end

  # @return [String]
  #   a readable fragement combining status and connector
  def object_status_tag
    object_status + object_status_connector_to_subject
  end

  # @return [String, nil]
  #   the type of this relationship, IF the type is a valid name, else nil
  def type_name
    r = self.type
    TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r : nil
  end

  def type_class=(value)
    write_attribute(:type, value.to_s)
  end

  def type_class
    r = read_attribute(:type).to_s
    TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r.safe_constantize : nil
  end

  # @return [String, nil]
  #   the NOMEN uri for this type
  def self.nomen_uri
    const_defined?(:NOMEN_URI, false) ? self::NOMEN_URI : nil
  end

  # @return [Time]
  #   effective date of publication, used to determine nomenclatural priorities
  #   !! Careful, if no date is present the current year is given, rather than nil, @proceps is this a safe inference?
  def nomenclature_date
    self.source ? (self.source.cached_nomenclature_date ? self.source.cached_nomenclature_date.to_time : Time.current) : Time.current
  end

  def is_combination?
    !!/TaxonNameRelationship::(OriginalCombination|Combination)/.match(self.type.to_s)
  end

  protected

  def subject_and_object_in_same_project
    if subject_taxon_name && object_taxon_name
      if subject_taxon_name.project_id != object_taxon_name.project_id
        errors.add(:base, 'one name is not in the same project as the other')
      end
    end
  end

  def validate_type
    # TODO: Remove, handled by STI
    if type && !TAXON_NAME_RELATIONSHIP_NAMES.include?(type.to_s)
      errors.add(:type, "'#{type}' is not a valid taxon name relationship")
    elsif self.type_class && object_taxon_name.class.to_s == 'Protonym' && !self.type_class.valid_object_ranks.include?(object_taxon_name.rank_string)
      errors.add(:type, "'#{type}' is not a valid taxon name relationship")
    end

    if object_taxon_name.class.to_s == 'Protonym' || object_taxon_name.class.to_s == 'Hybrid'
      errors.add(:type, "'#{type}' is not a valid taxon name relationship") if /TaxonNameRelationship::Combination::/.match(self.type)
    end

    if object_taxon_name.class.to_s == 'Combination'
      errors.add(:type, "'#{type}' is not a valid taxon name relationship") unless /TaxonNameRelationship::Combination::/.match(self.type)
    end
  end

  # @todo validate, that all the relationships in the table could be linked to relationships in classes (if those had changed)

  def validate_subject_and_object_share_code
    if object_taxon_name.type  == 'Protonym' && subject_taxon_name.type == 'Protonym'
      errors.add(:object_taxon_name_id, 'The related taxon is not in the same monenclatural group (ICZN, ICN, ICNP, ICVCN') if subject_taxon_name.rank_class.try(:nomenclatural_code) != object_taxon_name.rank_class.try(:nomenclatural_code)
    end
  end

  def validate_subject_and_object_are_not_identical
    if !self.object_taxon_name_id.nil? && self.object_taxon_name == self.subject_taxon_name
      errors.add(:object_taxon_name_id, "#{self.object_taxon_name.try(:cached_html)} should not refer to itself") unless self.type =~ /OriginalCombination/
    end
  end

  def validate_object_must_equal_subject_for_uncertain_placement
    if self.object_taxon_name_id != self.subject_taxon_name.parent_id && self.type_name == 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      errors.add(:object_taxon_name_id, "The parent #{self.subject_taxon_name.parent.cached_html} and the Incertae Sedis placement (#{self.object_taxon_name.cached_html}) should match")
    end
  end

  def validate_subject_and_object_ranks
    tname = self.type_name

    if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      rank_group = self.subject_taxon_name.rank_class.try(:parent)
      unless rank_group == self.object_taxon_name.rank_class.try(:parent)
        errors.add(:object_taxon_name_id, "Rank of related taxon should be in the #{rank_group.try(:rank_name)} rank group, not #{self.object_taxon_name.rank_class.try(:rank_name)}")
      end
    end

    if self.type_class.present? # only validate if it is set
      if object_taxon_name && object_taxon_name.rank_class
        if object_taxon_name.type == 'Protonym' || object_taxon_name.type == 'Hybrid'
          unless self.type_class.valid_object_ranks.include?(self.object_taxon_name.rank_string)
            errors.add(:object_taxon_name_id, "#{self.object_taxon_name.rank_class.rank_name.capitalize} rank of #{self.object_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
            errors.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.object_taxon_name.rank_class.rank_name} rank of #{self.object_taxon_name.cached_html}")
          end
        end
      end

      if subject_taxon_name && subject_taxon_name.rank_class
        if subject_taxon_name.type == 'Protonym' || subject_taxon_name.type == 'Hybrid'
          unless self.type_class.valid_subject_ranks.include?(self.subject_taxon_name.rank_string)
            soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
            soft_validations.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.subject_taxon_name.rank_class.rank_name} rank of #{self.subject_taxon_name.cached_html}")
          end
        end
      end
    end
  end

  ##### Protonym historically could be listed as a synonym to different taxa
  #def validate_uniqueness_of_synonym_subject
  #  if !self.type.nil? && /Synonym/.match(self.type_name) && !TaxonNameRelationship.where(subject_taxon_name_id: self.subject_taxon_name_id).with_type_contains('Synonym').not_self(self).empty?
  #    errors.add(:subject_taxon_name_id, 'Only one synonym relationship is allowed')
  #  end
  #end

  def validate_uniqueness_of_typification_object
    if /Typification/.match(self.type_name) && !TaxonNameRelationship.where(object_taxon_name_id: self.object_taxon_name_id).with_type_contains('Typification').not_self(self).empty?
      errors.add(:object_taxon_name_id, 'Only one Type designation relationship is allowed')
    end
  end

  def validate_rank_group
    if self.type =~ /Hybrid/ && self.subject_taxon_name && self.object_taxon_name
      if self.subject_taxon_name.rank_class.parent != self.object_taxon_name.rank_class.parent
        errors.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the rank of hybrid (#{self.object_taxon_name.rank_class.rank_name})")
      end
    end
  end

  def validate_object_and_subject_both_protonyms
    if /TaxonNameRelationship::Combination::/.match(self.type)
      errors.add(:object_taxon_name_id, 'Not a Combination') if object_taxon_name.type != 'Combination'
    else
      errors.add(:object_taxon_name_id, 'Not a Protonym') if object_taxon_name.type == 'Combination'
    end
    errors.add(:subject_taxon_name_id, 'Not a Protonym') if subject_taxon_name.type == 'Combination' && self.type != 'TaxonNameRelationship::CurrentCombination'
  end

  def set_cached_names_for_taxon_names
    # !! only fire if subject_taxon_name changed
    return true unless subject_taxon_name_id_previously_changed? || destroyed?

    TaxonName.transaction do
      if is_invalidating?
        t = subject_taxon_name

        if type_name =~/Misspelling/
          t.update_column(:cached_misspelling, t.get_cached_misspelling)
          t.update_columns(
              cached_author_year: t.get_author_and_year,
              cached_nomenclature_date: t.nomenclature_date,
              cached_original_combination: t.get_original_combination,
              cached_original_combination_html: t.get_original_combination_html)
        end

        if type_name =~/Misapplication/
          t.update_columns(
            cached_author_year: t.get_author_and_year,
            cached_nomenclature_date: t.nomenclature_date)
        end

        vn = t.get_valid_taxon_name

        # !! NO set cached should do this from TN side of things,
        # !! Not here

        n = t.get_full_name

        t.update_columns(
          cached: n,
          cached_html: t.get_full_name_html(n), # OK to force reload here, otherwise we need an exception in #set_cached
          cached_valid_taxon_name_id: vn.id,
          cached_is_valid: !t.unavailable_or_invalid?)

        t.combination_list_self.each do |c|
          c.update_column(:cached_valid_taxon_name_id, vn.id)
        end

        vn.list_of_invalid_taxon_names.each do |s|
          s.update_columns(
            cached_valid_taxon_name_id: vn.id,
            cached_is_valid: !s.unavailable_or_invalid?)

          s.combination_list_self.each do |c|
            c.update_column(:cached_valid_taxon_name_id, vn.id)
          end
        end

      end

    end

    true
  end

  def is_invalidating?
    TAXON_NAME_RELATIONSHIP_NAMES_INVALID.include?(type_name)
  end

  def sv_validate_required_relationships
    return true if self.subject_taxon_name.not_binominal?
    object_relationships = TaxonNameRelationship.where_object_is_taxon_name(self.object_taxon_name).not_self(self).collect{|r| r.type}
    required = self.type_class.required_taxon_name_relationships - object_relationships
    required.each do |r|
      soft_validations.add(:type, " Presence of #{self.subject_status} requires selection of #{r.demodulize.underscore.humanize.downcase}")
    end
  end

  def sv_validate_disjoint_relationships
    tname = self.type_name
    if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      subject_relationships = TaxonNameRelationship.where_subject_is_taxon_name(self.subject_taxon_name).not_self(self)
      subject_relationships.each  do |i|
        if self.type_class.disjoint_taxon_name_relationships.include?(i.type_name)
          soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with another relationship: '#{i.subject_status}'")
        end
      end
    end
  end

  def sv_validate_disjoint_object
    classifications = self.object_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
    disjoint_object_classes = self.type_class.disjoint_object_classes
    compare = disjoint_object_classes & classifications
    compare.each do |i|
      c = i.demodulize.underscore.humanize.downcase
      soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with the taxon status: '#{c}'")
      soft_validations.add(:object_taxon_name_id, "#{self.object_taxon_name.cached_html} has a conflicting status: '#{c}'")
    end
  end

  def sv_validate_disjoint_subject
    classifications = self.subject_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
    disjoint_subject_classes = self.type_class.disjoint_subject_classes
    compare = disjoint_subject_classes & classifications
    compare.each do |i|
      c = i.demodulize.underscore.humanize.downcase
      soft_validations.add(:type, "#{self.subject_status.capitalize} conflicting with the status: '#{c}'")
      soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.cached_html} has a conflicting status: '#{c}'")
    end
  end

  def sv_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_objective_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_fix_objective_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_not_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_fix_not_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_synonym_linked_to_valid_name
    #synonyms and misspellings should be linked to valid names
    if ::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
      obj = self.object_taxon_name
      subj = self.subject_taxon_name
      if subj.rank_class.try(:nomenclatural_code) == :iczn && (obj.parent_id != subj.parent_id || obj.rank_class != subj.rank_class) &&  subj.cached_valid_taxon_name_id == obj.cached_valid_taxon_name_id
        soft_validations.add(:subject_taxon_name_id, "#{self.subject_status.capitalize}  #{subj.cached_html_name_and_author_year} should have the same parent and rank with  #{obj.cached_html_name_and_author_year}",
                             success_message: 'The parent was updated', failure_message:  'The parent was not updated')
      end
    end
  end

  def sv_fix_subject_parent_update
    res = false
    if TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
      obj = self.object_taxon_name
      subj = self.subject_taxon_name
      unless obj.parent_id == subj.parent_id
        subj.parent_id = obj.parent_id
        subj.rank_class = obj.rank_class
        begin
          TaxonName.transaction do
            subj.save!
            res = true
          end
        rescue
        end
      end
    end
    res
  end

  def subject_invalid_statuses
    TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & self.subject_taxon_name.taxon_name_classifications.collect{|c| c.type_class.to_s}
  end

  def sv_validate_priority
    true # all validations moved to subclasses
  end

  def sv_validate_seniority
    true # all validations moved to subclasses
  end

  def sv_coordinated_taxa
    s = subject_taxon_name
    o = object_taxon_name
    s_new = s.lowest_rank_coordinated_taxon
    if s != s_new
      soft_validations.add(:subject_taxon_name_id, "Relationship should move from #{s.rank_class.rank_name} #{s.cached_html} to #{s_new.rank_class.rank_name} #{s_new.cached_html}",
                           success_message: "Relationship moved to  #{s_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
    end
  end

  def sv_coordinated_taxa_object
    s = subject_taxon_name
    o = object_taxon_name
    o_new = o.lowest_rank_coordinated_taxon
    if o != o_new
      soft_validations.add(:object_taxon_name_id, "Relationship should move from #{o.rank_class.rank_name} #{o.cached_html} to #{o_new.rank_class.rank_name} #{o_new.cached_html}",
                           success_message: "Relationship moved to  #{o_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
    end
  end

  def sv_fix_coordinated_subject_taxa
    s = subject_taxon_name
    s_new = s.lowest_rank_coordinated_taxon
    if s != s_new
      self.subject_taxon_name = s_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def sv_fix_coordinated_object_taxa
    o = self.object_taxon_name
    o_new = o.lowest_rank_coordinated_taxon
    if o != o_new
      self.object_taxon_name = o_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def sv_fix_combination_relationship
    s = self.subject_taxon_name
    list = s.list_of_coordinated_names + [s]
    if s.rank_string =~ /Species/
      s_new = list.detect{|t| t.rank_class.rank_name == 'species'}
    elsif s.rank_string =~ /Genus/
      s_new = list.detect{|t| t.rank_class.rank_name == 'genus'}
    else
      s_new = s
    end
    if s != s_new && !s.nil?
      self.subject_taxon_name = s_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def self.collect_to_s(*args)
    args.collect{|arg| arg.to_s}
  end

  def self.collect_descendants_to_s(*classes)
    ans = []
    classes.each do |klass|
      ans += klass.descendants.collect{|k| k.to_s}
    end
    ans
  end

  def self.collect_descendants_and_itself_to_s(*classes)
    classes.collect{|k| k.to_s} + self.collect_descendants_to_s(*classes)
  end

  # Force loading all descendants as soon as this class is referenced
  Dir.glob("#{Rails.root.join("app/models/taxon_name_relationship/**/*.rb")}")
    .sort { |a, b| a.split('/').count <=> b.split('/').count }
    .map { |p| p.split('/app/models/').last.sub(/\.rb$/, '') }
    .map { |p| p.split('/') }
    .map { |c| c.map { |n| ActiveSupport::Inflector.camelize(n) } }
    .map { |c| c.join('::') }.map(&:constantize)
end

#typeString

Returns the relationship/“predicate” between the subject and object taxon names.

Returns:

  • (String)

    the relationship/“predicate” between the subject and object taxon names



44
45
46
47
48
49
50
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
140
141
142
143
144
145
146
147
148
149
150
151
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
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
219
220
221
222
223
224
225
226
227
228
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
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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
357
358
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'app/models/taxon_name_relationship.rb', line 44

class TaxonNameRelationship < ApplicationRecord
  include Housekeeping
  include Shared::Citations
  include Shared::Notes
  include SoftValidation
  include Shared::DwcOccurrenceHooks
  include Shared::IsData

  # @return [Boolean, nil]
  #   When true, cached values are not built
  attr_accessor :no_cached

  belongs_to :subject_taxon_name, class_name: 'TaxonName', inverse_of: :taxon_name_relationships # left side
  belongs_to :object_taxon_name, class_name: 'TaxonName', inverse_of: :related_taxon_name_relationships # right side

  # !! Keep as after_commit unless you are wanting to spend a lot of time
  # !! refactoring tests
  after_commit :set_cached_names_for_taxon_names, unless: -> {self.no_cached || destroyed?}
  after_destroy :set_cached_names_for_taxon_names, unless: -> {self.no_cached}

  # TODO: remove, it's required by STI
  validates_presence_of :type, message: 'Relationship type should be specified'
  validates_presence_of :subject_taxon_name, message: 'Missing taxon name on the left side'
  validates_presence_of :object_taxon_name, message: 'Missing taxon name on the right side'
  validates_uniqueness_of :object_taxon_name_id, scope: [:type, :project_id], if: :is_combination?
  validates_uniqueness_of :object_taxon_name_id, scope: [:type, :subject_taxon_name_id, :project_id], unless: :is_combination?

  validate :validate_type, :validate_subject_and_object_are_not_identical
  validate :subject_and_object_in_same_project

  with_options unless: -> {!subject_taxon_name || !object_taxon_name} do
    validate :validate_subject_and_object_share_code,
      :validate_uniqueness_of_typification_object,
      #:validate_uniqueness_of_synonym_subject,
      :validate_object_and_subject_both_protonyms,
      :validate_object_must_equal_subject_for_uncertain_placement,
      :validate_subject_and_object_ranks,
      :validate_rank_group
  end

  # TODO: isolate to an include file sensu protonym
  soft_validate(
    :sv_validate_required_relationships,
    set: :validate_required_relationships,
    name: 'Required relationships',
    description: 'Required relationships' )

  soft_validate(
    :sv_validate_disjoint_relationships,
    set: :validate_disjoint_relationships,
    name: 'Conflicting relationships',
    description: 'Detect conflicting relationships' )

  soft_validate(
    :sv_validate_disjoint_object,
    set: :validate_disjoint_object,
    name: 'Conflicting object taxon',
    description: 'Object taxon has a status conflicting with the relationship' )

  soft_validate(
    :sv_validate_disjoint_subject,
    set: :validate_disjoint_subject,
    name: 'Conflicting subject taxon',
    description: 'Subject taxon has a status conflicting with the relationship' )

  soft_validate(
    :sv_specific_relationship,
    set: :specific_relationship,
    name: 'validate relationship',
    description: 'Validate integrity of the relationship, for example, the year applicability range' )

  soft_validate(
    :sv_objective_synonym_relationship,
    set: :objective_synonym_relationship,
    fix: :sv_fix_objective_synonym_relationship,
    name: 'Objective synonym relationship',
    description: 'Objective synonyms should have the same type' )

  soft_validate(
    :sv_synonym_relationship,
    set: :synonym_relationship,
    name: 'Synonym relationship',
    description: 'Validate integrity of synonym relationship' )

  soft_validate(
    :sv_not_specific_relationship,
    set: :not_specific_relationship,
    fix: :sv_fix_not_specific_relationship,
    name: 'Not specific relationship',
    description: 'More specific relationship is preferred, for example "Subjective synonym" instead of "Synonym".' )

  soft_validate(
    :sv_synonym_linked_to_valid_name,
    set: :synonym_linked_to_valid_name,
    fix: :sv_fix_subject_parent_update,
    name: 'Synonym not linked to valid taxon',
    description: 'Synonyms should be linked to valid taxon.' )

  soft_validate(
    :sv_validate_priority,
    set: :validate_priority,
    name: 'Priority validation',
    description: 'Junior synonym should be younger than senior synonym' )

  soft_validate(
    :sv_validate_seniority,
    set: :validate_seniority,
    name: 'Seniority validation',
    description: 'Of two synonyms described in the same paper, one described at a higher rank has a priority' )

  soft_validate(
    :sv_coordinated_taxa,
    set: :coordinated_taxa,
    fix: :sv_fix_coordinated_subject_taxa,
    name: 'Move relationship to coordinate taxon',
    description: 'Relationship should be moved to the lowest rank coordinate taxon (for example from species to nomynotypical subspecies). It could be updated automatically with the Fix.' )

  soft_validate(
    :sv_coordinated_taxa_object,
    set: :coordinated_taxa,
    fix: :sv_fix_coordinated_object_taxa,
    name: 'Move object relationship to coordinate taxon',
    description: 'Relationship should be moved to the lowest rank coordinate object taxon (for example from species to nomynotypical subspecies). It could be updated automatically with the Fix.')

  scope :where_subject_is_taxon_name, -> (taxon_name) {where(subject_taxon_name_id: taxon_name)}
  scope :where_object_is_taxon_name, -> (taxon_name) {where(object_taxon_name_id: taxon_name)}
  scope :where_object_in_taxon_names, -> (taxon_name_array) {where('"taxon_name_relationships"."object_taxon_name_id" IN (?)', taxon_name_array)}

  scope :with_type_string, -> (type_string) { where(sanitize_sql_array(["taxon_name_relationships.type = '%s'", type_string])) }

  scope :with_type_base, -> (base_string) {where('"taxon_name_relationships"."type" LIKE ?', "#{base_string}%")}
  scope :with_type_contains, -> (base_string) {where('"taxon_name_relationships"."type" LIKE ?', "%#{base_string}%")}

  scope :with_two_type_bases, -> (base_string1, base_string2) {
    where('taxon_name_relationships.type LIKE ? OR taxon_name_relationships.type LIKE ?', "#{base_string1}%", "#{base_string2}%") }

  scope :homonym_or_suppressed, -> {where("taxon_name_relationships.type LIKE 'TaxonNameRelationship::Iczn::Invalidating::Homonym%' OR taxon_name_relationships.type LIKE 'TaxonNameRelationship::Iczn::Invalidating::Suppression::Total'") }
  scope :with_type_array, -> (base_array) {where('taxon_name_relationships.type IN (?)', base_array ) }

  def dwc_occurrences
    DwcOccurrence
      .joins("JOIN collection_objects co on dwc_occurrence_object_id = co.id AND dwc_occurrence_object_type = 'CollectionObject'")
      .joins("JOIN taxon_determinations td on co.id = td.taxon_determination_object_id AND td.taxon_determination_object_type = 'CollectionObject'")
      .joins("JOIN otus o on o.id = td.otu_id")
      .where(o: {taxon_name_id: [subject_taxon_name_id, object_taxon_name_id]})
      .distinct
  end

  # @return [Array of TaxonNameClassification]
  #  the inferable TaxonNameClassification(s) added to the subject when this relationship is used
  #  !! Not implemented
  def subject_properties
    []
  end

  # @return [Array of TaxonNameClassification]
  #  the inferable TaxonNameClassification(s) added to the subject when this relationship is used
  #  !! Not implmented
  def object_properties
    []
  end

  # @return class
  #   this method calls Module#module_parent
  def self.parent
    self.module_parent
  end

  # @return [Array of NomenclatureRank]
  #   the valid ranks to which the subject name can belong, set in subclasses. (left side)
  def self.valid_subject_ranks
    []
  end

  # @return [Array of NomenclatureRank]
  #   the valid ranks to which the object name can belong, set in subclasses. (right side)
  def self.valid_object_ranks
    []
  end

  # @return [Array of TaxonNameRelationships]
  #   if this relationships is set for the subject, then others in this array should not be used for that subject
  def self.disjoint_taxon_name_relationships
    []
  end

  # TODO: why isn't this disjoint?
  # disjoint relationships for the taxon as a object
  def self.required_taxon_name_relationships
    []
  end

  def self.disjoint_subject_classes
    []
  end

  def self.disjoint_object_classes
    []
  end

  def self.gbif_status_of_subject
    nil
  end

  def self.gbif_status_of_object
    nil
  end

  def self.assignable
    false
  end

  # @return [Symbol]
  #   determine the relative age of subject and object
  #   :direct - subject is younger than object
  #   :reverse - object is younger than subject
  def self.nomenclatural_priority
    nil
  end

  # @return [String]
  #    the status inferred by the relationship to the object name
  def object_status
    self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
  end

  # @return [String]
  #    the status inferred by the relationship to the subject name
  def subject_status
    self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
  end

  # @return [String]
  #    the connecting word in the relationship from the subject name to object name
  def subject_status_connector_to_object
    ' of'
  end

  # @return [String]
  #    the connecting word in the relationship from the object name to subject name
  def object_status_connector_to_subject
    ' of'
  end

  # @return [String]
  #   a readable fragement combining status and connector
  def subject_status_tag
    subject_status + subject_status_connector_to_object
  end

  # @return [String]
  #   a readable fragement combining status and connector
  def object_status_tag
    object_status + object_status_connector_to_subject
  end

  # @return [String, nil]
  #   the type of this relationship, IF the type is a valid name, else nil
  def type_name
    r = self.type
    TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r : nil
  end

  def type_class=(value)
    write_attribute(:type, value.to_s)
  end

  def type_class
    r = read_attribute(:type).to_s
    TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r.safe_constantize : nil
  end

  # @return [String, nil]
  #   the NOMEN uri for this type
  def self.nomen_uri
    const_defined?(:NOMEN_URI, false) ? self::NOMEN_URI : nil
  end

  # @return [Time]
  #   effective date of publication, used to determine nomenclatural priorities
  #   !! Careful, if no date is present the current year is given, rather than nil, @proceps is this a safe inference?
  def nomenclature_date
    self.source ? (self.source.cached_nomenclature_date ? self.source.cached_nomenclature_date.to_time : Time.current) : Time.current
  end

  def is_combination?
    !!/TaxonNameRelationship::(OriginalCombination|Combination)/.match(self.type.to_s)
  end

  protected

  def subject_and_object_in_same_project
    if subject_taxon_name && object_taxon_name
      if subject_taxon_name.project_id != object_taxon_name.project_id
        errors.add(:base, 'one name is not in the same project as the other')
      end
    end
  end

  def validate_type
    # TODO: Remove, handled by STI
    if type && !TAXON_NAME_RELATIONSHIP_NAMES.include?(type.to_s)
      errors.add(:type, "'#{type}' is not a valid taxon name relationship")
    elsif self.type_class && object_taxon_name.class.to_s == 'Protonym' && !self.type_class.valid_object_ranks.include?(object_taxon_name.rank_string)
      errors.add(:type, "'#{type}' is not a valid taxon name relationship")
    end

    if object_taxon_name.class.to_s == 'Protonym' || object_taxon_name.class.to_s == 'Hybrid'
      errors.add(:type, "'#{type}' is not a valid taxon name relationship") if /TaxonNameRelationship::Combination::/.match(self.type)
    end

    if object_taxon_name.class.to_s == 'Combination'
      errors.add(:type, "'#{type}' is not a valid taxon name relationship") unless /TaxonNameRelationship::Combination::/.match(self.type)
    end
  end

  # @todo validate, that all the relationships in the table could be linked to relationships in classes (if those had changed)

  def validate_subject_and_object_share_code
    if object_taxon_name.type  == 'Protonym' && subject_taxon_name.type == 'Protonym'
      errors.add(:object_taxon_name_id, 'The related taxon is not in the same monenclatural group (ICZN, ICN, ICNP, ICVCN') if subject_taxon_name.rank_class.try(:nomenclatural_code) != object_taxon_name.rank_class.try(:nomenclatural_code)
    end
  end

  def validate_subject_and_object_are_not_identical
    if !self.object_taxon_name_id.nil? && self.object_taxon_name == self.subject_taxon_name
      errors.add(:object_taxon_name_id, "#{self.object_taxon_name.try(:cached_html)} should not refer to itself") unless self.type =~ /OriginalCombination/
    end
  end

  def validate_object_must_equal_subject_for_uncertain_placement
    if self.object_taxon_name_id != self.subject_taxon_name.parent_id && self.type_name == 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      errors.add(:object_taxon_name_id, "The parent #{self.subject_taxon_name.parent.cached_html} and the Incertae Sedis placement (#{self.object_taxon_name.cached_html}) should match")
    end
  end

  def validate_subject_and_object_ranks
    tname = self.type_name

    if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      rank_group = self.subject_taxon_name.rank_class.try(:parent)
      unless rank_group == self.object_taxon_name.rank_class.try(:parent)
        errors.add(:object_taxon_name_id, "Rank of related taxon should be in the #{rank_group.try(:rank_name)} rank group, not #{self.object_taxon_name.rank_class.try(:rank_name)}")
      end
    end

    if self.type_class.present? # only validate if it is set
      if object_taxon_name && object_taxon_name.rank_class
        if object_taxon_name.type == 'Protonym' || object_taxon_name.type == 'Hybrid'
          unless self.type_class.valid_object_ranks.include?(self.object_taxon_name.rank_string)
            errors.add(:object_taxon_name_id, "#{self.object_taxon_name.rank_class.rank_name.capitalize} rank of #{self.object_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
            errors.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.object_taxon_name.rank_class.rank_name} rank of #{self.object_taxon_name.cached_html}")
          end
        end
      end

      if subject_taxon_name && subject_taxon_name.rank_class
        if subject_taxon_name.type == 'Protonym' || subject_taxon_name.type == 'Hybrid'
          unless self.type_class.valid_subject_ranks.include?(self.subject_taxon_name.rank_string)
            soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
            soft_validations.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.subject_taxon_name.rank_class.rank_name} rank of #{self.subject_taxon_name.cached_html}")
          end
        end
      end
    end
  end

  ##### Protonym historically could be listed as a synonym to different taxa
  #def validate_uniqueness_of_synonym_subject
  #  if !self.type.nil? && /Synonym/.match(self.type_name) && !TaxonNameRelationship.where(subject_taxon_name_id: self.subject_taxon_name_id).with_type_contains('Synonym').not_self(self).empty?
  #    errors.add(:subject_taxon_name_id, 'Only one synonym relationship is allowed')
  #  end
  #end

  def validate_uniqueness_of_typification_object
    if /Typification/.match(self.type_name) && !TaxonNameRelationship.where(object_taxon_name_id: self.object_taxon_name_id).with_type_contains('Typification').not_self(self).empty?
      errors.add(:object_taxon_name_id, 'Only one Type designation relationship is allowed')
    end
  end

  def validate_rank_group
    if self.type =~ /Hybrid/ && self.subject_taxon_name && self.object_taxon_name
      if self.subject_taxon_name.rank_class.parent != self.object_taxon_name.rank_class.parent
        errors.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the rank of hybrid (#{self.object_taxon_name.rank_class.rank_name})")
      end
    end
  end

  def validate_object_and_subject_both_protonyms
    if /TaxonNameRelationship::Combination::/.match(self.type)
      errors.add(:object_taxon_name_id, 'Not a Combination') if object_taxon_name.type != 'Combination'
    else
      errors.add(:object_taxon_name_id, 'Not a Protonym') if object_taxon_name.type == 'Combination'
    end
    errors.add(:subject_taxon_name_id, 'Not a Protonym') if subject_taxon_name.type == 'Combination' && self.type != 'TaxonNameRelationship::CurrentCombination'
  end

  def set_cached_names_for_taxon_names
    # !! only fire if subject_taxon_name changed
    return true unless subject_taxon_name_id_previously_changed? || destroyed?

    TaxonName.transaction do
      if is_invalidating?
        t = subject_taxon_name

        if type_name =~/Misspelling/
          t.update_column(:cached_misspelling, t.get_cached_misspelling)
          t.update_columns(
              cached_author_year: t.get_author_and_year,
              cached_nomenclature_date: t.nomenclature_date,
              cached_original_combination: t.get_original_combination,
              cached_original_combination_html: t.get_original_combination_html)
        end

        if type_name =~/Misapplication/
          t.update_columns(
            cached_author_year: t.get_author_and_year,
            cached_nomenclature_date: t.nomenclature_date)
        end

        vn = t.get_valid_taxon_name

        # !! NO set cached should do this from TN side of things,
        # !! Not here

        n = t.get_full_name

        t.update_columns(
          cached: n,
          cached_html: t.get_full_name_html(n), # OK to force reload here, otherwise we need an exception in #set_cached
          cached_valid_taxon_name_id: vn.id,
          cached_is_valid: !t.unavailable_or_invalid?)

        t.combination_list_self.each do |c|
          c.update_column(:cached_valid_taxon_name_id, vn.id)
        end

        vn.list_of_invalid_taxon_names.each do |s|
          s.update_columns(
            cached_valid_taxon_name_id: vn.id,
            cached_is_valid: !s.unavailable_or_invalid?)

          s.combination_list_self.each do |c|
            c.update_column(:cached_valid_taxon_name_id, vn.id)
          end
        end

      end

    end

    true
  end

  def is_invalidating?
    TAXON_NAME_RELATIONSHIP_NAMES_INVALID.include?(type_name)
  end

  def sv_validate_required_relationships
    return true if self.subject_taxon_name.not_binominal?
    object_relationships = TaxonNameRelationship.where_object_is_taxon_name(self.object_taxon_name).not_self(self).collect{|r| r.type}
    required = self.type_class.required_taxon_name_relationships - object_relationships
    required.each do |r|
      soft_validations.add(:type, " Presence of #{self.subject_status} requires selection of #{r.demodulize.underscore.humanize.downcase}")
    end
  end

  def sv_validate_disjoint_relationships
    tname = self.type_name
    if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
      subject_relationships = TaxonNameRelationship.where_subject_is_taxon_name(self.subject_taxon_name).not_self(self)
      subject_relationships.each  do |i|
        if self.type_class.disjoint_taxon_name_relationships.include?(i.type_name)
          soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with another relationship: '#{i.subject_status}'")
        end
      end
    end
  end

  def sv_validate_disjoint_object
    classifications = self.object_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
    disjoint_object_classes = self.type_class.disjoint_object_classes
    compare = disjoint_object_classes & classifications
    compare.each do |i|
      c = i.demodulize.underscore.humanize.downcase
      soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with the taxon status: '#{c}'")
      soft_validations.add(:object_taxon_name_id, "#{self.object_taxon_name.cached_html} has a conflicting status: '#{c}'")
    end
  end

  def sv_validate_disjoint_subject
    classifications = self.subject_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
    disjoint_subject_classes = self.type_class.disjoint_subject_classes
    compare = disjoint_subject_classes & classifications
    compare.each do |i|
      c = i.demodulize.underscore.humanize.downcase
      soft_validations.add(:type, "#{self.subject_status.capitalize} conflicting with the status: '#{c}'")
      soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.cached_html} has a conflicting status: '#{c}'")
    end
  end

  def sv_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_objective_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_fix_objective_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_synonym_relationship
    true # all validations moved to subclasses
  end

  def sv_not_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_fix_not_specific_relationship
    true # all validations moved to subclasses
  end

  def sv_synonym_linked_to_valid_name
    #synonyms and misspellings should be linked to valid names
    if ::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
      obj = self.object_taxon_name
      subj = self.subject_taxon_name
      if subj.rank_class.try(:nomenclatural_code) == :iczn && (obj.parent_id != subj.parent_id || obj.rank_class != subj.rank_class) &&  subj.cached_valid_taxon_name_id == obj.cached_valid_taxon_name_id
        soft_validations.add(:subject_taxon_name_id, "#{self.subject_status.capitalize}  #{subj.cached_html_name_and_author_year} should have the same parent and rank with  #{obj.cached_html_name_and_author_year}",
                             success_message: 'The parent was updated', failure_message:  'The parent was not updated')
      end
    end
  end

  def sv_fix_subject_parent_update
    res = false
    if TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
      obj = self.object_taxon_name
      subj = self.subject_taxon_name
      unless obj.parent_id == subj.parent_id
        subj.parent_id = obj.parent_id
        subj.rank_class = obj.rank_class
        begin
          TaxonName.transaction do
            subj.save!
            res = true
          end
        rescue
        end
      end
    end
    res
  end

  def subject_invalid_statuses
    TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & self.subject_taxon_name.taxon_name_classifications.collect{|c| c.type_class.to_s}
  end

  def sv_validate_priority
    true # all validations moved to subclasses
  end

  def sv_validate_seniority
    true # all validations moved to subclasses
  end

  def sv_coordinated_taxa
    s = subject_taxon_name
    o = object_taxon_name
    s_new = s.lowest_rank_coordinated_taxon
    if s != s_new
      soft_validations.add(:subject_taxon_name_id, "Relationship should move from #{s.rank_class.rank_name} #{s.cached_html} to #{s_new.rank_class.rank_name} #{s_new.cached_html}",
                           success_message: "Relationship moved to  #{s_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
    end
  end

  def sv_coordinated_taxa_object
    s = subject_taxon_name
    o = object_taxon_name
    o_new = o.lowest_rank_coordinated_taxon
    if o != o_new
      soft_validations.add(:object_taxon_name_id, "Relationship should move from #{o.rank_class.rank_name} #{o.cached_html} to #{o_new.rank_class.rank_name} #{o_new.cached_html}",
                           success_message: "Relationship moved to  #{o_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
    end
  end

  def sv_fix_coordinated_subject_taxa
    s = subject_taxon_name
    s_new = s.lowest_rank_coordinated_taxon
    if s != s_new
      self.subject_taxon_name = s_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def sv_fix_coordinated_object_taxa
    o = self.object_taxon_name
    o_new = o.lowest_rank_coordinated_taxon
    if o != o_new
      self.object_taxon_name = o_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def sv_fix_combination_relationship
    s = self.subject_taxon_name
    list = s.list_of_coordinated_names + [s]
    if s.rank_string =~ /Species/
      s_new = list.detect{|t| t.rank_class.rank_name == 'species'}
    elsif s.rank_string =~ /Genus/
      s_new = list.detect{|t| t.rank_class.rank_name == 'genus'}
    else
      s_new = s
    end
    if s != s_new && !s.nil?
      self.subject_taxon_name = s_new
      begin
        TaxonNameRelationship.transaction do
          self.save
          return true
        end
      rescue
      end
    end
    false
  end

  def self.collect_to_s(*args)
    args.collect{|arg| arg.to_s}
  end

  def self.collect_descendants_to_s(*classes)
    ans = []
    classes.each do |klass|
      ans += klass.descendants.collect{|k| k.to_s}
    end
    ans
  end

  def self.collect_descendants_and_itself_to_s(*classes)
    classes.collect{|k| k.to_s} + self.collect_descendants_to_s(*classes)
  end

  # Force loading all descendants as soon as this class is referenced
  Dir.glob("#{Rails.root.join("app/models/taxon_name_relationship/**/*.rb")}")
    .sort { |a, b| a.split('/').count <=> b.split('/').count }
    .map { |p| p.split('/app/models/').last.sub(/\.rb$/, '') }
    .map { |p| p.split('/') }
    .map { |c| c.map { |n| ActiveSupport::Inflector.camelize(n) } }
    .map { |c| c.join('::') }.map(&:constantize)
end

Class Method Details

.assignableObject



252
253
254
# File 'app/models/taxon_name_relationship.rb', line 252

def self.assignable
  false
end

.collect_descendants_and_itself_to_s(*classes) ⇒ Object (protected)



700
701
702
# File 'app/models/taxon_name_relationship.rb', line 700

def self.collect_descendants_and_itself_to_s(*classes)
  classes.collect{|k| k.to_s} + self.collect_descendants_to_s(*classes)
end

.collect_descendants_to_s(*classes) ⇒ Object (protected)



692
693
694
695
696
697
698
# File 'app/models/taxon_name_relationship.rb', line 692

def self.collect_descendants_to_s(*classes)
  ans = []
  classes.each do |klass|
    ans += klass.descendants.collect{|k| k.to_s}
  end
  ans
end

.collect_to_s(*args) ⇒ Object (protected)



688
689
690
# File 'app/models/taxon_name_relationship.rb', line 688

def self.collect_to_s(*args)
  args.collect{|arg| arg.to_s}
end

.disjoint_object_classesObject



240
241
242
# File 'app/models/taxon_name_relationship.rb', line 240

def self.disjoint_object_classes
  []
end

.disjoint_subject_classesObject



236
237
238
# File 'app/models/taxon_name_relationship.rb', line 236

def self.disjoint_subject_classes
  []
end

.disjoint_taxon_name_relationshipsArray of TaxonNameRelationships

Returns if this relationships is set for the subject, then others in this array should not be used for that subject.

Returns:

  • (Array of TaxonNameRelationships)

    if this relationships is set for the subject, then others in this array should not be used for that subject



226
227
228
# File 'app/models/taxon_name_relationship.rb', line 226

def self.disjoint_taxon_name_relationships
  []
end

.gbif_status_of_objectObject



248
249
250
# File 'app/models/taxon_name_relationship.rb', line 248

def self.gbif_status_of_object
  nil
end

.gbif_status_of_subjectObject



244
245
246
# File 'app/models/taxon_name_relationship.rb', line 244

def self.gbif_status_of_subject
  nil
end

.nomen_uriString?

Returns the NOMEN uri for this type.

Returns:

  • (String, nil)

    the NOMEN uri for this type



318
319
320
# File 'app/models/taxon_name_relationship.rb', line 318

def self.nomen_uri
  const_defined?(:NOMEN_URI, false) ? self::NOMEN_URI : nil
end

.nomenclatural_prioritySymbol

Returns determine the relative age of subject and object :direct - subject is younger than object :reverse - object is younger than subject.

Returns:

  • (Symbol)

    determine the relative age of subject and object :direct - subject is younger than object :reverse - object is younger than subject



260
261
262
# File 'app/models/taxon_name_relationship.rb', line 260

def self.nomenclatural_priority
  nil
end

.parentObject

Returns class this method calls Module#module_parent.

Returns:

  • class this method calls Module#module_parent



208
209
210
# File 'app/models/taxon_name_relationship.rb', line 208

def self.parent
  self.module_parent
end

.required_taxon_name_relationshipsObject

TODO: why isn’t this disjoint? disjoint relationships for the taxon as a object



232
233
234
# File 'app/models/taxon_name_relationship.rb', line 232

def self.required_taxon_name_relationships
  []
end

.valid_object_ranksArray of NomenclatureRank

Returns the valid ranks to which the object name can belong, set in subclasses. (right side).

Returns:

  • (Array of NomenclatureRank)

    the valid ranks to which the object name can belong, set in subclasses. (right side)



220
221
222
# File 'app/models/taxon_name_relationship.rb', line 220

def self.valid_object_ranks
  []
end

.valid_subject_ranksArray of NomenclatureRank

Returns the valid ranks to which the subject name can belong, set in subclasses. (left side).

Returns:

  • (Array of NomenclatureRank)

    the valid ranks to which the subject name can belong, set in subclasses. (left side)



214
215
216
# File 'app/models/taxon_name_relationship.rb', line 214

def self.valid_subject_ranks
  []
end

Instance Method Details

#dwc_occurrencesObject



183
184
185
186
187
188
189
190
# File 'app/models/taxon_name_relationship.rb', line 183

def dwc_occurrences
  DwcOccurrence
    .joins("JOIN collection_objects co on dwc_occurrence_object_id = co.id AND dwc_occurrence_object_type = 'CollectionObject'")
    .joins("JOIN taxon_determinations td on co.id = td.taxon_determination_object_id AND td.taxon_determination_object_type = 'CollectionObject'")
    .joins("JOIN otus o on o.id = td.otu_id")
    .where(o: {taxon_name_id: [subject_taxon_name_id, object_taxon_name_id]})
    .distinct
end

#is_combination?Boolean

Returns:

  • (Boolean)


329
330
331
# File 'app/models/taxon_name_relationship.rb', line 329

def is_combination?
  !!/TaxonNameRelationship::(OriginalCombination|Combination)/.match(self.type.to_s)
end

#is_invalidating?Boolean (protected)

Returns:

  • (Boolean)


498
499
500
# File 'app/models/taxon_name_relationship.rb', line 498

def is_invalidating?
  TAXON_NAME_RELATIONSHIP_NAMES_INVALID.include?(type_name)
end

#nomenclature_dateTime

Returns effective date of publication, used to determine nomenclatural priorities !! Careful, if no date is present the current year is given, rather than nil, @proceps is this a safe inference?.

Returns:

  • (Time)

    effective date of publication, used to determine nomenclatural priorities !! Careful, if no date is present the current year is given, rather than nil, @proceps is this a safe inference?



325
326
327
# File 'app/models/taxon_name_relationship.rb', line 325

def nomenclature_date
  self.source ? (self.source.cached_nomenclature_date ? self.source.cached_nomenclature_date.to_time : Time.current) : Time.current
end

#object_propertiesArray of TaxonNameClassification

Returns the inferable TaxonNameClassification(s) added to the subject when this relationship is used !! Not implmented.

Returns:

  • (Array of TaxonNameClassification)

    the inferable TaxonNameClassification(s) added to the subject when this relationship is used !! Not implmented



202
203
204
# File 'app/models/taxon_name_relationship.rb', line 202

def object_properties
  []
end

#object_statusString

Returns the status inferred by the relationship to the object name.

Returns:

  • (String)

    the status inferred by the relationship to the object name



266
267
268
# File 'app/models/taxon_name_relationship.rb', line 266

def object_status
  self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
end

#object_status_connector_to_subjectString

Returns the connecting word in the relationship from the object name to subject name.

Returns:

  • (String)

    the connecting word in the relationship from the object name to subject name



284
285
286
# File 'app/models/taxon_name_relationship.rb', line 284

def object_status_connector_to_subject
  ' of'
end

#object_status_tagString

Returns a readable fragement combining status and connector.

Returns:

  • (String)

    a readable fragement combining status and connector



296
297
298
# File 'app/models/taxon_name_relationship.rb', line 296

def object_status_tag
  object_status + object_status_connector_to_subject
end

#set_cached_names_for_taxon_namesObject (protected)



441
442
443
444
445
446
447
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
494
495
496
# File 'app/models/taxon_name_relationship.rb', line 441

def set_cached_names_for_taxon_names
  # !! only fire if subject_taxon_name changed
  return true unless subject_taxon_name_id_previously_changed? || destroyed?

  TaxonName.transaction do
    if is_invalidating?
      t = subject_taxon_name

      if type_name =~/Misspelling/
        t.update_column(:cached_misspelling, t.get_cached_misspelling)
        t.update_columns(
            cached_author_year: t.get_author_and_year,
            cached_nomenclature_date: t.nomenclature_date,
            cached_original_combination: t.get_original_combination,
            cached_original_combination_html: t.get_original_combination_html)
      end

      if type_name =~/Misapplication/
        t.update_columns(
          cached_author_year: t.get_author_and_year,
          cached_nomenclature_date: t.nomenclature_date)
      end

      vn = t.get_valid_taxon_name

      # !! NO set cached should do this from TN side of things,
      # !! Not here

      n = t.get_full_name

      t.update_columns(
        cached: n,
        cached_html: t.get_full_name_html(n), # OK to force reload here, otherwise we need an exception in #set_cached
        cached_valid_taxon_name_id: vn.id,
        cached_is_valid: !t.unavailable_or_invalid?)

      t.combination_list_self.each do |c|
        c.update_column(:cached_valid_taxon_name_id, vn.id)
      end

      vn.list_of_invalid_taxon_names.each do |s|
        s.update_columns(
          cached_valid_taxon_name_id: vn.id,
          cached_is_valid: !s.unavailable_or_invalid?)

        s.combination_list_self.each do |c|
          c.update_column(:cached_valid_taxon_name_id, vn.id)
        end
      end

    end

  end

  true
end

#subject_and_object_in_same_projectObject (protected)



335
336
337
338
339
340
341
# File 'app/models/taxon_name_relationship.rb', line 335

def subject_and_object_in_same_project
  if subject_taxon_name && object_taxon_name
    if subject_taxon_name.project_id != object_taxon_name.project_id
      errors.add(:base, 'one name is not in the same project as the other')
    end
  end
end

#subject_invalid_statusesObject (protected)



601
602
603
# File 'app/models/taxon_name_relationship.rb', line 601

def subject_invalid_statuses
  TAXON_NAME_CLASS_NAMES_UNAVAILABLE_AND_INVALID & self.subject_taxon_name.taxon_name_classifications.collect{|c| c.type_class.to_s}
end

#subject_propertiesArray of TaxonNameClassification

Returns the inferable TaxonNameClassification(s) added to the subject when this relationship is used !! Not implemented.

Returns:

  • (Array of TaxonNameClassification)

    the inferable TaxonNameClassification(s) added to the subject when this relationship is used !! Not implemented



195
196
197
# File 'app/models/taxon_name_relationship.rb', line 195

def subject_properties
  []
end

#subject_statusString

Returns the status inferred by the relationship to the subject name.

Returns:

  • (String)

    the status inferred by the relationship to the subject name



272
273
274
# File 'app/models/taxon_name_relationship.rb', line 272

def subject_status
  self.type_name.demodulize.underscore.humanize.downcase.gsub(/\d+/, ' \0 ').squish
end

#subject_status_connector_to_objectString

Returns the connecting word in the relationship from the subject name to object name.

Returns:

  • (String)

    the connecting word in the relationship from the subject name to object name



278
279
280
# File 'app/models/taxon_name_relationship.rb', line 278

def subject_status_connector_to_object
  ' of'
end

#subject_status_tagString

Returns a readable fragement combining status and connector.

Returns:

  • (String)

    a readable fragement combining status and connector



290
291
292
# File 'app/models/taxon_name_relationship.rb', line 290

def subject_status_tag
  subject_status + subject_status_connector_to_object
end

#sv_coordinated_taxaObject (protected)



613
614
615
616
617
618
619
620
621
# File 'app/models/taxon_name_relationship.rb', line 613

def sv_coordinated_taxa
  s = subject_taxon_name
  o = object_taxon_name
  s_new = s.lowest_rank_coordinated_taxon
  if s != s_new
    soft_validations.add(:subject_taxon_name_id, "Relationship should move from #{s.rank_class.rank_name} #{s.cached_html} to #{s_new.rank_class.rank_name} #{s_new.cached_html}",
                         success_message: "Relationship moved to  #{s_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
  end
end

#sv_coordinated_taxa_objectObject (protected)



623
624
625
626
627
628
629
630
631
# File 'app/models/taxon_name_relationship.rb', line 623

def sv_coordinated_taxa_object
  s = subject_taxon_name
  o = object_taxon_name
  o_new = o.lowest_rank_coordinated_taxon
  if o != o_new
    soft_validations.add(:object_taxon_name_id, "Relationship should move from #{o.rank_class.rank_name} #{o.cached_html} to #{o_new.rank_class.rank_name} #{o_new.cached_html}",
                         success_message: "Relationship moved to  #{o_new.rank_class.rank_name}", failure_message:  'Failed to update relationship')
  end
end

#sv_fix_combination_relationshipObject (protected)



665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'app/models/taxon_name_relationship.rb', line 665

def sv_fix_combination_relationship
  s = self.subject_taxon_name
  list = s.list_of_coordinated_names + [s]
  if s.rank_string =~ /Species/
    s_new = list.detect{|t| t.rank_class.rank_name == 'species'}
  elsif s.rank_string =~ /Genus/
    s_new = list.detect{|t| t.rank_class.rank_name == 'genus'}
  else
    s_new = s
  end
  if s != s_new && !s.nil?
    self.subject_taxon_name = s_new
    begin
      TaxonNameRelationship.transaction do
        self.save
        return true
      end
    rescue
    end
  end
  false
end

#sv_fix_coordinated_object_taxaObject (protected)



649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'app/models/taxon_name_relationship.rb', line 649

def sv_fix_coordinated_object_taxa
  o = self.object_taxon_name
  o_new = o.lowest_rank_coordinated_taxon
  if o != o_new
    self.object_taxon_name = o_new
    begin
      TaxonNameRelationship.transaction do
        self.save
        return true
      end
    rescue
    end
  end
  false
end

#sv_fix_coordinated_subject_taxaObject (protected)



633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# File 'app/models/taxon_name_relationship.rb', line 633

def sv_fix_coordinated_subject_taxa
  s = subject_taxon_name
  s_new = s.lowest_rank_coordinated_taxon
  if s != s_new
    self.subject_taxon_name = s_new
    begin
      TaxonNameRelationship.transaction do
        self.save
        return true
      end
    rescue
    end
  end
  false
end

#sv_fix_not_specific_relationshipObject (protected)



565
566
567
# File 'app/models/taxon_name_relationship.rb', line 565

def sv_fix_not_specific_relationship
  true # all validations moved to subclasses
end

#sv_fix_objective_synonym_relationshipObject (protected)



553
554
555
# File 'app/models/taxon_name_relationship.rb', line 553

def sv_fix_objective_synonym_relationship
  true # all validations moved to subclasses
end

#sv_fix_subject_parent_updateObject (protected)



581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'app/models/taxon_name_relationship.rb', line 581

def sv_fix_subject_parent_update
  res = false
  if TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
    obj = self.object_taxon_name
    subj = self.subject_taxon_name
    unless obj.parent_id == subj.parent_id
      subj.parent_id = obj.parent_id
      subj.rank_class = obj.rank_class
      begin
        TaxonName.transaction do
          subj.save!
          res = true
        end
      rescue
      end
    end
  end
  res
end

#sv_not_specific_relationshipObject (protected)



561
562
563
# File 'app/models/taxon_name_relationship.rb', line 561

def sv_not_specific_relationship
  true # all validations moved to subclasses
end

#sv_objective_synonym_relationshipObject (protected)



549
550
551
# File 'app/models/taxon_name_relationship.rb', line 549

def sv_objective_synonym_relationship
  true # all validations moved to subclasses
end

#sv_specific_relationshipObject (protected)



545
546
547
# File 'app/models/taxon_name_relationship.rb', line 545

def sv_specific_relationship
  true # all validations moved to subclasses
end

#sv_synonym_linked_to_valid_nameObject (protected)



569
570
571
572
573
574
575
576
577
578
579
# File 'app/models/taxon_name_relationship.rb', line 569

def sv_synonym_linked_to_valid_name
  #synonyms and misspellings should be linked to valid names
  if ::TAXON_NAME_RELATIONSHIP_NAMES_SYNONYM.include?(self.type_name)
    obj = self.object_taxon_name
    subj = self.subject_taxon_name
    if subj.rank_class.try(:nomenclatural_code) == :iczn && (obj.parent_id != subj.parent_id || obj.rank_class != subj.rank_class) &&  subj.cached_valid_taxon_name_id == obj.cached_valid_taxon_name_id
      soft_validations.add(:subject_taxon_name_id, "#{self.subject_status.capitalize}  #{subj.cached_html_name_and_author_year} should have the same parent and rank with  #{obj.cached_html_name_and_author_year}",
                           success_message: 'The parent was updated', failure_message:  'The parent was not updated')
    end
  end
end

#sv_synonym_relationshipObject (protected)



557
558
559
# File 'app/models/taxon_name_relationship.rb', line 557

def sv_synonym_relationship
  true # all validations moved to subclasses
end

#sv_validate_disjoint_objectObject (protected)



523
524
525
526
527
528
529
530
531
532
# File 'app/models/taxon_name_relationship.rb', line 523

def sv_validate_disjoint_object
  classifications = self.object_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
  disjoint_object_classes = self.type_class.disjoint_object_classes
  compare = disjoint_object_classes & classifications
  compare.each do |i|
    c = i.demodulize.underscore.humanize.downcase
    soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with the taxon status: '#{c}'")
    soft_validations.add(:object_taxon_name_id, "#{self.object_taxon_name.cached_html} has a conflicting status: '#{c}'")
  end
end

#sv_validate_disjoint_relationshipsObject (protected)



511
512
513
514
515
516
517
518
519
520
521
# File 'app/models/taxon_name_relationship.rb', line 511

def sv_validate_disjoint_relationships
  tname = self.type_name
  if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
    subject_relationships = TaxonNameRelationship.where_subject_is_taxon_name(self.subject_taxon_name).not_self(self)
    subject_relationships.each  do |i|
      if self.type_class.disjoint_taxon_name_relationships.include?(i.type_name)
        soft_validations.add(:type, "#{self.subject_status.capitalize} relationship is conflicting with another relationship: '#{i.subject_status}'")
      end
    end
  end
end

#sv_validate_disjoint_subjectObject (protected)



534
535
536
537
538
539
540
541
542
543
# File 'app/models/taxon_name_relationship.rb', line 534

def sv_validate_disjoint_subject
  classifications = self.subject_taxon_name.taxon_name_classifications.reload.map {|i| i.type_name}
  disjoint_subject_classes = self.type_class.disjoint_subject_classes
  compare = disjoint_subject_classes & classifications
  compare.each do |i|
    c = i.demodulize.underscore.humanize.downcase
    soft_validations.add(:type, "#{self.subject_status.capitalize} conflicting with the status: '#{c}'")
    soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.cached_html} has a conflicting status: '#{c}'")
  end
end

#sv_validate_priorityObject (protected)



605
606
607
# File 'app/models/taxon_name_relationship.rb', line 605

def sv_validate_priority
  true # all validations moved to subclasses
end

#sv_validate_required_relationshipsObject (protected)



502
503
504
505
506
507
508
509
# File 'app/models/taxon_name_relationship.rb', line 502

def sv_validate_required_relationships
  return true if self.subject_taxon_name.not_binominal?
  object_relationships = TaxonNameRelationship.where_object_is_taxon_name(self.object_taxon_name).not_self(self).collect{|r| r.type}
  required = self.type_class.required_taxon_name_relationships - object_relationships
  required.each do |r|
    soft_validations.add(:type, " Presence of #{self.subject_status} requires selection of #{r.demodulize.underscore.humanize.downcase}")
  end
end

#sv_validate_seniorityObject (protected)



609
610
611
# File 'app/models/taxon_name_relationship.rb', line 609

def sv_validate_seniority
  true # all validations moved to subclasses
end

#type_classObject



311
312
313
314
# File 'app/models/taxon_name_relationship.rb', line 311

def type_class
  r = read_attribute(:type).to_s
  TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r.safe_constantize : nil
end

#type_class=(value) ⇒ Object



307
308
309
# File 'app/models/taxon_name_relationship.rb', line 307

def type_class=(value)
  write_attribute(:type, value.to_s)
end

#type_nameString?

Returns the type of this relationship, IF the type is a valid name, else nil.

Returns:

  • (String, nil)

    the type of this relationship, IF the type is a valid name, else nil



302
303
304
305
# File 'app/models/taxon_name_relationship.rb', line 302

def type_name
  r = self.type
  TAXON_NAME_RELATIONSHIP_NAMES.include?(r) ? r : nil
end

#validate_object_and_subject_both_protonymsObject (protected)



432
433
434
435
436
437
438
439
# File 'app/models/taxon_name_relationship.rb', line 432

def validate_object_and_subject_both_protonyms
  if /TaxonNameRelationship::Combination::/.match(self.type)
    errors.add(:object_taxon_name_id, 'Not a Combination') if object_taxon_name.type != 'Combination'
  else
    errors.add(:object_taxon_name_id, 'Not a Protonym') if object_taxon_name.type == 'Combination'
  end
  errors.add(:subject_taxon_name_id, 'Not a Protonym') if subject_taxon_name.type == 'Combination' && self.type != 'TaxonNameRelationship::CurrentCombination'
end

#validate_object_must_equal_subject_for_uncertain_placementObject (protected)



374
375
376
377
378
# File 'app/models/taxon_name_relationship.rb', line 374

def validate_object_must_equal_subject_for_uncertain_placement
  if self.object_taxon_name_id != self.subject_taxon_name.parent_id && self.type_name == 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
    errors.add(:object_taxon_name_id, "The parent #{self.subject_taxon_name.parent.cached_html} and the Incertae Sedis placement (#{self.object_taxon_name.cached_html}) should match")
  end
end

#validate_rank_groupObject (protected)



424
425
426
427
428
429
430
# File 'app/models/taxon_name_relationship.rb', line 424

def validate_rank_group
  if self.type =~ /Hybrid/ && self.subject_taxon_name && self.object_taxon_name
    if self.subject_taxon_name.rank_class.parent != self.object_taxon_name.rank_class.parent
      errors.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the rank of hybrid (#{self.object_taxon_name.rank_class.rank_name})")
    end
  end
end

#validate_subject_and_object_are_not_identicalObject (protected)



368
369
370
371
372
# File 'app/models/taxon_name_relationship.rb', line 368

def validate_subject_and_object_are_not_identical
  if !self.object_taxon_name_id.nil? && self.object_taxon_name == self.subject_taxon_name
    errors.add(:object_taxon_name_id, "#{self.object_taxon_name.try(:cached_html)} should not refer to itself") unless self.type =~ /OriginalCombination/
  end
end

#validate_subject_and_object_ranksObject (protected)



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'app/models/taxon_name_relationship.rb', line 380

def validate_subject_and_object_ranks
  tname = self.type_name

  if tname =~ /TaxonNameRelationship::(Icnp|Icn|Iczn|Icvcn)/ && tname != 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement'
    rank_group = self.subject_taxon_name.rank_class.try(:parent)
    unless rank_group == self.object_taxon_name.rank_class.try(:parent)
      errors.add(:object_taxon_name_id, "Rank of related taxon should be in the #{rank_group.try(:rank_name)} rank group, not #{self.object_taxon_name.rank_class.try(:rank_name)}")
    end
  end

  if self.type_class.present? # only validate if it is set
    if object_taxon_name && object_taxon_name.rank_class
      if object_taxon_name.type == 'Protonym' || object_taxon_name.type == 'Hybrid'
        unless self.type_class.valid_object_ranks.include?(self.object_taxon_name.rank_string)
          errors.add(:object_taxon_name_id, "#{self.object_taxon_name.rank_class.rank_name.capitalize} rank of #{self.object_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
          errors.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.object_taxon_name.rank_class.rank_name} rank of #{self.object_taxon_name.cached_html}")
        end
      end
    end

    if subject_taxon_name && subject_taxon_name.rank_class
      if subject_taxon_name.type == 'Protonym' || subject_taxon_name.type == 'Hybrid'
        unless self.type_class.valid_subject_ranks.include?(self.subject_taxon_name.rank_string)
          soft_validations.add(:subject_taxon_name_id, "#{self.subject_taxon_name.rank_class.rank_name.capitalize} rank of #{self.subject_taxon_name.cached_html} is not compatible with the #{self.subject_status} relationship")
          soft_validations.add(:type, "Relationship #{self.subject_status} is not compatible with the #{self.subject_taxon_name.rank_class.rank_name} rank of #{self.subject_taxon_name.cached_html}")
        end
      end
    end
  end
end

#validate_subject_and_object_share_codeObject (protected)

TODO:

validate, that all the relationships in the table could be linked to relationships in classes (if those had changed)



362
363
364
365
366
# File 'app/models/taxon_name_relationship.rb', line 362

def validate_subject_and_object_share_code
  if object_taxon_name.type  == 'Protonym' && subject_taxon_name.type == 'Protonym'
    errors.add(:object_taxon_name_id, 'The related taxon is not in the same monenclatural group (ICZN, ICN, ICNP, ICVCN') if subject_taxon_name.rank_class.try(:nomenclatural_code) != object_taxon_name.rank_class.try(:nomenclatural_code)
  end
end

#validate_typeObject (protected)



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'app/models/taxon_name_relationship.rb', line 343

def validate_type
  # TODO: Remove, handled by STI
  if type && !TAXON_NAME_RELATIONSHIP_NAMES.include?(type.to_s)
    errors.add(:type, "'#{type}' is not a valid taxon name relationship")
  elsif self.type_class && object_taxon_name.class.to_s == 'Protonym' && !self.type_class.valid_object_ranks.include?(object_taxon_name.rank_string)
    errors.add(:type, "'#{type}' is not a valid taxon name relationship")
  end

  if object_taxon_name.class.to_s == 'Protonym' || object_taxon_name.class.to_s == 'Hybrid'
    errors.add(:type, "'#{type}' is not a valid taxon name relationship") if /TaxonNameRelationship::Combination::/.match(self.type)
  end

  if object_taxon_name.class.to_s == 'Combination'
    errors.add(:type, "'#{type}' is not a valid taxon name relationship") unless /TaxonNameRelationship::Combination::/.match(self.type)
  end
end

#validate_uniqueness_of_typification_objectObject (protected)

Protonym historically could be listed as a synonym to different taxa def validate_uniqueness_of_synonym_subject

if !self.type.nil? && /Synonym/.match(self.type_name) && !TaxonNameRelationship.where(subject_taxon_name_id: self.subject_taxon_name_id).with_type_contains('Synonym').not_self(self).empty?
  errors.add(:subject_taxon_name_id, 'Only one synonym relationship is allowed')
end

end



418
419
420
421
422
# File 'app/models/taxon_name_relationship.rb', line 418

def validate_uniqueness_of_typification_object
  if /Typification/.match(self.type_name) && !TaxonNameRelationship.where(object_taxon_name_id: self.object_taxon_name_id).with_type_contains('Typification').not_self(self).empty?
    errors.add(:object_taxon_name_id, 'Only one Type designation relationship is allowed')
  end
end