Class: DatasetRecord::DarwinCore::Taxon

Inherits:
DatasetRecord::DarwinCore show all
Defined in:
app/models/dataset_record/darwin_core/taxon.rb

Constant Summary collapse

KNOWN_KEYS_COMBINATIONS =
[
  %i{uninomial},
  %i{uninomial rank parent},
  %i{genus species},
  %i{genus species infraspecies},
  %i{genus subgenus species},
  %i{genus subgenus species infraspecies}
].freeze
PARSE_DETAILS_KEYS =
%i(uninomial genus species infraspecies).freeze
ORIGINAL_COMBINATION_RANKS =
{
  genus: 'TaxonNameRelationship::OriginalCombination::OriginalGenus',
  subgenus: 'TaxonNameRelationship::OriginalCombination::OriginalSubgenus',
  species: 'TaxonNameRelationship::OriginalCombination::OriginalSpecies',
  subspecies: 'TaxonNameRelationship::OriginalCombination::OriginalSubspecies',
  variety: 'TaxonNameRelationship::OriginalCombination::OriginalVariety',
  form: 'TaxonNameRelationship::OriginalCombination::OriginalForm'
}.freeze

Instance Attribute Summary

Attributes inherited from DatasetRecord

#metadata, #status

Instance Method Summary collapse

Methods inherited from DatasetRecord::DarwinCore

#get_field_mapping, #get_field_value, #get_fields_mapping, #get_tw_biocuration_groups, #get_tw_data_attribute_fields_for, #get_tw_fields_for, #get_tw_tag_fields_for, #normalize_value!, #term_value_changed

Methods inherited from DatasetRecord

#create_fields, #data_fields, #dataset_record_fields, #destroy_fields, #field_db_attributes, #fields_db_attributes, #frozen_fields?, #get_data_field, #initialize_data_fields, #set_data_field, #update_fields

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 Housekeeping

#has_polymorphic_relationship?

Methods inherited from ApplicationRecord

transaction_with_retry

Instance Method Details

#create_parent_element_hashHash{Symbol => TaxonName} (private)

Create a hash of parents from checklist

Returns:

  • (Hash{Symbol => TaxonName})

    hash of ranks and TaxonNames of genus and species rank parents



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
# File 'app/models/dataset_record/darwin_core/taxon.rb', line 548

def create_parent_element_hash
  parent = get_parent

  # if parent is root, return empty hash
  return {} unless parent

  parents = [parent]

  while (next_parent = find_by_taxonID(parents[-1].['parent']))
    parents << next_parent
  end

  # convert DatasetRecords into hash of rank, protonym pairs
  parent_elements = parents.to_h do |p|
    [
      # Key is rank (as set in checklist file)
      DatasetRecordField.where(dataset_record: p)
                        .at(get_field_mapping(:taxonRank))
        &.pick(:value)
        &.downcase&.to_sym,
      # value is Protonym
      TaxonName.find(p.['imported_objects']['taxon_name']['id'])
    ]

  end

  parent_elements.filter! { |p_rank, _| ORIGINAL_COMBINATION_RANKS.has_key?(p_rank) }
  parent_elements
end

#data_field_changed(index, value) ⇒ Object (private)

TODO add restage button/trigger when relevant fields change. Changing an id here means recalculating dependencies



631
632
633
634
635
# File 'app/models/dataset_record/darwin_core/taxon.rb', line 631

def data_field_changed(index, value)
  # if index == get_field_mapping(:parentNameUsageID) && status == "NotReady"
  #   self.status = "Ready" if %w[Ready Imported].include? get_parent&.status
  # end
end

#dependencies_imported?(taxon_id) ⇒ Boolean (private)

Check if all dependencies of a taxonID are imported

Returns:

  • (Boolean)


615
616
617
618
619
620
621
622
623
624
625
626
627
628
# File 'app/models/dataset_record/darwin_core/taxon.rb', line 615

def dependencies_imported?(taxon_id)
  dependency_taxon_ids = DatasetRecord::DarwinCore::Taxon.where(id: import_dataset.core_records_fields
                                                                                  .at(get_field_mapping(:taxonID))
                                                                                  .with_value(taxon_id.to_s)
                                                                                  .select(:dataset_record_id)
  ).pick(:metadata)['dependencies']

  DatasetRecord::DarwinCore::Taxon.where(id: import_dataset.core_records_fields
                                                           .at(get_field_mapping(:taxonID))
                                                           .with_values(dependency_taxon_ids.map { |d| d.to_s })
                                                           .select(:dataset_record_id)
  ).where(status: 'Imported').count == dependency_taxon_ids.length

end

#find_by_taxonID(taxon_id) ⇒ Object (private)



597
598
599
600
601
602
603
# File 'app/models/dataset_record/darwin_core/taxon.rb', line 597

def find_by_taxonID(taxon_id)
  DatasetRecord::DarwinCore::Taxon.where(id: import_dataset.core_records_fields
                                                           .at(get_field_mapping(:taxonID))
                                                           .with_value(taxon_id.to_s)
                                                           .select(:dataset_record_id)
  ).first
end

#get_original_combinationObject (private)



588
589
590
591
592
593
594
# File 'app/models/dataset_record/darwin_core/taxon.rb', line 588

def get_original_combination
  DatasetRecord::DarwinCore::Taxon.where(id: import_dataset.core_records_fields
                                                           .at(get_field_mapping(:taxonID))
                                                           .with_value(get_field_value(:originalNameUsageID))
                                                           .select(:dataset_record_id)
  ).first
end

#get_parentObject (private)



579
580
581
582
583
584
585
# File 'app/models/dataset_record/darwin_core/taxon.rb', line 579

def get_parent
  DatasetRecord::DarwinCore::Taxon.where(id: import_dataset.core_records_fields
                                                           .at(get_field_mapping(:taxonID))
                                                           .with_value(get_field_value(:parentNameUsageID))
                                                           .select(:dataset_record_id)
  ).first
end

#get_taxon_name_from_taxon_id(taxon_id) ⇒ TaxonName (private)

Returns:



606
607
608
609
610
611
612
# File 'app/models/dataset_record/darwin_core/taxon.rb', line 606

def get_taxon_name_from_taxon_id(taxon_id)
  TaxonName.find(DatasetRecord::DarwinCore::Taxon.where(id: import_dataset.core_records_fields
                                                                          .at(get_field_mapping(:taxonID))
                                                                          .with_value(taxon_id.to_s)
                                                                          .select(:dataset_record_id)
  ).pick(:metadata)['imported_objects']['taxon_name']['id'])
end

#import(dwc_data_attributes = {}) ⇒ Object

rubocop:disable Metric/MethodLength



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
# File 'app/models/dataset_record/darwin_core/taxon.rb', line 26

def import(dwc_data_attributes = {})
  super
  begin
    DatasetRecord.transaction(requires_new: true) do
      self..delete('error_data')

      nomenclature_code = get_field_value('nomenclaturalCode')&.downcase&.to_sym || import_dataset.default_nomenclatural_code
      unless Ranks::CODES.include?(nomenclature_code)
        raise DarwinCore::InvalidData.new(
          { "nomenclaturalCode": ["Unrecognized nomenclatural code #{get_field_value('nomenclaturalCode')}"] }
        )
      end
      # parse_results_details = Biodiversity::Parser.parse(get_field_value('scientificName') || '')[:details]&.values&.first

      parse_results = Biodiversity::Parser.parse(get_field_value(:scientificName) || '')
      parse_results_details = parse_results[:details]
      parse_results_details = (parse_results_details.keys - PARSE_DETAILS_KEYS).empty? ? parse_results_details.values.first : nil if parse_results_details

      raise DarwinCore::InvalidData.new({
                                          "scientificName": parse_results[:qualityWarnings] ?
                                                              parse_results[:qualityWarnings].map { |q| q[:warning] } :
                                                              ['Unable to parse scientific name. Please make sure it is correctly spelled.']
                                        }) unless (1..3).include?(parse_results[:quality]) && parse_results_details&.is_a?(Hash)

      raise 'UNKNOWN NAME DETAILS COMBINATION' unless KNOWN_KEYS_COMBINATIONS.include?(parse_results_details.keys - [:authorship])

      name_key = parse_results_details[:uninomial] ? :uninomial : (parse_results_details.keys - [:authorship]).last
      name_details = parse_results_details[name_key]

      name = name_details.kind_of?(Array) ? name_details.first[:value] : name_details

      authorship = parse_results_details.dig(:authorship, :normalized) || get_field_value('scientificNameAuthorship')

      author_name = nil
      year = nil

      # split authorship into name and year
      if authorship.present?
        if nomenclature_code == :iczn
          if (authorship_matchdata = authorship.match(/\(?(?<author>.+),? (?<year>\d{4})?\)?/))

            # regex will include comma, no easy way around it
            author_name = authorship_matchdata[:author].delete_suffix(',')
            year = authorship_matchdata[:year]

            # author name should be wrapped in parentheses if the verbatim authorship was
            if authorship.start_with?('(') and authorship.end_with?(')')
              author_name = '(' + author_name + ')'
            end
          end

        else
          # Fall back to simple name + date parsing if not iczn
          author_name = Utilities::Strings.verbatim_author(authorship)
          year = Utilities::Strings.year_of_publication(authorship)
        end
      end

      if year && (name_published_in_year = get_field_value('namePublishedInYear')) &&
        year != name_published_in_year
        raise DarwinCore::InvalidData.new(
          { "namePublishedInYear": ["parsed year from scientificName or scientificNameAuthorship (#{year}) "\
                                    "does not match namePublishedInYear (#{name_published_in_year})"]
          })
      end
      year ||= get_field_value('namePublishedInYear')

      # TODO validate that rank is a real rank, otherwise Combination will crash on find_or_initialize_by
      rank = get_field_value('taxonRank')
      is_hybrid = ['is_hybrid'] # TODO: NO...

      if ['parent'].nil?
        if self.import_dataset.use_existing_hierarchy?
          protonym_attributes = { name:, #
                                cached: get_field_value(:scientificName),
                                rank_class: Ranks.lookup(nomenclature_code, rank),
                                verbatim_author: author_name,
                                year_of_publication: year}
          potential_protonyms = TaxonName.where(protonym_attributes.merge({project:})) # merged project here so data is not leaked in error messages.

          if potential_protonyms.count == 1
            parent = potential_protonyms.first.parent
          elsif potential_protonyms.count > 1
            matching_protonyms = potential_protonyms.map { |proto| "[id: #{proto.id} #{proto.cached_html_name_and_author_year}]" }.join(', ')
            raise DarwinCore::InvalidData.new(
              { "parentNameUsageID": ["parent ID is blank, 'use existing taxon hierarchy' is enabled in settings, " \
                                        "and multiple TaxonNames matched #{protonym_attributes}: #{matching_protonyms}"] })
          else
            raise DarwinCore::InvalidData.new(
              { "parentNameUsageID": ["parent ID is blank, 'use existing taxon hierarchy' is enabled in settings, " \
                                        "and no TaxonNames matched #{protonym_attributes}"] })
          end
        else
          parent = project.root_taxon_name
        end
      else
        parent = TaxonName.find(get_parent.['imported_objects']['taxon_name']['id'])
      end

      if ['type'] == 'protonym'

        # if the name is a synonym, we should use the valid taxon's rank and parent
        # I *think* it's ok to do the same for homonyms, since we could have case where homonym's parent is a synonym,
        # and it has been moved from species to subspecies rank.
        # we fetch parent from the source file when calculating original combination, so it's ok to modify it here.
        if ['has_external_accepted_name']
          valid_name = get_taxon_name_from_taxon_id(get_field_value(:acceptedNameUsageID))
          rank = valid_name.rank
          parent = valid_name.parent
        elsif parent.is_a? Combination # this can happen when the name is unavailable, it's not a synonym so it doesn't point to anything else
          parent = parent.finest_protonym
        end

        taxon_name = Protonym.find_or_initialize_by({
          name:,
          parent:,
          rank_class: Ranks.lookup(nomenclature_code, rank),
          # also_create_otu: false,
          verbatim_author: author_name,
          year_of_publication: year,
          project:
        })

        unless taxon_name.persisted?
          taxon_name.taxon_name_classifications.build(type: TaxonNameClassification::Icn::Hybrid) if is_hybrid
          taxon_name.data_attributes.build(import_predicate: 'DwC-A import metadata', type: 'ImportAttribute', value: {
            scientificName: get_field_value('scientificName'),
            scientificNameAuthorship: get_field_value('scientificNameAuthorship'),
            taxonRank: get_field_value('taxonRank'),
            metadata:
          })

        end

        # make OC relationships to OC ancestors
        # can't make original combination with Root or if matching pre-existing taxon name
        # Do not make original combination if we assumed the value.
        if ['parent'].present? && (.fetch('create_original_combination', true) == true)

          # Loop through parents of original combination based on parentNameUsageID, not TW parent
          # this way we get the name as intended, not with any valid/current names
          original_combination_parents = [find_by_taxonID(get_original_combination.['parent'])].compact

          # build list of parent DatasetRecords
          if original_combination_parents.size > 0
            while (next_parent = find_by_taxonID(original_combination_parents[-1]&.['parent']))
              original_combination_parents << next_parent
            end
          end

          # in cases where the taxon original combination is subgenus of self eg Sima (Sima), the first parent of the list
          # should be dropped because it hasn't been imported yet
          original_combination_parents = original_combination_parents.drop_while {|p| p.status != 'Imported' }

          # convert DatasetRecords into list of Protonyms
          original_combination_parents.map! do |p|
            h = {}
            h[:protonym] = TaxonName.find(p.['imported_objects']['taxon_name']['id'])
            h[:rank] = DatasetRecordField.where(dataset_record_id: p)
                                         .at(get_field_mapping(:taxonRank))
                                         .pick(:value)
                                         .downcase
            h
          end

          original_combination_parents.each do |ancestor|
            ancestor_protonym = ancestor[:protonym]
            ancestor_rank = ancestor[:rank]

            # If OC parent is combination, need to create relationship for lowest element
            if ancestor_protonym.is_a?(Combination)
              ancestor_protonym = ancestor[:protonym].finest_protonym
            end

            if (rank_in_type = ORIGINAL_COMBINATION_RANKS[ancestor_rank&.downcase&.to_sym])

              # if the subgenus is newer than taxon_name's authorship, skip it (the name must have been classified in the subgenus later)
              next if ancestor_rank&.downcase&.to_sym == :subgenus &&
                !ancestor_protonym.year_integer.nil? &&
                !taxon_name.year_integer.nil? &&
                ancestor_protonym.year_integer > taxon_name.year_integer

              taxon_name.save!
              TaxonNameRelationship.find_or_create_by!(type: rank_in_type, subject_taxon_name: ancestor_protonym, object_taxon_name: taxon_name)
            end
          end
        end

        # don't create OC relationship with self if OC was assumed, default to true for any datasets
        # created before this feature existed (since creating OC was always expected then)
        if .fetch('create_original_combination', true)

          # when creating the OC record pointing to self,
          # can't assume OC rank is same as valid rank, need to look at OC row to find real rank
          # This is easier for the end-user than adding OC to protonym when importing the OC row,
          # but might be more complex to code

          # get OC dataset_record_id so we can pull the taxonRank from it.
          oc_dataset_record_id = import_dataset.core_records_fields
                                               .at(get_field_mapping(:taxonID))
                                               .with_value(get_field_value(:originalNameUsageID))
                                               .pick(:dataset_record_id)

          oc_protonym_rank = import_dataset.core_records_fields
                                           .where(dataset_record_id: oc_dataset_record_id)
                                           .at(get_field_mapping(:taxonRank))
                                           .pick(:value)
                                           .downcase.to_sym

          if ORIGINAL_COMBINATION_RANKS.has_key?(oc_protonym_rank)
            TaxonNameRelationship.create_with(subject_taxon_name: taxon_name).find_or_create_by!(
              type: ORIGINAL_COMBINATION_RANKS[oc_protonym_rank],
              object_taxon_name: taxon_name)

            # detect if current name rank is genus and original combination is with self at subgenus level, eg Aus (Aus)
            # if so, generate OC relationship with genus (since oc_protonym_rank will be subgenus)
            if oc_protonym_rank == :subgenus && get_field_value('taxonRank').downcase == 'genus' &&
              (get_original_combination&.['parent'] == get_field_value('taxonID'))
              TaxonNameRelationship.create_with(subject_taxon_name: taxon_name).find_or_create_by!(
                type: ORIGINAL_COMBINATION_RANKS[:genus],
                object_taxon_name: taxon_name)
            end
          end
        end

        # if taxonomicStatus is a synonym or homonym, create the relationship to acceptedNameUsageID
        if ['has_external_accepted_name']
          valid_name = get_taxon_name_from_taxon_id(get_field_value(:acceptedNameUsageID))

          synonym_classes = {
            iczn: {
              synonym: 'TaxonNameRelationship::Iczn::Invalidating::Synonym',
              homonym: 'TaxonNameRelationship::Iczn::Invalidating::Synonym::Objective::ReplacedHomonym',
              misspelling: 'TaxonNameRelationship::Iczn::Invalidating::Usage::Misspelling',
              'original misspelling':  'TaxonNameRelationship::Iczn::Invalidating::Usage::IncorrectOriginalSpelling',

              # invalid can be either a relationship or classification, depending on if 'has_external_accepted_name' is true or not
              invalid: 'TaxonNameRelationship::Iczn::Invalidating'
            },
            # TODO support other nomenclatural codes
            # icnp: {
            #   synonym: "TaxonNameRelationship::Icnp::Unaccepting::Synonym",
            #   homonym: "TaxonNameRelationship::Icnp::Unaccepting::Homonym"
            # },
            # icn: {
            #   synonym: "TaxonNameRelationship::Icn::Unaccepting::Synonym",
            #   homonym: "TaxonNameRelationship::Icn::Unaccepting::Homonym"
            # }
          }.freeze

          if (status = get_field_value(:taxonomicStatus)&.downcase)

            # workaround to handle cases where Protonym is a synonym, but row marked as synonym has different rank/parent
            # so we use a row that does as the protonym instead. That row could have some other status, but
            # we know it's a synonym.
            if ['is_synonym']
              status = :synonym
            end

            type = synonym_classes[nomenclature_code][status.to_sym]


            raise DarwinCore::InvalidData.new(
              { "taxonomicStatus": ['acceptedNameUsageID refers to a different protonym, ' \
                "but status #{status} did not match synonym, homonym, invalid, misspelling or original misspelling."] }) if type.nil?

            taxon_name.taxon_name_relationships.find_or_initialize_by(object_taxon_name: valid_name, type:)

            if status.to_s == 'synonym'
              # if synonym and not same rank as valid, and not original combination,
              # create a combination with the old parent and rank

              if (old_rank = get_field_value('taxonRank').downcase) != rank.downcase &&
                ['original_combination'] != get_field_value('taxonID') &&
                ORIGINAL_COMBINATION_RANKS.has_key?(old_rank.downcase.to_sym)

                # save taxon so we can create a combination
                taxon_name.save!

                # stolen from combination handling portion of code
                parent_elements = create_parent_element_hash.transform_values {|v| v.is_a?(Combination) ? v.finest_protonym : v}

                combination_attributes = { **parent_elements }
                combination_attributes[old_rank.downcase] = taxon_name if old_rank

                # Can't use find_or_initialize_by because of dynamic parameters, causes query to fail because ranks are not columns in db
                # => PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "genus"
                # LINE 1: ..."taxon_names" WHERE "taxon_names"."type" = $1 AND "genus"."i...

                taxon_combination_name = Combination.matching_protonyms(**combination_attributes.transform_values { |v| v.id }).first
                taxon_combination_name = Combination.create!(combination_attributes) if taxon_combination_name.nil?
              end
            end

            # Add homonym status (if applicable)
            if status == 'homonym'
              taxon_name.taxon_name_classifications.find_or_initialize_by(type: 'TaxonNameClassification::Iczn::Available::Invalid::Homonym')
            end

          else
            raise DarwinCore::InvalidData.new({ "taxonomicStatus": ['No taxonomic status, but acceptedNameUsageID has different protonym'] })
          end

          # if taxonomicStatus is a homonym, invalid, unavailable, excluded, create the status
          # if it's incertae sedis, create the relationship
          # TODO why have an OR with nil? shouldn't the first condition check that?
        elsif get_field_value(:taxonomicStatus) != 'valid' || get_field_value(:taxonomicStatus).nil?
          status_types = {
            invalid: 'TaxonNameClassification::Iczn::Available::Invalid',
            unavailable: 'TaxonNameClassification::Iczn::Unavailable',
            excluded: 'TaxonNameClassification::Iczn::Unavailable::Excluded',
            'nomen nudum': 'TaxonNameClassification::Iczn::Unavailable::NomenNudum',
            ichnotaxon: 'TaxonNameClassification::Iczn::Fossil::Ichnotaxon',
            fossil: 'TaxonNameClassification::Iczn::Fossil',
            'nomen dubium': 'TaxonNameClassification::Iczn::Available::Valid::NomenDubium'
          }.freeze

          if (status = get_field_value(:taxonomicStatus)&.downcase)

            # if name in incertae sedis, attach to finest level known (usually parent) and add TaxonNameRelationship
            if status == 'incertae sedis'

              # if user has provided a `TW:TaxonNameRelationship:incertae_sedis_in_rank` field, use that to determine
              # which rank of parent should be used for I.S. relationship
              if (verbatim_is_rank = get_field_value('TW:TaxonNameRelationship:incertae_sedis_in_rank'))
                # must save here so that `ancestor_at_rank` works
                # (otherwise could use `ancestors_through_parents` and check rank manually)
                taxon_name.save
                incertae_sedis_parent = taxon_name.ancestor_at_rank(verbatim_is_rank.downcase)

                if incertae_sedis_parent.nil?
                  available_parent_ranks = taxon_name.ancestors.map { |a| "#{a.rank}: #{a.name}" }.join(', ')
                  raise DarwinCore::InvalidData.new({ "TW:TaxonNameRelationship:incertae_sedis_in_rank":
                                                        ["Taxon #{taxon_name.name} does not have a parent at rank #{verbatim_is_rank}.
                                                          Available ancestors are #{available_parent_ranks}.".squish] })
                end

                # Parent should be same as incertae sedis object_taxon
                # Supplying a parent taxonID with a different rank than the incertae sedis parent
                # will an original combination relationship with the old parent, which
                # the ui will render as [Aus] bus, (where the incertae sedis parent is Cus)
                taxon_name.parent = incertae_sedis_parent

              else
                # if parent has uncertain placement in rank, taxon's parent should be changed to whichever taxon the parent's UncertainRelationship is with
                incertae_sedis_parent = parent.iczn_uncertain_placement
                # if parent doesn't have uncertain placement, make relationship with family or subfamily (FamilyGroup)
                incertae_sedis_parent ||= taxon_name.ancestors.with_base_of_rank_class('NomenclaturalRank::Iczn::FamilyGroup').first

                # Parent should be same as incertae sedis object_taxon
                taxon_name.parent = incertae_sedis_parent
              end

              taxon_name.taxon_name_relationships.find_or_initialize_by(
                object_taxon_name: incertae_sedis_parent,
                type: 'TaxonNameRelationship::Iczn::Validating::UncertainPlacement')

            else
              type = status_types[status.to_sym]

              raise DarwinCore::InvalidData.new(
                { "taxonomicStatus": ["Couldn't find a status that matched #{status}.",
                                      "Possible statuses: [#{status_types.keys.join(", ")}]"] }) if type.nil?

              taxon_name.taxon_name_classifications.find_or_initialize_by(type:)
            end
          end
        end

        # Taxon status might not be "fossil" if synonym, homonym, incertae sedis, etc.
        if get_field_value('TW:TaxonNameClassification:Iczn:Fossil')
          taxon_name.taxon_name_classifications.find_or_initialize_by(type: 'TaxonNameClassification::Iczn::Fossil')
        end

        # add gender or part of speech classification if given
        if (gender = get_field_value('TW:TaxonNameClassification:Latinized:Gender'))
          gender_types = {
            masculine: 'TaxonNameClassification::Latinized::Gender::Masculine',
            feminine: 'TaxonNameClassification::Latinized::Gender::Feminine',
            neuter: 'TaxonNameClassification::Latinized::Gender::Neuter'
          }.freeze

          gender_classification = gender_types[gender.downcase.to_sym]

          raise DarwinCore::InvalidData.new({ "TW:TaxonNameClassification:Latinized:Gender": ["Gender #{gender.downcase} is not one of: masculine, feminine, neuter."] }) if gender_classification.nil?

          taxon_name.taxon_name_classifications.find_or_initialize_by(type: gender_classification)

        elsif (part_of_speech = get_field_value('TW:TaxonNameClassification:Latinized:PartOfSpeech'))
          parts_of_speech_types = {
            adjective: 'TaxonNameClassification::Latinized::PartOfSpeech::Adjective',
            participle: 'TaxonNameClassification::Latinized::PartOfSpeech::Participle',
            'noun in apposition': 'TaxonNameClassification::Latinized::PartOfSpeech::NounInApposition',
            'noun in genitive case': 'TaxonNameClassification::Latinized::PartOfSpeech::NounInGenitiveCase'
          }.freeze

          part_of_speech_classification = parts_of_speech_types[part_of_speech.downcase.to_sym]

          raise DarwinCore::InvalidData.new({ "TW:TaxonNameClassification:Latinized:": ["PartOfSpeech #{part_of_speech.downcase} is not one of: adjective, participle, noun in apposition, noun in genitive case."] }) if part_of_speech_classification.nil?

          taxon_name.taxon_name_classifications.find_or_initialize_by(type: part_of_speech_classification)

          # if taxon has different original combination conjugation, and genus has gender, use OC name.
          # It will be conjugated correctly with new genus and the original combination will use the correct conjugation

          if oc_dataset_record_id != self.id &&
            taxon_name.is_species_rank? &&
            taxon_name.ancestor_at_rank('genus').gender_name

            oc_name = import_dataset.core_records_fields
                          .where(dataset_record_id: oc_dataset_record_id)
                          .at(get_field_mapping(:scientificName))
                          .pick(:value)

            finest_oc_name = oc_name.split.last

            # check if OC name is conjugated differently, then see if current name can be conjugated into oc name
            if finest_oc_name != name and taxon_name.predict_three_forms.values.include?(finest_oc_name)
              taxon_name.name = finest_oc_name
            end
          end
        end

      elsif ['type'] == 'combination'

        # get protonym from staging metadata
        protonym_record = find_by_taxonID(['protonym_taxon_id'])
        # current_name_record = find_by_taxonID(get_field_value(:originalNameUsageID))

        current_name = Protonym.find(protonym_record.['imported_objects']['taxon_name']['id'])

        # because Combination uses named arguments, we need to get the ranks of the parent names to create the combination
        if parent.is_a?(Combination)
          parent_elements = parent.combination_taxon_names.index_by { |protonym| protonym.rank }

        else
          # parent is a protonym, look at parents in checklist to build combination
          parent_elements = create_parent_element_hash
        end

        combination_attributes = { **parent_elements }
        combination_attributes[rank.downcase] = current_name if rank

        # Can't use find_or_initialize_by because of dynamic parameters, causes query to fail because ranks are not columns in db
        # => PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "genus"
        # LINE 1: ..."taxon_names" WHERE "taxon_names"."type" = $1 AND "genus"."i...

        taxon_name = Combination.matching_protonyms(**combination_attributes.transform_values { |v| v.id }).first
        taxon_name = Combination.new(combination_attributes) if taxon_name.nil?

      else
        raise DarwinCore::InvalidData.new({ "originalNameUsageID": ['Could not determine if name is protonym or combination'] })
      end

      if taxon_name.save
        # TODO add relationships and combinations to this hash
        self.[:imported_objects] = { taxon_name: { id: taxon_name.id } }
        self.status = 'Imported'
      else
        self.status = 'Errored'

        # if error exist with taxon_name_relationships, add their errors under the main attribute (:taxon_name_relationships)
        # eg:
        #   original error: {:taxon_name_relationships=>["is invalid"]}
        #   TNR error: [{:object_taxon_name_id=>["The parent Miomyrmecini and the Incertae Sedis placement (Dolichoderinae) should match"]}]
        #   resulting message: {:taxon_name_relationships=>["is invalid", "The parent Miomyrmecini and the Incertae Sedis placement (Dolichoderinae) should match"]}
        # TODO expand to other relationships, like classifications
        if taxon_name.errors.messages[:taxon_name_relationships]
          # skip relationships with no errors
          errored_relationships = taxon_name.taxon_name_relationships.reject { |r| r.errors.empty? }

          # add error messages to taxon_name.errors[:taxon_name_relationships]
          errored_relationships.each { |r| r.errors.map { |error| taxon_name.errors.add(:taxon_name_relationships, message: error.message) } }
        end

        self.[:error_data] = {
          messages: taxon_name.errors.messages
        }
      end

      save!

      if self.status == 'Imported'
        # loop over dependants, see if all other dependencies are met, if so mark them as ready
        ['dependants'].each do |dependant_taxonID|
          if dependencies_imported?(dependant_taxonID)
            DatasetRecord::DarwinCore::Taxon.where(status: 'NotReady',
                                                   id: import_dataset.core_records_fields
                                                                     .at(get_field_mapping(:taxonID))
                                                                     .where(value: dependant_taxonID)
                                                                     .select(:dataset_record_id)
            ).first&.update!(status: 'Ready')
          end
        end
      end
    end
  rescue DarwinCore::InvalidData => invalid
    self.status = 'Errored'
    self.['error_data'] = { messages: invalid.error_data }
  rescue ActiveRecord::RecordInvalid => invalid
    self.status = 'Errored'
    self.['error_data'] = {
      messages: invalid.record.errors.messages
    }
  rescue StandardError => e
    raise if Rails.env.development?
    self.status = 'Failed'
    self.[:exception_data] = {
      message: e.message,
      backtrace: e.backtrace
    }
  ensure
    save!
  end

  self
end